Skip to content

Commit

Permalink
chore: remove manual memo calcs (#5094)
Browse files Browse the repository at this point in the history
  • Loading branch information
0xApotheosis authored Aug 18, 2023
1 parent ae6a880 commit c4e178f
Show file tree
Hide file tree
Showing 13 changed files with 100 additions and 512 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,8 @@ import { getConfig } from 'config'
import type { Asset } from 'lib/asset-service'
import type { SwapErrorRight, TradeQuote } from 'lib/swapper/api'
import { makeSwapErrorRight, SwapErrorType } from 'lib/swapper/api'
import type {
ThorCosmosSdkSupportedChainId,
ThornodeQuoteResponseSuccess,
} from 'lib/swapper/swappers/ThorchainSwapper/types'
import type { ThorCosmosSdkSupportedChainId } from 'lib/swapper/swappers/ThorchainSwapper/types'
import { getInboundAddressDataForChain } from 'lib/swapper/swappers/ThorchainSwapper/utils/getInboundAddressDataForChain'
import { getLimit } from 'lib/swapper/swappers/ThorchainSwapper/utils/getLimit/getLimit'
import { makeSwapMemo } from 'lib/swapper/swappers/ThorchainSwapper/utils/makeSwapMemo/makeSwapMemo'

type GetCosmosTxDataInput = {
accountNumber: number
Expand All @@ -31,27 +26,14 @@ type GetCosmosTxDataInput = {
affiliateBps: string
buyAssetUsdRate: string
feeAssetUsdRate: string
thornodeQuote: ThornodeQuoteResponseSuccess
memo: string
}

export const getCosmosTxData = async (
input: GetCosmosTxDataInput,
): Promise<Result<ThorchainSignTx | CosmosSignTx, SwapErrorRight>> => {
const {
accountNumber,
destinationAddress,
sellAmountCryptoBaseUnit,
sellAsset,
buyAsset,
slippageTolerance,
quote,
from,
sellAdapter,
affiliateBps,
buyAssetUsdRate,
feeAssetUsdRate,
thornodeQuote,
} = input
const { accountNumber, sellAmountCryptoBaseUnit, sellAsset, quote, from, sellAdapter, memo } =
input
const fromThorAsset = sellAsset.chainId === KnownChainIds.ThorchainMainnet
const daemonUrl = getConfig().REACT_APP_THORCHAIN_NODE_URL
const maybeVault = await (async () => {
Expand All @@ -73,27 +55,6 @@ export const getCosmosTxData = async (
}),
)

const maybeLimit = await getLimit({
buyAsset,
sellAmountCryptoBaseUnit,
sellAsset,
slippageTolerance,
protocolFees: quote.steps[0].feeData.protocolFees,
buyAssetUsdRate,
feeAssetUsdRate,
thornodeQuote,
})

if (maybeLimit.isErr()) return Err(maybeLimit.unwrapErr())

const limit = maybeLimit.unwrap()
const memo = makeSwapMemo({
buyAssetId: buyAsset.assetId,
destinationAddress,
limit,
affiliateBps,
})

const maybeBuiltTxResponse = (() => {
switch (true) {
case fromThorAsset:
Expand Down
7 changes: 5 additions & 2 deletions src/lib/swapper/swappers/ThorchainSwapper/endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const thorchainApi: Swapper2Api = {
}))
}

return await getThorTradeQuote(input, rates).then(async firstQuote => {
return await getThorTradeQuote(input).then(async firstQuote => {
// If the first quote fails there is no need to check if the donation amount is below the minimum
if (firstQuote.isErr())
return mapTradeQuoteToTradeQuote2(firstQuote, receiveAddress, affiliateBps)
Expand All @@ -65,7 +65,10 @@ export const thorchainApi: Swapper2Api = {
If the donation amount is below the minimum,
we need to fetch a new quote with no affiliate fee
*/
await getThorTradeQuote({ ...input, affiliateBps: '0' }, rates)
await getThorTradeQuote({
...input,
affiliateBps: '0',
})
: firstQuote

return mapTradeQuoteToTradeQuote2(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,30 +1,18 @@
import type { AssetId } from '@shapeshiftoss/caip'
import { fromAssetId } from '@shapeshiftoss/caip'
import type { Result } from '@sniptt/monads'
import { Err, Ok } from '@sniptt/monads'
import { getConfig } from 'config'
import type { Asset } from 'lib/asset-service'
import type { ProtocolFee, SwapErrorRight } from 'lib/swapper/api'
import type { SwapErrorRight } from 'lib/swapper/api'
import { makeSwapErrorRight, SwapErrorType } from 'lib/swapper/api'
import { deposit } from 'lib/swapper/swappers/ThorchainSwapper/evm/routerCalldata'
import { getInboundAddressDataForChain } from 'lib/swapper/swappers/ThorchainSwapper/utils/getInboundAddressDataForChain'
import { getLimit } from 'lib/swapper/swappers/ThorchainSwapper/utils/getLimit/getLimit'
import { makeSwapMemo } from 'lib/swapper/swappers/ThorchainSwapper/utils/makeSwapMemo/makeSwapMemo'
import { isNativeEvmAsset } from 'lib/swapper/swappers/utils/helpers/helpers'

import type { ThornodeQuoteResponseSuccess } from '../../types'

type GetEvmThorTxInfoArgs = {
sellAsset: Asset
buyAsset: Asset
sellAmountCryptoBaseUnit: string
slippageTolerance: string
destinationAddress: string
protocolFees: Record<AssetId, ProtocolFee>
affiliateBps: string
buyAssetUsdRate: string
feeAssetUsdRate: string
thornodeQuote: ThornodeQuoteResponseSuccess
memo: string
}

type GetEvmThorTxInfoReturn = Promise<
Expand All @@ -41,15 +29,8 @@ type GetBtcThorTxInfo = (args: GetEvmThorTxInfoArgs) => GetEvmThorTxInfoReturn

export const getThorTxInfo: GetBtcThorTxInfo = async ({
sellAsset,
buyAsset,
sellAmountCryptoBaseUnit,
slippageTolerance,
destinationAddress,
protocolFees,
affiliateBps,
buyAssetUsdRate,
feeAssetUsdRate,
thornodeQuote,
memo,
}) => {
const daemonUrl = getConfig().REACT_APP_THORCHAIN_NODE_URL
const { assetReference } = fromAssetId(sellAsset.assetId)
Expand All @@ -70,35 +51,15 @@ export const getThorTxInfo: GetBtcThorTxInfo = async ({
}),
)

const maybeLimit = await getLimit({
buyAsset,
const data = deposit(
router,
vault,
isNativeEvmAsset(sellAsset.assetId)
? '0x0000000000000000000000000000000000000000'
: assetReference,
sellAmountCryptoBaseUnit,
sellAsset,
slippageTolerance,
protocolFees,
buyAssetUsdRate,
feeAssetUsdRate,
thornodeQuote,
})

return maybeLimit.andThen(limit => {
const memo = makeSwapMemo({
buyAssetId: buyAsset.assetId,
destinationAddress,
limit,
affiliateBps,
})

const data = deposit(
router,
vault,
isNativeEvmAsset(sellAsset.assetId)
? '0x0000000000000000000000000000000000000000'
: assetReference,
sellAmountCryptoBaseUnit,
memo,
)
memo,
)

return Ok({ data, router })
})
return Ok({ data, router })
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ jest.mock('config', () => {

const expectedQuoteResponse: ThorEvmTradeQuote = {
rate: '144114.94366197183098591549',
recommendedSlippage: '0.04357',
recommendedSlippage: '0.0435',
data: '0x',
router: '0x3624525075b88B24ecc29CE226b0CEc1fFcB6976',
steps: [
Expand Down Expand Up @@ -108,7 +108,7 @@ describe('getTradeQuote', () => {
'First output should be to inbound_address, second output should be change back to self, third output should be OP_RETURN, limited to 80 bytes. Do not send below the dust threshold. Do not use exotic spend scripts, locks or address formats (P2WSH with Bech32 address format preferred).',
outbound_delay_blocks: 575,
outbound_delay_seconds: 6900,
slippage_bps: 4357,
slippage_bps: 435,
warning: 'Do not cache this response. Do not send funds after the expiry.',
memo: '=:ETH.ETH:0x32DBc9Cf9E8FbCebE1e0a2ecF05Ed86Ca3096Cb6::ss:0',
},
Expand All @@ -122,14 +122,10 @@ describe('getTradeQuote', () => {
sellAmountIncludingProtocolFeesCryptoBaseUnit: '713014679420',
buyAsset: ETH,
sellAsset: FOX_MAINNET,
slippageTolerancePercentage: '0.04357',
}

const maybeTradeQuote = await getThorTradeQuote(input, {
sellAssetUsdRate: '0.15399605260336216',
buyAssetUsdRate: '1595',
feeAssetUsdRate: '1595',
runeAssetUsdRate: '0.30',
})
const maybeTradeQuote = await getThorTradeQuote(input)
expect(maybeTradeQuote.isOk()).toBe(true)
expect(maybeTradeQuote.unwrap()).toEqual(expectedQuoteResponse)
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import type {
import { makeSwapErrorRight, SwapErrorType, SwapperName } from 'lib/swapper/api'
import { getThorTxInfo as getEvmThorTxInfo } from 'lib/swapper/swappers/ThorchainSwapper/evm/utils/getThorTxData'
import type {
Rates,
ThorCosmosSdkSupportedChainId,
ThorEvmSupportedChainId,
ThorUtxoSupportedChainId,
Expand All @@ -34,6 +33,10 @@ import { THORCHAIN_FIXED_PRECISION } from 'lib/swapper/swappers/ThorchainSwapper
import { getQuote } from 'lib/swapper/swappers/ThorchainSwapper/utils/getQuote/getQuote'
import { getUtxoTxFees } from 'lib/swapper/swappers/ThorchainSwapper/utils/txFeeHelpers/utxoTxFees/getUtxoTxFees'
import { getThorTxInfo as getUtxoThorTxInfo } from 'lib/swapper/swappers/ThorchainSwapper/utxo/utils/getThorTxData'
import {
convertBasisPointsToDecimalPercentage,
convertDecimalPercentageToBasisPoints,
} from 'state/slices/tradeQuoteSlice/utils'

import { isNativeEvmAsset } from '../../utils/helpers/helpers'
import { getEvmTxFees } from '../utils/txFeeHelpers/evmTxFees/getEvmTxFees'
Expand All @@ -50,26 +53,23 @@ type ThorTradeQuote =

export const getThorTradeQuote = async (
input: GetTradeQuoteInput & { wallet?: HDWallet },
rates: Rates,
): Promise<Result<ThorTradeQuote, SwapErrorRight>> => {
const {
sellAsset,
buyAsset,
sellAmountIncludingProtocolFeesCryptoBaseUnit: sellAmountCryptoBaseUnit,
slippageTolerancePercentage,
accountNumber,
chainId,
receiveAddress,
affiliateBps,
wallet,
slippageTolerancePercentage,
} = input

const slippageTolerance =
slippageTolerancePercentage ?? getDefaultSlippagePercentageForSwapper(SwapperName.Thorchain)

const { buyAssetUsdRate, feeAssetUsdRate } = rates

const { chainId: buyAssetChainId } = fromAssetId(buyAsset.assetId)
const slippageBps = convertDecimalPercentageToBasisPoints(
slippageTolerancePercentage ?? getDefaultSlippagePercentageForSwapper(SwapperName.Thorchain),
).toString()

const chainAdapterManager = getChainAdapterManager()
const sellAdapter = chainAdapterManager.get(chainId)
Expand Down Expand Up @@ -100,18 +100,22 @@ export const getThorTradeQuote = async (
sellAmountCryptoBaseUnit,
receiveAddress,
affiliateBps,
slippageBps,
})

if (maybeQuote.isErr()) return Err(maybeQuote.unwrapErr())

const thornodeQuote = maybeQuote.unwrap()
const {
slippage_bps: slippageBps,
slippage_bps: recommendedSlippageBps,
fees,
expected_amount_out: expectedAmountOutThorBaseUnit,
memo,
} = thornodeQuote

const slippagePercentage = bn(slippageBps).div(1000)
const recommendedSlippageDecimalPercentage = convertBasisPointsToDecimalPercentage(
recommendedSlippageBps.toString(),
).toString()

const rate = (() => {
const THOR_PRECISION = 8
Expand Down Expand Up @@ -147,7 +151,7 @@ export const getThorTradeQuote = async (
})()

const commonQuoteFields = {
recommendedSlippage: slippagePercentage.div(100).toString(),
recommendedSlippage: recommendedSlippageDecimalPercentage,
}

const commonStepFields = {
Expand Down Expand Up @@ -176,15 +180,8 @@ export const getThorTradeQuote = async (
return (async (): Promise<Promise<Result<ThorEvmTradeQuote, SwapErrorRight>>> => {
const maybeThorTxInfo = await getEvmThorTxInfo({
sellAsset,
buyAsset,
sellAmountCryptoBaseUnit,
slippageTolerance,
destinationAddress: receiveAddress,
protocolFees,
affiliateBps,
buyAssetUsdRate,
feeAssetUsdRate,
thornodeQuote,
memo,
})

if (maybeThorTxInfo.isErr()) return Err(maybeThorTxInfo.unwrapErr())
Expand Down Expand Up @@ -225,16 +222,8 @@ export const getThorTradeQuote = async (
return (async (): Promise<Result<TradeQuote<ThorUtxoSupportedChainId>, SwapErrorRight>> => {
const maybeThorTxInfo = await getUtxoThorTxInfo({
sellAsset,
buyAsset,
sellAmountCryptoBaseUnit,
slippageTolerance,
destinationAddress: receiveAddress,
xpub: (input as GetUtxoTradeQuoteInput).xpub,
protocolFees,
affiliateBps,
buyAssetUsdRate,
feeAssetUsdRate,
thornodeQuote,
memo,
})

if (maybeThorTxInfo.isErr()) return Err(maybeThorTxInfo.unwrapErr())
Expand Down
Loading

0 comments on commit c4e178f

Please sign in to comment.