Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature(types,app): Added swap config endpoint and types #3164

Draft
wants to merge 2 commits into
base: develop
Choose a base branch
from
Draft
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
13 changes: 13 additions & 0 deletions packages/api/src/app/api/app-api-maker.mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import {App} from '@yoroi/types'
import {mockGetFrontendFees} from './frontend-fees.mocks'
import {mockGetSwapConfig} from './swap-config.mocks'

const loading = () => new Promise(() => {})
const unknownError = () => Promise.reject(new Error('Unknown error'))
Expand All @@ -27,6 +28,18 @@ const getFrontendFees = {
},
}

const getSwapConfig = {
success: () => Promise.resolve(mockGetSwapConfig.withFees),
delayed: (timeout?: number) =>
delayedResponse({data: mockGetSwapConfig.withFees, timeout}),
empty: () => Promise.resolve(mockGetSwapConfig.empty),
loading,
error: {
unknown: unknownError,
},
}

export const mockAppApi: App.Api = {
getFrontendFees: getFrontendFees.success,
getSwapConfig: getSwapConfig.success,
} as const
4 changes: 4 additions & 0 deletions packages/api/src/app/api/app-api-maker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {Fetcher, fetcher} from '@yoroi/common'
import {App} from '@yoroi/types'

import {getFrontendFees as getFrontendFeesWrapper} from './frontend-fees'
import {getSwapConfigWrapper} from './swap-config'

