Skip to content

Commit

Permalink
feat(zrxSwapper): add usd rate (shapeshift#85)
Browse files Browse the repository at this point in the history
* Add getUsdRate to Zrx
  • Loading branch information
toshiSat authored Sep 30, 2021
1 parent 0f6455a commit 1d5d36e
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 5 deletions.
6 changes: 6 additions & 0 deletions packages/swapper/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,10 @@ export interface Swapper {
* @param buyAsset
*/
canTradePair(sellAsset: Asset, buyAsset: Asset): boolean

/**
* Get the usd rate from either the assets symbol or tokenId
* @param input
*/
getUsdRate(input: Pick<Asset, 'symbol' | 'tokenId'>): Promise<string>
}
5 changes: 5 additions & 0 deletions packages/swapper/src/swappers/thorchain/ThorchainSwapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ export class ThorchainSwapper implements Swapper {
return undefined
}

getUsdRate(input: Pick<Asset, 'symbol' | 'tokenId'>): Promise<string> {
console.info(input)
throw new Error('Method not implemented.')
}

getAvailableAssets(assets: Asset[]): Asset[] {
console.info(assets)
throw new Error('Method not implemented.')
Expand Down
27 changes: 24 additions & 3 deletions packages/swapper/src/swappers/zrx/ZrxSwapper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
ChainTypes,
NetworkTypes,
ContractTypes,
Asset,
GetQuoteInput,
SwapperType
} from '@shapeshiftoss/types'
Expand All @@ -14,7 +13,13 @@ import { ZrxError } from '../..'
import { DEFAULT_SLIPPAGE } from './utils/constants'
import { buildQuoteTx } from '../zrx/buildQuoteTx/buildQuoteTx'
import { getZrxQuote } from './getQuote/getQuote'
import { zrxService } from './utils/zrxService'

const axios = jest.createMockFromModule('axios')
//@ts-ignore
axios.create = jest.fn(() => axios)
jest.mock('./utils/helpers/helpers')
jest.mock('./utils/zrxService')
jest.mock('../zrx/buildQuoteTx/buildQuoteTx', () => ({
buildQuoteTx: jest.fn()
}))
Expand Down Expand Up @@ -111,7 +116,7 @@ describe('ZrxSwapper', () => {
const error = new ZrxError(message)
expect(error.message).toBe(`ZrxError:${message}`)
})
it('available assets filters out all non-ethereum assets', () => {
it('getAvailableAssets filters out all non-ethereum assets', () => {
const swapper = new ZrxSwapper(zrxSwapperDeps)
const availableAssets = swapper.getAvailableAssets([BTC, FOX, WETH])
expect(availableAssets).toStrictEqual([FOX, WETH])
Expand All @@ -129,8 +134,24 @@ describe('ZrxSwapper', () => {
it('calls buildQuoteTx on swapper.buildQuoteTx', async () => {
const swapper = new ZrxSwapper(zrxSwapperDeps)
const args = { input, wallet }

await swapper.buildQuoteTx(args)
expect(buildQuoteTx).toHaveBeenCalled()
})
describe('getUsdRate', () => {
it('getUsdRate gets the usd rate of the symbol', async () => {
const swapper = new ZrxSwapper(zrxSwapperDeps)
;(zrxService.get as jest.Mock<unknown>).mockReturnValue(
Promise.resolve({ data: { price: '2' } })
)
const rate = await swapper.getUsdRate({ symbol: 'FOX' })
expect(rate).toBe('0.5')
})
it('getUsdRate fails', async () => {
const swapper = new ZrxSwapper(zrxSwapperDeps)
;(zrxService.get as jest.Mock<unknown>).mockReturnValue(Promise.resolve({ data: {} }))
await expect(swapper.getUsdRate({ symbol: 'WETH', tokenId: '0x0001' })).rejects.toThrow(
'getUsdRate - Failed to get price data'
)
})
})
})
23 changes: 22 additions & 1 deletion packages/swapper/src/swappers/zrx/ZrxSwapper.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import Web3 from 'web3'
import { AxiosResponse } from 'axios'
import BigNumber from 'bignumber.js'
import { zrxService } from './utils/zrxService'
import {
Asset,
BuildQuoteTxArgs,
ChainTypes,
GetQuoteInput,
Quote,
SwapperType
SwapperType,
QuoteResponse
} from '@shapeshiftoss/types'
import { ChainAdapterManager } from '@shapeshiftoss/chain-adapters'
import { Swapper } from '../../api'
Expand Down Expand Up @@ -45,6 +49,23 @@ export class ZrxSwapper implements Swapper {
return getZrxQuote(input)
}

async getUsdRate(input: Pick<Asset, 'symbol' | 'tokenId'>): Promise<string> {
const { symbol, tokenId } = input
const rateResponse: AxiosResponse<QuoteResponse> = await zrxService.get<QuoteResponse>(
'/swap/v1/price',
{
params: {
buyToken: 'USDC',
buyAmount: '1000000', // $1
sellToken: tokenId || symbol
}
}
)
if (!rateResponse.data.price) throw new ZrxError('getUsdRate - Failed to get price data')

return new BigNumber(1).dividedBy(rateResponse.data.price).toString()
}

getAvailableAssets(assets: Asset[]): Asset[] {
return assets.filter((asset) => asset.chain === ChainTypes.Ethereum)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { AxiosResponse } from 'axios'
import * as rax from 'retry-axios'
import { ChainAdapter } from '@shapeshiftoss/chain-adapters'
import { SwapError } from '../../..'
import { ChainTypes, Quote, BuildQuoteTxArgs } from '@shapeshiftoss/types'
import { Quote, BuildQuoteTxArgs } from '@shapeshiftoss/types'
import { ZrxSwapperDeps } from '../ZrxSwapper'
import { applyAxiosRetry } from '../utils/applyAxiosRetry'
import { erc20AllowanceAbi } from '../utils/abi/erc20-abi'
Expand Down

0 comments on commit 1d5d36e

Please sign in to comment.