Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
0f8b883
update types
kaladinlight Apr 20, 2023
1b3d516
update types and add top level asset check
kaladinlight Apr 20, 2023
8e0d76f
add fee and build/broadcast helpers and improve approve helper
kaladinlight Apr 20, 2023
4a8ecd4
update zrx to use new helpers (eip1559 fees)
kaladinlight Apr 20, 2023
4a150ff
updated thorchain swapper to use new helpers (eip1559)
kaladinlight Apr 20, 2023
3333f67
use updated approve helper
kaladinlight Apr 20, 2023
1d72155
remove requirement to pass in hex number to buildCustomTx
kaladinlight Apr 20, 2023
e128062
Merge branch 'develop' into eip1559-fees
kaladinlight Apr 20, 2023
6ecdf28
cleanup
kaladinlight Apr 20, 2023
d606eee
pass back eip1559 fees for thorchain
kaladinlight Apr 20, 2023
fc835f7
add fee and build/broadcast helpers
kaladinlight Apr 21, 2023
f57a6de
update fox-farming to use new helpers
kaladinlight Apr 21, 2023
17f8805
pass back eip1559 fees for cowswap quote and use bn for const
kaladinlight Apr 21, 2023
1d7e4fa
cleanup naming and types
kaladinlight Apr 21, 2023
1145778
update univ2 to use new helpers
kaladinlight Apr 21, 2023
a48710f
update naming changes
kaladinlight Apr 21, 2023
ab22c75
jesus fucking tits tests
kaladinlight Apr 21, 2023
6a70be9
format
kaladinlight Apr 21, 2023
3840e65
additional cowswap cleanup
kaladinlight Apr 24, 2023
38f6f65
additional zrx swapper cleanup
kaladinlight Apr 24, 2023
89455ef
additional thorchain swapper cleanup
kaladinlight Apr 24, 2023
33859cb
review feedback
kaladinlight Apr 24, 2023
eea80a8
explicit data
kaladinlight Apr 24, 2023
52e0151
fix tests again
kaladinlight Apr 24, 2023
0f0d47d
fee data helper to pull average eip1559 and fast legacy fees
kaladinlight Apr 24, 2023
0c42599
Merge branch 'develop' into eip1559-fees
kaladinlight Apr 24, 2023
967fcf2
average eip1559 vs fast legacy with updated comment
kaladinlight Apr 25, 2023
cb00807
small cleanup approval fee
kaladinlight Apr 25, 2023
4c9bfde
fix tests
kaladinlight Apr 25, 2023
63140b5
remove parser log
kaladinlight Apr 25, 2023
f369882
Merge branch 'develop' into eip1559-fees
kaladinlight Apr 25, 2023
e1af646
fix: pass value for deposit
kaladinlight Apr 25, 2023
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
20 changes: 0 additions & 20 deletions jest.config.js

This file was deleted.