export const appApiMaker = ({
baseUrl,
Expand All @@ -10,9 +11,12 @@ export const appApiMaker = ({
baseUrl: string
request?: Fetcher
}): Readonly<App.Api> => {
// @deprecated in favour of getSwapConfig
const getFrontendFees = getFrontendFeesWrapper(baseUrl, request)
const getSwapConfig = getSwapConfigWrapper(baseUrl, request)

return {
getFrontendFees,
getSwapConfig,
} as const
}
3 changes: 3 additions & 0 deletions packages/api/src/app/api/frontend-fees.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import {z} from 'zod'
import {createTypeGuardFromSchema, fetcher, Fetcher} from '@yoroi/common'
import {App} from '@yoroi/types'

/**
* @deprecated in favour of getSwapConfig
*/
export const getFrontendFees =
(baseUrl: string, request: Fetcher = fetcher) =>
async (): Promise<App.FrontendFeesResponse> => {
Expand Down
77 changes: 77 additions & 0 deletions packages/api/src/app/api/swap-config.mocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/* istanbul ignore file */

import {App} from '@yoroi/types'

const empty: App.SwapConfigResponse = {
aggregators: {},
liquidityProvidersEnabled: [],
isSwapEnabled: false,
} as const

export const withFees: App.SwapConfigResponse = {
aggregators: {
muesliswap: {
isEnabled: true,
discountTokenId:
'afbe91c0b44b3040e360057bf8354ead8c49c4979ae6ab7c4fbdc9eb.4d494c4b7632',
frontendFeeTiers: [
{
primaryTokenValueThreshold: '100000000',
secondaryTokenBalanceThreshold: '5000',
variableFeeMultiplier: 0.00015,
fixedFee: '1000000',
},
{
primaryTokenValueThreshold: '100000000',
secondaryTokenBalanceThreshold: '2000',
variableFeeMultiplier: 0.0002,
fixedFee: '1000000',
},
{
primaryTokenValueThreshold: '100000000',
secondaryTokenBalanceThreshold: '1000',
variableFeeMultiplier: 0.00025,
fixedFee: '1000000',
},
{
primaryTokenValueThreshold: '100000000',
secondaryTokenBalanceThreshold: '500',
variableFeeMultiplier: 0.0003,
fixedFee: '1000000',
},
{
primaryTokenValueThreshold: '100000000',
secondaryTokenBalanceThreshold: '100',
variableFeeMultiplier: 0.00035,
fixedFee: '1000000',
},
{
primaryTokenValueThreshold: '100000000',
secondaryTokenBalanceThreshold: '0',
variableFeeMultiplier: 0.0005,
fixedFee: '1000000',
},
],
},
dexhunter: {
isEnabled: false,
discountTokenId:
'95a427e384527065f2f8946f5e86320d0117839a5e98ea2c0b55fb00.48554e54',
frontendFeeTiers: [],
},
},
liquidityProvidersEnabled: [
'minswap',
'wingriders',
'sundaeswap',
'muesliswap',
'muesliswap_v2',
'vyfi',
],
isSwapEnabled: true,
}

export const mockGetSwapConfig = {
empty,
withFees,
} as const
41 changes: 41 additions & 0 deletions packages/api/src/app/api/swap-config.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import {getSwapConfigWrapper, isSwapConfigResponse} from './swap-config'
import {mockGetSwapConfig as mocks} from './swap-config.mocks'

describe('isSwapConfigResponse', () => {
it.each`
desc | data | expected
${'with fess'} | ${mocks.withFees} | ${true}
${'empty'} | ${mocks.empty} | ${true}
`(`should be $expected when $desc`, ({data, expected}) => {
expect(isSwapConfigResponse(data)).toEqual(expected)
})
})

describe('getSwapConfig', () => {
it('success', async () => {
const fetch = jest.fn().mockResolvedValue(mocks.withFees)
const getSwapConfig = getSwapConfigWrapper('https://localhost', fetch)
const result = await getSwapConfig()
expect(result).toEqual(mocks.withFees)
})

it('throws if response is not valid', async () => {
const fetch = jest.fn().mockResolvedValue({x: 1})
const getSwapConfig = getSwapConfigWrapper('https://localhost', fetch)
await expect(getSwapConfig()).rejects.toThrow(
'Invalid swap config response',
)
})

it('throws any other error', async () => {
const networkError = {error: 'network'}
const fetch = jest.fn().mockRejectedValue(networkError)
const getSwapConfig = getSwapConfigWrapper('https://localhost', fetch)
await expect(getSwapConfig()).rejects.toEqual(networkError)
})

it('no deps for coverage', () => {
const getSwapConfig = getSwapConfigWrapper('https://localhost')
expect(getSwapConfig).toBeDefined()
})
})
66 changes: 66 additions & 0 deletions packages/api/src/app/api/swap-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import {z} from 'zod'
import {createTypeGuardFromSchema, fetcher, Fetcher} from '@yoroi/common'
import {App} from '@yoroi/types'

export const getSwapConfigWrapper =
(baseUrl: string, request: Fetcher = fetcher) =>
async (): Promise<App.SwapConfigResponse> => {
return request<App.SwapConfigResponse>({
url: `${baseUrl}/v1/swap/config`,
data: undefined,
method: 'GET',
headers: {'Content-Type': 'application/json'},
}).then((response) => {
const parsedResponse = parseSwapConfigResponse(response)
if (!parsedResponse)
return Promise.reject(new Error('Invalid swap config response'))

return Promise.resolve(parsedResponse)
})
}

const SwapConfigAggregatorSchema = z.union([
z.literal('muesliswap'),
z.literal('dexhunter'),
])

const AppSwapFrontendFeesTierSchema = z.object({
primaryTokenValueThreshold: z.string(),
secondaryTokenBalanceThreshold: z.string(),
variableFeeMultiplier: z.number(),
fixedFee: z.string(),
})

const AppSwapConfigResponseSchema = z
.object({
aggregators: z.record(
z.object({
isEnabled: z.boolean(),
frontendFeeTiers: z.array(AppSwapFrontendFeesTierSchema),
discountTokenId: z.string(),
}),
),
liquidityProvidersEnabled: z.array(z.string()),
isSwapEnabled: z.boolean(),
})
.refine(
(object) => {
const keys = Object.keys(object.aggregators)
return keys.every(
(key) => SwapConfigAggregatorSchema.safeParse(key).success,
)
},
{
message: "Aggregator key must be 'muesliswap', 'dexhunter'",
},
)

export const isSwapConfigResponse = createTypeGuardFromSchema(
AppSwapConfigResponseSchema,
)

export const parseSwapConfigResponse = (
data: unknown,
): App.SwapConfigResponse | undefined => {
return isSwapConfigResponse(data) ? data : undefined
}
13 changes: 13 additions & 0 deletions packages/types/src/api/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {SwapAggregator} from '../swap/aggregator'

export interface AppApi {
getFrontendFees(): Promise<AppFrontendFeesResponse>
getSwapConfig(): Promise<AppSwapConfigResponse>
}

export type AppFrontendFeesResponse = Readonly<{
Expand All @@ -15,3 +16,15 @@ export type AppFrontendFeeTier = Readonly<{
variableFeeMultiplier: number
fixedFee: BalanceQuantity
}>

export type AppSwapConfigResponse = Readonly<{
aggregators: {
[aggregator in SwapAggregator]?: {
isEnabled: boolean
frontendFeeTiers: ReadonlyArray<AppFrontendFeeTier>
discountTokenId: string
}
}
liquidityProvidersEnabled: ReadonlyArray<string>
isSwapEnabled: boolean
}>
12 changes: 8 additions & 4 deletions packages/types/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
SwapOpenOrder,
SwapOrderType,
} from './swap/order'
import {SwapPool, SwapPoolProvider, SwapSupportedProvider} from './swap/pool'
import {SwapPool, SwapPoolProvider} from './swap/pool'
import {SwapStorage} from './swap/storage'
import {SwapManager} from './swap/manager'
import {AppStorage, AppStorageFolderName} from './app/storage'
Expand Down Expand Up @@ -72,7 +72,12 @@ import {
ResolverErrorNotFound,
ResolverErrorUnsupportedTld,
} from './resolver/errors'
import {AppApi, AppFrontendFeeTier, AppFrontendFeesResponse} from './api/app'
import {
AppApi,
AppFrontendFeeTier,
AppFrontendFeesResponse,
AppSwapConfigResponse,
} from './api/app'
import {
ApiFtMetadata,
ApiFtMetadataRecord,
Expand Down Expand Up @@ -158,6 +163,7 @@ export namespace App {

export type FrontendFeeTier = AppFrontendFeeTier
export type FrontendFeesResponse = AppFrontendFeesResponse
export type SwapConfigResponse = AppSwapConfigResponse
}

export namespace Swap {
Expand All @@ -181,8 +187,6 @@ export namespace Swap {
export type Pool = SwapPool
export type PoolResponse = SwapPool[]
export type PoolProvider = SwapPoolProvider
export type SupportedProvider = SwapSupportedProvider

export type Storage = SwapStorage
}

Expand Down
12 changes: 1 addition & 11 deletions packages/types/src/swap/pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,8 @@ export type SwapPoolProvider =
| 'vyfi'
| 'spectrum'

export type SwapSupportedProvider = Extract<
SwapPoolProvider,
| 'minswap'
| 'wingriders'
| 'sundaeswap'
| 'muesliswap'
| 'muesliswap_v2'
| 'vyfi'
>

export type SwapPool = {
provider: SwapSupportedProvider
provider: SwapPoolProvider
Copy link
Member Author

Choose a reason for hiding this comment

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

eventually will become a string, otherwise the parser will throw if a new is added on the fly.

fee: string // % pool liquidity provider fee, usually 0.3.
tokenA: BalanceAmount
tokenB: BalanceAmount
Expand Down
Loading