33 changes: 31 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,35 @@
"react-dom@^18.2.0": "patch:react-dom@npm%3A18.2.0#./.yarn/patches/react-dom-npm-18.2.0-dd675bca1c.patch"
},
"jest": {
"resetMocks": false
"preset": "ts-jest",
"testEnvironment": "node",
"testPathIgnorePatterns": [
"/node_modules/",
".d.ts",
".js",
"__mocks__",
"mockData"
],
"clearMocks": true,
"resetMocks": false,
"roots": [
"<rootDir>"
],
"collectCoverage": false,
"setupFiles": [
"<rootDir>/.jest/setup.js"
],
"moduleNameMapper": {
"^@shapeshiftoss\\/([^/ ]+)": [
"@shapeshiftoss/$1",
"@shapeshiftoss/$1/src"
]
},
"globals": {
"ts-jest": {
"sourceMap": true,
"isolatedModules": true
}
}
}
}
}
3 changes: 1 addition & 2 deletions packages/chain-adapters/src/evm/EvmBaseAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ import type {
import { ValidAddressResultType } from '../types'
import {
chainIdToChainLabel,
convertNumberToHex,
getAssetNamespace,
toAddressNList,
toRootDerivationPath,
Expand Down Expand Up @@ -548,7 +547,7 @@ export abstract class EvmBaseAdapter<T extends EvmChainId> implements IChainAdap
const bip44Params = this.getBIP44Params({ accountNumber })
const txToSign = {
addressNList: toAddressNList(bip44Params),
value: convertNumberToHex(value),
value: numberToHex(value),
to,
chainId: Number(fromChainId(this.chainId).chainReference),
data,
Expand Down
7 changes: 0 additions & 7 deletions packages/unchained-client/src/evm/parser/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { AssetId, ChainId } from '@shapeshiftoss/caip'
import { ASSET_NAMESPACE, ASSET_REFERENCE, ethChainId, toAssetId } from '@shapeshiftoss/caip'
import { Logger } from '@shapeshiftoss/logger'
import { BigNumber } from 'bignumber.js'
import { ethers } from 'ethers'

Expand All @@ -12,11 +11,6 @@ import type { ParsedTx, SubParser, Tx, TxSpecific } from './types'
export * from './types'
export * from './utils'

const logger = new Logger({
namespace: ['unchained-client', 'evm', 'parser'],
level: process.env.LOG_LEVEL,
})

export interface TransactionParserArgs {
chainId: ChainId
assetId: AssetId
Expand Down Expand Up @@ -170,7 +164,6 @@ export class BaseTransactionParser<T extends Tx> {
case 'BEP721':
return ASSET_NAMESPACE.bep721
default:
logger.warn(`unsupported asset namespace: ${transfer.type}`)
return
}
})()
Expand Down
92 changes: 91 additions & 1 deletion src/features/defi/helpers/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import type { Asset } from '@shapeshiftoss/asset-service'
import type { AccountId, ChainId } from '@shapeshiftoss/caip'
import { cosmosChainId, osmosisChainId } from '@shapeshiftoss/caip'
import { bnOrZero } from 'lib/bignumber/bignumber'
import type {
evm,
EvmChainAdapter,
EvmChainId,
FeeData,
FeeDataEstimate,
} from '@shapeshiftoss/chain-adapters'
import type { HDWallet } from '@shapeshiftoss/hdwallet-core'
import { supportsETH } from '@shapeshiftoss/hdwallet-core'
import { BigNumber, bn, bnOrZero } from 'lib/bignumber/bignumber'
import { selectPortfolioCryptoPrecisionBalanceByFilter } from 'state/slices/selectors'
import { store } from 'state/store'

Expand Down Expand Up @@ -34,3 +43,84 @@ export const canCoverTxFees = ({

return bnOrZero(feeAssetBalanceCryptoHuman).minus(bnOrZero(estimatedGasCryptoPrecision)).gte(0)
}

export const getFeeDataFromEstimate = ({
average,
fast,
}: FeeDataEstimate<EvmChainId>): FeeData<EvmChainId> => ({
txFee: BigNumber.max(
average.txFee,
bnOrZero(bn(fast.chainSpecific.gasPrice).times(average.chainSpecific.gasLimit)),
).toFixed(0), // use worst case average eip1559 vs fast legacy
chainSpecific: {
gasLimit: average.chainSpecific.gasLimit, // average and fast gasLimit values are the same
gasPrice: fast.chainSpecific.gasPrice, // fast gas price since it is underestimated currently
maxFeePerGas: average.chainSpecific.maxFeePerGas,
maxPriorityFeePerGas: average.chainSpecific.maxPriorityFeePerGas,
},
})

type GetFeesFromFeeDataArgs = {
wallet: HDWallet
feeData: evm.FeeData
}

export const getFeesFromFeeData = async ({
wallet,
feeData: { gasLimit, gasPrice, maxFeePerGas, maxPriorityFeePerGas },
}: GetFeesFromFeeDataArgs): Promise<evm.Fees & { gasLimit: string }> => {
if (!supportsETH(wallet)) throw new Error('wallet has no evm support')
if (!gasLimit) throw new Error('gasLimit is required')

const supportsEip1559 = await wallet.ethSupportsEIP1559()

// use eip1559 fees if able
if (supportsEip1559 && maxFeePerGas && maxPriorityFeePerGas) {
return { gasLimit, maxFeePerGas, maxPriorityFeePerGas }
}

// fallback to legacy fees if unable to use eip1559
if (gasPrice) return { gasLimit, gasPrice }

throw new Error('legacy gas or eip1559 gas required')
}

type BuildAndBroadcastArgs = GetFeesFromFeeDataArgs & {
accountNumber: number
adapter: EvmChainAdapter
data: string
to: string
value: string
}

export const buildAndBroadcast = async ({
accountNumber,
adapter,
data,
feeData,
to,
value,
wallet,
}: BuildAndBroadcastArgs) => {
const { txToSign } = await adapter.buildCustomTx({
wallet,
to,
accountNumber,
value,
data,
...(await getFeesFromFeeData({ wallet, feeData })),
})

if (wallet.supportsOfflineSigning()) {
const signedTx = await adapter.signTransaction({ txToSign, wallet })
const txid = await adapter.broadcastTransaction(signedTx)
return txid
}

if (wallet.supportsBroadcast() && adapter.signAndBroadcastTransaction) {
const txid = await adapter.signAndBroadcastTransaction({ txToSign, wallet })
return txid
}

throw new Error('buildAndBroadcast: no broadcast support')
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export const ClaimConfirm = ({ accountId, assetId, amount, onBack }: ClaimConfir

assertIsFoxEthStakingContractAddress(contractAddress)

const { claimRewards, getClaimGasData, foxFarmingContract } = useFoxFarming(contractAddress)
const { claimRewards, getClaimFeeData, foxFarmingContract } = useFoxFarming(contractAddress)
const translate = useTranslate()
const mixpanel = getMixPanel()
const { onOngoingFarmingTxIdChange } = useFoxEth()
Expand Down Expand Up @@ -156,9 +156,9 @@ export const ClaimConfirm = ({ accountId, assetId, amount, onBack }: ClaimConfir
!(walletState.wallet && feeAsset && feeMarketData && foxFarmingContract && accountAddress)
)
return
const gasEstimate = await getClaimGasData(accountAddress)
if (!gasEstimate) throw new Error('Gas estimation failed')
const estimatedGasCrypto = bnOrZero(gasEstimate.average.txFee)
const feeData = await getClaimFeeData(accountAddress)
if (!feeData) throw new Error('Gas estimation failed')
const estimatedGasCrypto = bnOrZero(feeData.txFee)
.div(`1e${feeAsset.precision}`)
.toPrecision()
setCanClaim(true)
Expand All @@ -174,7 +174,7 @@ export const ClaimConfirm = ({ accountId, assetId, amount, onBack }: ClaimConfir
feeAsset.precision,
feeMarketData,
feeMarketData.price,
getClaimGasData,
getClaimFeeData,
walletState.wallet,
foxFarmingContract,
])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export const Approve: React.FC<FoxFarmingApproveProps> = ({ accountId, onNext })
)
assertIsFoxEthStakingContractAddress(contractAddress)

const { allowance, approve, getStakeGasData } = useFoxFarming(contractAddress)
const { allowance, approve, getStakeFeeData } = useFoxFarming(contractAddress)

const assets = useAppSelector(selectAssets)

Expand Down Expand Up @@ -109,9 +109,9 @@ export const Approve: React.FC<FoxFarmingApproveProps> = ({ accountId, onNext })
maxAttempts: 30,
})
// Get deposit gas estimate
const gasData = await getStakeGasData(state.deposit.cryptoAmount)
if (!gasData) return
const estimatedGasCryptoPrecision = bnOrZero(gasData.average.txFee)
const feeData = await getStakeFeeData(state.deposit.cryptoAmount)
if (!feeData) return
const estimatedGasCryptoPrecision = bnOrZero(feeData.txFee)
.div(bn(10).pow(feeAsset.precision))
.toPrecision()
dispatch({
Expand Down Expand Up @@ -147,7 +147,7 @@ export const Approve: React.FC<FoxFarmingApproveProps> = ({ accountId, onNext })
wallet,
asset,
approve,
getStakeGasData,
getStakeFeeData,
feeAsset.precision,
onNext,
assets,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ export const Deposit: React.FC<DepositProps> = ({

const {
allowance: foxFarmingAllowance,
getStakeGasData,
getApproveGasData,
getStakeFeeData,
getApproveFeeData,
} = useFoxFarming(contractAddress)

const feeAssetId = getChainAdapterManager().get(chainId)?.getFeeAssetId()
Expand Down Expand Up @@ -132,9 +132,9 @@ export const Deposit: React.FC<DepositProps> = ({
): Promise<string | undefined> => {
if (!assetReference) return
try {
const gasData = await getStakeGasData(deposit.cryptoAmount)
if (!gasData) return
return bnOrZero(gasData.average.txFee).div(bn(10).pow(feeAsset.precision)).toPrecision()
const feeData = await getStakeFeeData(deposit.cryptoAmount)
if (!feeData) return
return bnOrZero(feeData.txFee).div(bn(10).pow(feeAsset.precision)).toPrecision()
} catch (error) {
moduleLogger.error(
{ fn: 'getDepositGasEstimateCryptoPrecision', error },
Expand Down Expand Up @@ -180,12 +180,12 @@ export const Deposit: React.FC<DepositProps> = ({
assets,
)
} else {
const estimatedGasCryptoBaseUnit = await getApproveGasData()
if (!estimatedGasCryptoBaseUnit) return
const feeData = await getApproveFeeData()
if (!feeData) return
dispatch({
type: FoxFarmingDepositActionType.SET_APPROVE,
payload: {
estimatedGasCryptoPrecision: bnOrZero(estimatedGasCryptoBaseUnit.average.txFee)
estimatedGasCryptoPrecision: bnOrZero(feeData.txFee)
.div(bn(10).pow(feeAsset.precision))
.toPrecision(),
},
Expand All @@ -210,14 +210,14 @@ export const Deposit: React.FC<DepositProps> = ({
feeAsset,
foxFarmingOpportunity,
assetReference,
getStakeGasData,
getStakeFeeData,
toast,
translate,
asset,
foxFarmingAllowance,
onNext,
assets,
getApproveGasData,
getApproveFeeData,
],
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const Approve: React.FC<ApproveProps> = ({ accountId, onNext }) => {

assertIsFoxEthStakingContractAddress(contractAddress)

const { allowance, approve, getUnstakeGasData } = useFoxFarming(contractAddress)
const { allowance, approve, getUnstakeFeeData } = useFoxFarming(contractAddress)
const toast = useToast()
const assets = useAppSelector(selectAssets)

Expand Down Expand Up @@ -107,9 +107,9 @@ export const Approve: React.FC<ApproveProps> = ({ accountId, onNext }) => {
maxAttempts: 30,
})
// Get withdraw gas estimate
const gasData = await getUnstakeGasData(state.withdraw.lpAmount, state.withdraw.isExiting)
if (!gasData) return
const estimatedGasCrypto = bnOrZero(gasData.average.txFee)
const feeData = await getUnstakeFeeData(state.withdraw.lpAmount, state.withdraw.isExiting)
if (!feeData) return
const estimatedGasCrypto = bnOrZero(feeData.txFee)
.div(bn(10).pow(underlyingAsset?.precision ?? 0))
.toPrecision()
dispatch({
Expand Down Expand Up @@ -145,7 +145,7 @@ export const Approve: React.FC<ApproveProps> = ({ accountId, onNext }) => {
opportunity,
wallet,
approve,
getUnstakeGasData,
getUnstakeFeeData,
underlyingAsset?.precision,
onNext,
assets,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export const ExpiredWithdraw: React.FC<ExpiredWithdrawProps> = ({

assertIsFoxEthStakingContractAddress(contractAddress)

const { getUnstakeGasData, allowance, getApproveGasData } = useFoxFarming(contractAddress)
const { getUnstakeFeeData, allowance, getApproveFeeData } = useFoxFarming(contractAddress)

const methods = useForm<WithdrawValues>({ mode: 'onChange' })

Expand Down Expand Up @@ -108,9 +108,9 @@ export const ExpiredWithdraw: React.FC<ExpiredWithdrawProps> = ({

const getWithdrawGasEstimate = async () => {
try {
const fee = await getUnstakeGasData(amountAvailableCryptoPrecision.toFixed(), true)
if (!fee) return
return bnOrZero(fee.average.txFee).div(bn(10).pow(feeAsset.precision)).toPrecision()
const feeData = await getUnstakeFeeData(amountAvailableCryptoPrecision.toFixed(), true)
if (!feeData) return
return bnOrZero(feeData.txFee).div(bn(10).pow(feeAsset.precision)).toPrecision()
} catch (error) {
// TODO: handle client side errors maybe add a toast?
moduleLogger.error(
Expand Down Expand Up @@ -162,12 +162,12 @@ export const ExpiredWithdraw: React.FC<ExpiredWithdrawProps> = ({
assets,
)
} else {
const estimatedGasCrypto = await getApproveGasData()
if (!estimatedGasCrypto) return
const feeData = await getApproveFeeData()
if (!feeData) return
dispatch({
type: FoxFarmingWithdrawActionType.SET_APPROVE,
payload: {
estimatedGasCryptoPrecision: bnOrZero(estimatedGasCrypto.average.txFee)
estimatedGasCryptoPrecision: bnOrZero(feeData.txFee)
.div(bn(10).pow(feeAsset.precision))
.toPrecision(),
},
Expand Down
Loading