From f1ce27f94d52debb0d35ecfaa6d8342272da412a Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Sun, 23 Apr 2023 19:31:19 +0200 Subject: [PATCH 01/29] feat: manually reapply lib/1032 --- packages/investor-foxy/package.json | 3 +- packages/investor-foxy/src/abi/erc20-abi.ts | 4 +- packages/investor-foxy/src/abi/foxy-abi.ts | 4 +- .../investor-foxy/src/abi/foxy-staking-abi.ts | 4 +- .../src/abi/liquidity-reserve-abi.ts | 4 +- .../investor-foxy/src/abi/toke-manager-abi.ts | 4 +- .../investor-foxy/src/abi/toke-pool-abi.ts | 4 +- .../src/abi/toke-reward-hash-abi.ts | 4 +- packages/investor-foxy/src/api/api.ts | 597 +++++++++--------- packages/investor-foxy/src/api/foxy-types.ts | 4 +- yarn.lock | 5 +- 11 files changed, 310 insertions(+), 327 deletions(-) diff --git a/packages/investor-foxy/package.json b/packages/investor-foxy/package.json index 8b1fe8ec98f..a0bcb98f158 100644 --- a/packages/investor-foxy/package.json +++ b/packages/investor-foxy/package.json @@ -21,11 +21,12 @@ "cli": "yarn build && yarn node dist/foxycli.js" }, "dependencies": { - "@ethersproject/providers": "^5.5.3", + "@ethersproject/providers": "^5.7.2", "@shapeshiftoss/caip": "workspace:^", "@shapeshiftoss/chain-adapters": "workspace:^", "@shapeshiftoss/logger": "workspace:^", "@shapeshiftoss/types": "workspace:^", + "ethers": "^5.7.2", "readline-sync": "^1.4.10", "web3-core": "1.7.4", "web3-utils": "1.7.4" diff --git a/packages/investor-foxy/src/abi/erc20-abi.ts b/packages/investor-foxy/src/abi/erc20-abi.ts index bc1723c6421..6d3c608bff2 100644 --- a/packages/investor-foxy/src/abi/erc20-abi.ts +++ b/packages/investor-foxy/src/abi/erc20-abi.ts @@ -1,6 +1,6 @@ -import type { AbiItem } from 'web3-utils' +import type { ContractInterface } from 'ethers/lib/ethers' -export const erc20Abi: AbiItem[] = [ +export const erc20Abi: ContractInterface = [ { constant: true, inputs: [], diff --git a/packages/investor-foxy/src/abi/foxy-abi.ts b/packages/investor-foxy/src/abi/foxy-abi.ts index cc8e6ccdbcb..8a0a8563606 100644 --- a/packages/investor-foxy/src/abi/foxy-abi.ts +++ b/packages/investor-foxy/src/abi/foxy-abi.ts @@ -1,6 +1,6 @@ -import type { AbiItem } from 'web3-utils' +import type { ContractInterface } from 'ethers/lib/ethers' -export const foxyAbi: AbiItem[] = [ +export const foxyAbi: ContractInterface = [ { inputs: [], stateMutability: 'nonpayable', diff --git a/packages/investor-foxy/src/abi/foxy-staking-abi.ts b/packages/investor-foxy/src/abi/foxy-staking-abi.ts index 44d3ee93bed..eb667ab58ef 100644 --- a/packages/investor-foxy/src/abi/foxy-staking-abi.ts +++ b/packages/investor-foxy/src/abi/foxy-staking-abi.ts @@ -1,6 +1,6 @@ -import type { AbiItem } from 'web3-utils' +import type { ContractInterface } from 'ethers/lib/ethers' -export const foxyStakingAbi: AbiItem[] = [ +export const foxyStakingAbi: ContractInterface = [ { inputs: [ { diff --git a/packages/investor-foxy/src/abi/liquidity-reserve-abi.ts b/packages/investor-foxy/src/abi/liquidity-reserve-abi.ts index b2e9615dece..fedefe5c43c 100644 --- a/packages/investor-foxy/src/abi/liquidity-reserve-abi.ts +++ b/packages/investor-foxy/src/abi/liquidity-reserve-abi.ts @@ -1,6 +1,6 @@ -import type { AbiItem } from 'web3-utils' +import type { ContractInterface } from 'ethers/lib/ethers' -export const liquidityReserveAbi: AbiItem[] = [ +export const liquidityReserveAbi: ContractInterface = [ { inputs: [ { diff --git a/packages/investor-foxy/src/abi/toke-manager-abi.ts b/packages/investor-foxy/src/abi/toke-manager-abi.ts index c6ee537cef2..ab0a29c8a9e 100644 --- a/packages/investor-foxy/src/abi/toke-manager-abi.ts +++ b/packages/investor-foxy/src/abi/toke-manager-abi.ts @@ -1,6 +1,6 @@ -import type { AbiItem } from 'web3-utils' +import type { ContractInterface } from 'ethers/lib/ethers' -export const tokeManagerAbi: AbiItem[] = [ +export const tokeManagerAbi: ContractInterface = [ { inputs: [], stateMutability: 'nonpayable', type: 'constructor' }, { anonymous: false, diff --git a/packages/investor-foxy/src/abi/toke-pool-abi.ts b/packages/investor-foxy/src/abi/toke-pool-abi.ts index c8c9018fa3a..c33909307f1 100644 --- a/packages/investor-foxy/src/abi/toke-pool-abi.ts +++ b/packages/investor-foxy/src/abi/toke-pool-abi.ts @@ -1,6 +1,6 @@ -import type { AbiItem } from 'web3-utils' +import type { ContractInterface } from 'ethers/lib/ethers' -export const tokePoolAbi: AbiItem[] = [ +export const tokePoolAbi: ContractInterface = [ { anonymous: false, inputs: [ diff --git a/packages/investor-foxy/src/abi/toke-reward-hash-abi.ts b/packages/investor-foxy/src/abi/toke-reward-hash-abi.ts index 758f382dcf1..f16d0a4687b 100644 --- a/packages/investor-foxy/src/abi/toke-reward-hash-abi.ts +++ b/packages/investor-foxy/src/abi/toke-reward-hash-abi.ts @@ -1,6 +1,6 @@ -import type { AbiItem } from 'web3-utils' +import type { ContractInterface } from 'ethers/lib/ethers' -export const tokeRewardHashAbi: AbiItem[] = [ +export const tokeRewardHashAbi: ContractInterface = [ { inputs: [], stateMutability: 'nonpayable', type: 'constructor' }, { anonymous: false, diff --git a/packages/investor-foxy/src/api/api.ts b/packages/investor-foxy/src/api/api.ts index d77125ce5cb..b4c5c5e1e7e 100644 --- a/packages/investor-foxy/src/api/api.ts +++ b/packages/investor-foxy/src/api/api.ts @@ -1,4 +1,4 @@ -import { JsonRpcProvider } from '@ethersproject/providers' +import { JsonRpcBatchProvider } from '@ethersproject/providers' import type { ChainReference } from '@shapeshiftoss/caip' import { CHAIN_NAMESPACE, CHAIN_REFERENCE, toAssetId } from '@shapeshiftoss/caip' import type { ChainAdapter } from '@shapeshiftoss/chain-adapters' @@ -6,10 +6,8 @@ import { Logger } from '@shapeshiftoss/logger' import { KnownChainIds, WithdrawType } from '@shapeshiftoss/types' import axios from 'axios' import type { BigNumber } from 'bignumber.js' +import { ethers } from 'ethers' import { toLower } from 'lodash' -import Web3 from 'web3' -import type { HttpProvider, TransactionReceipt } from 'web3-core/types' -import type { Contract } from 'web3-eth-contract' import { numberToHex } from 'web3-utils' import { erc20Abi } from '../abi/erc20-abi' @@ -89,12 +87,11 @@ const TOKE_IPFS_URL = 'https://ipfs.tokemaklabs.xyz/ipfs' export class FoxyApi { public adapter: ChainAdapter - public provider: HttpProvider + public provider: JsonRpcBatchProvider private providerUrl: string - public jsonRpcProvider: JsonRpcProvider - public web3: Web3 - private foxyStakingContracts: Contract[] - private liquidityReserveContracts: Contract[] + public jsonRpcProvider: JsonRpcBatchProvider + private foxyStakingContracts: ethers.Contract[] + private liquidityReserveContracts: ethers.Contract[] private readonly ethereumChainReference: ChainReference private foxyAddresses: FoxyAddressesType @@ -105,14 +102,14 @@ export class FoxyApi { chainReference = CHAIN_REFERENCE.EthereumMainnet, }: ConstructorArgs) { this.adapter = adapter - this.provider = new Web3.providers.HttpProvider(providerUrl) - this.jsonRpcProvider = new JsonRpcProvider(providerUrl) - this.web3 = new Web3(this.provider) + this.provider = new JsonRpcBatchProvider(providerUrl) + this.jsonRpcProvider = new JsonRpcBatchProvider(providerUrl) this.foxyStakingContracts = foxyAddresses.map( - addresses => new this.web3.eth.Contract(foxyStakingAbi, addresses.staking), + addresses => new ethers.Contract(addresses.staking, foxyStakingAbi, this.provider), ) this.liquidityReserveContracts = foxyAddresses.map( - addresses => new this.web3.eth.Contract(liquidityReserveAbi, addresses.liquidityReserve), + addresses => + new ethers.Contract(addresses.liquidityReserve, liquidityReserveAbi, this.provider), ) this.ethereumChainReference = chainReference this.providerUrl = providerUrl @@ -124,8 +121,8 @@ export class FoxyApi { * to exponential notation ('1.6e+21') in javascript. * @param amount */ - private normalizeAmount(amount: BigNumber) { - return this.web3.utils.toBN(amount.toFixed()) + private normalizeAmount(amount: BigNumber): ethers.BigNumber { + return ethers.BigNumber.from(amount.toFixed()) } private async signAndBroadcastTx(input: SignAndBroadcastTx): Promise { @@ -136,12 +133,12 @@ export class FoxyApi { if (dryRun) return signedTx try { if (this.providerUrl.includes('localhost') || this.providerUrl.includes('127.0.0.1')) { - const sendSignedTx = await this.web3.eth.sendSignedTransaction(signedTx) - return sendSignedTx?.blockHash + const sendSignedTx = await this.provider.sendTransaction(signedTx) + return sendSignedTx?.blockHash ?? '' } return this.adapter.broadcastTransaction(signedTx) - } catch (err) { - throw new Error(`Failed to broadcast: ${err}`) + } catch (e) { + throw new Error(`Failed to broadcast: ${e}`) } } else if (wallet.supportsBroadcast() && this.adapter.signAndBroadcastTransaction) { if (dryRun) { @@ -154,7 +151,8 @@ export class FoxyApi { } checksumAddress(address: string): string { - return this.web3.utils.toChecksumAddress(address) + // ethers always returns checksum addresses from getAddress() calls + return ethers.utils.getAddress(address) } private verifyAddresses(addresses: string[]) { @@ -162,41 +160,43 @@ export class FoxyApi { addresses.forEach(address => { this.checksumAddress(address) }) - } catch (err) { - throw new Error(`Verify Address: ${err}`) + } catch (e) { + throw new Error(`Verify Address: ${e}`) } } - private getStakingContract(contractAddress: string): Contract { + private getStakingContract(contractAddress: string): ethers.Contract { const stakingContract = this.foxyStakingContracts.find( - item => toLower(item.options.address) === toLower(contractAddress), + item => toLower(item.address) === toLower(contractAddress), ) if (!stakingContract) throw new Error('Not a valid contract address') return stakingContract } - private getLiquidityReserveContract(liquidityReserveAddress: string): Contract { + private getLiquidityReserveContract(liquidityReserveAddress: string): ethers.Contract { const liquidityReserveContract = this.liquidityReserveContracts.find( - item => toLower(item.options.address) === toLower(liquidityReserveAddress), + item => toLower(item.address) === toLower(liquidityReserveAddress), ) if (!liquidityReserveContract) throw new Error('Not a valid reserve contract address') return liquidityReserveContract } - private async getGasPriceAndNonce(userAddress: string) { - let nonce: number + private async getGasPriceAndNonce( + userAddress: string, + ): Promise<{ nonce: string; gasPrice: string }> { + let nonce try { - nonce = await this.web3.eth.getTransactionCount(userAddress) - } catch (err) { - throw new Error(`Get nonce Error: ${err}`) + nonce = (await this.provider.getTransactionCount(userAddress)).toString() + } catch (e) { + throw new Error(`Get nonce Error: ${e}`) } let gasPrice: string try { - gasPrice = await this.web3.eth.getGasPrice() - } catch (err) { - throw new Error(`Get gasPrice Error: ${err}`) + gasPrice = (await this.provider.getGasPrice()).toString() + } catch (e) { + throw new Error(`Get gasPrice Error: ${e}`) } - return { nonce: String(nonce), gasPrice } + return { nonce, gasPrice } } async getFoxyOpportunities() { @@ -204,21 +204,21 @@ export class FoxyApi { const opportunities = await Promise.all( this.foxyAddresses.map(async addresses => { const stakingContract = this.foxyStakingContracts.find( - item => toLower(item.options.address) === toLower(addresses.staking), + item => toLower(item.address) === toLower(addresses.staking), ) try { - const expired = await stakingContract?.methods.pauseStaking().call() + const expired = await stakingContract?.pauseStaking() const tvl = await this.tvl({ tokenContractAddress: addresses.foxy }) const apy = this.apy() return transformData({ ...addresses, expired, tvl, apy }) - } catch (err) { - throw new Error(`Failed to get contract data ${err}`) + } catch (e) { + throw new Error(`Failed to get contract data ${e}`) } }), ) return opportunities - } catch (err) { - throw new Error(`getFoxyOpportunities Error: ${err}`) + } catch (e) { + throw new Error(`getFoxyOpportunities Error: ${e}`) } } @@ -232,26 +232,26 @@ export class FoxyApi { const stakingContract = this.getStakingContract(addresses.staking) try { - const expired = await stakingContract.methods.pauseStaking().call() + const expired = await stakingContract.pauseStaking() const tvl = await this.tvl({ tokenContractAddress: addresses.foxy }) const apy = this.apy() return transformData({ ...addresses, tvl, apy, expired }) - } catch (err) { - throw new Error(`Failed to get contract data ${err}`) + } catch (e) { + throw new Error(`Failed to get contract data ${e}`) } } - async getGasPrice() { - const gasPrice = await this.web3.eth.getGasPrice() - return bnOrZero(gasPrice) + async getGasPrice(): Promise { + const gasPrice = await this.provider.getGasPrice() + return gasPrice.toString() } - getTxReceipt({ txid }: TxReceipt): Promise { + getTxReceipt({ txid }: TxReceipt): Promise { if (!txid) throw new Error('Must pass txid') - return this.web3.eth.getTransactionReceipt(txid) + return this.provider.getTransactionReceipt(txid) } - async estimateClaimWithdrawGas(input: ClaimWithdrawal): Promise { + async estimateClaimWithdrawGas(input: ClaimWithdrawal): Promise { const { claimAddress, userAddress, contractAddress } = input const addressToClaim = claimAddress ?? userAddress this.verifyAddresses([addressToClaim, userAddress, contractAddress]) @@ -259,34 +259,32 @@ export class FoxyApi { const stakingContract = this.getStakingContract(contractAddress) try { - const estimatedGas = await stakingContract.methods.claimWithdraw(addressToClaim).estimateGas({ + const estimatedGas = await stakingContract.estimateGas.claimWithdraw(addressToClaim, { from: userAddress, }) - return bnOrZero(estimatedGas) - } catch (err) { - throw new Error(`Failed to get gas ${err}`) + return estimatedGas.toString() + } catch (e) { + throw new Error(`Failed to get gas ${e}`) } } - async estimateSendWithdrawalRequestsGas( - input: TxInputWithoutAmountAndWallet, - ): Promise { + async estimateSendWithdrawalRequestsGas(input: TxInputWithoutAmountAndWallet): Promise { const { userAddress, contractAddress } = input this.verifyAddresses([userAddress, contractAddress]) const stakingContract = this.getStakingContract(contractAddress) try { - const estimatedGas = await stakingContract.methods.sendWithdrawalRequests().estimateGas({ + const estimatedGas = await stakingContract.estimateGas.sendWithdrawalRequests([], { from: userAddress, }) - return bnOrZero(estimatedGas) - } catch (err) { - throw new Error(`Failed to get gas ${err}`) + return estimatedGas.toString() + } catch (e) { + throw new Error(`Failed to get gas ${e}`) } } - async estimateAddLiquidityGas(input: EstimateGasTxInput): Promise { + async estimateAddLiquidityGas(input: EstimateGasTxInput): Promise { const { amountDesired, userAddress, contractAddress } = input this.verifyAddresses([userAddress, contractAddress]) if (!amountDesired.gt(0)) throw new Error('Must send valid amount') @@ -294,18 +292,17 @@ export class FoxyApi { const liquidityReserveContract = this.getLiquidityReserveContract(contractAddress) try { - const estimatedGas = await liquidityReserveContract.methods - .addLiquidity(this.normalizeAmount(amountDesired)) - .estimateGas({ - from: userAddress, - }) - return bnOrZero(estimatedGas) - } catch (err) { - throw new Error(`Failed to get gas ${err}`) + const estimatedGas = await liquidityReserveContract.estimateGas.addLiquidity( + this.normalizeAmount(amountDesired), + { from: userAddress }, + ) + return estimatedGas.toString() + } catch (e) { + throw new Error(`Failed to get gas ${e}`) } } - async estimateRemoveLiquidityGas(input: EstimateGasTxInput): Promise { + async estimateRemoveLiquidityGas(input: EstimateGasTxInput): Promise { const { amountDesired, userAddress, contractAddress } = input this.verifyAddresses([userAddress, contractAddress]) if (!amountDesired.gt(0)) throw new Error('Must send valid amount') @@ -313,18 +310,17 @@ export class FoxyApi { const liquidityReserveContract = this.getLiquidityReserveContract(contractAddress) try { - const estimatedGas = await liquidityReserveContract.methods - .removeLiquidity(this.normalizeAmount(amountDesired)) - .estimateGas({ - from: userAddress, - }) - return bnOrZero(estimatedGas) - } catch (err) { - throw new Error(`Failed to get gas ${err}`) + const estimatedGas = await liquidityReserveContract.estimateGas.removeLiquidity( + this.normalizeAmount(amountDesired), + { from: userAddress }, + ) + return estimatedGas.toString() + } catch (e) { + throw new Error(`Failed to get gas ${e}`) } } - async estimateWithdrawGas(input: WithdrawEstimateGasInput): Promise { + async estimateWithdrawGas(input: WithdrawEstimateGasInput): Promise { const { amountDesired, userAddress, contractAddress, type } = input this.verifyAddresses([userAddress, contractAddress]) @@ -335,39 +331,37 @@ export class FoxyApi { try { const estimatedGas = isDelayed - ? await stakingContract.methods - .unstake(this.normalizeAmount(amountDesired), true) - .estimateGas({ - from: userAddress, - }) - : await stakingContract.methods.instantUnstake(true).estimateGas({ - from: userAddress, - }) - return bnOrZero(estimatedGas) - } catch (err) { - throw new Error(`Failed to get gas ${err}`) + ? await stakingContract.estimateGas['unstake(uint256,bool)']( + this.normalizeAmount(amountDesired), + true, + { from: userAddress }, + ) + : await stakingContract.estimateGas.instantUnstake(true, { from: userAddress }) + return estimatedGas.toString() + } catch (e) { + throw new Error(`Failed to get gas ${e}`) } } - async estimateApproveGas(input: EstimateGasApproveInput): Promise { + async estimateApproveGas(input: EstimateGasApproveInput): Promise { const { userAddress, tokenContractAddress, contractAddress } = input this.verifyAddresses([userAddress, contractAddress, tokenContractAddress]) - const depositTokenContract = new this.web3.eth.Contract(erc20Abi, tokenContractAddress) + const depositTokenContract = new ethers.Contract(tokenContractAddress, erc20Abi, this.provider) try { - const estimatedGas = await depositTokenContract.methods - .approve(contractAddress, MAX_ALLOWANCE) - .estimateGas({ - from: userAddress, - }) - return bnOrZero(estimatedGas) - } catch (err) { - throw new Error(`Failed to get gas ${err}`) + const estimatedGas = await depositTokenContract.estimateGas.approve( + contractAddress, + MAX_ALLOWANCE, + { from: userAddress }, + ) + return estimatedGas.toString() + } catch (e) { + throw new Error(`Failed to get gas ${e}`) } } - async estimateDepositGas(input: EstimateGasTxInput): Promise { + async estimateDepositGas(input: EstimateGasTxInput): Promise { const { amountDesired, userAddress, contractAddress } = input this.verifyAddresses([userAddress, contractAddress]) if (!amountDesired.gt(0)) throw new Error('Must send valid amount') @@ -375,14 +369,13 @@ export class FoxyApi { const stakingContract = this.getStakingContract(contractAddress) try { - const estimatedGas = await stakingContract.methods - .stake(this.normalizeAmount(amountDesired), userAddress) - .estimateGas({ - from: userAddress, - }) - return bnOrZero(estimatedGas) - } catch (err) { - throw new Error(`Failed to get gas ${err}`) + const estimatedGas = await stakingContract.estimateGas['stake(uint256)']( + this.normalizeAmount(amountDesired), + { from: userAddress }, + ) + return estimatedGas.toString() + } catch (e) { + throw new Error(`Failed to get gas ${e}`) } } @@ -399,25 +392,20 @@ export class FoxyApi { this.verifyAddresses([userAddress, contractAddress, tokenContractAddress]) if (!wallet) throw new Error('Missing inputs') - let estimatedGasBN: BigNumber + let estimatedGas: string try { - estimatedGasBN = await this.estimateApproveGas(input) - } catch (err) { - throw new Error(`Estimate Gas Error: ${err}`) + estimatedGas = await this.estimateApproveGas(input) + } catch (e) { + throw new Error(`Estimate Gas Error: ${e}`) } - const depositTokenContract = new this.web3.eth.Contract(erc20Abi, tokenContractAddress) - const data: string = depositTokenContract.methods - .approve( - contractAddress, - amount ? numberToHex(this.normalizeAmount(bnOrZero(amount))) : MAX_ALLOWANCE, - ) - .encodeABI({ - from: userAddress, - }) + const depositTokenContract = new ethers.Contract(tokenContractAddress, erc20Abi, this.provider) + const data: string = depositTokenContract.interface.encodeFunctionData('approve', [ + contractAddress, + amount ? numberToHex(bnOrZero(amount).toString()) : MAX_ALLOWANCE, + ]) const { nonce, gasPrice } = await this.getGasPriceAndNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) - const estimatedGas = estimatedGasBN.toString() const payload = { bip44Params, chainId: chainReferenceAsNumber, @@ -435,18 +423,19 @@ export class FoxyApi { const { userAddress, tokenContractAddress, contractAddress } = input this.verifyAddresses([userAddress, contractAddress, tokenContractAddress]) - const depositTokenContract: Contract = new this.web3.eth.Contract( - erc20Abi, + const depositTokenContract: ethers.Contract = new ethers.Contract( tokenContractAddress, + erc20Abi, + this.provider, ) let allowance try { - allowance = await depositTokenContract.methods.allowance(userAddress, contractAddress).call() - } catch (err) { - throw new Error(`Failed to get allowance ${err}`) + allowance = await depositTokenContract.allowance(userAddress, contractAddress) + } catch (e) { + throw new Error(`Failed to get allowance ${e}`) } - return allowance + return allowance.toString() } async deposit(input: TxInput): Promise { @@ -462,25 +451,21 @@ export class FoxyApi { if (!amountDesired.gt(0)) throw new Error('Must send valid amount') if (!wallet) throw new Error('Missing inputs') - let estimatedGasBN: BigNumber + let estimatedGas: string try { - estimatedGasBN = await this.estimateDepositGas(input) - } catch (err) { - throw new Error(`Estimate Gas Error: ${err}`) + estimatedGas = await this.estimateDepositGas(input) + } catch (e) { + throw new Error(`Estimate Gas Error: ${e}`) } const stakingContract = this.getStakingContract(contractAddress) - const userChecksum = this.web3.utils.toChecksumAddress(userAddress) - const data: string = await stakingContract.methods - .stake(this.normalizeAmount(amountDesired), userAddress) - .encodeABI({ - value: 0, - from: userChecksum, - }) + const data = stakingContract.interface.encodeFunctionData('stake(uint256,address)', [ + this.normalizeAmount(amountDesired), + userAddress, + ]) const { nonce, gasPrice } = await this.getGasPriceAndNonce(userAddress) - const estimatedGas = estimatedGasBN.toString() const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, @@ -508,11 +493,11 @@ export class FoxyApi { this.verifyAddresses([userAddress, contractAddress]) if (!wallet) throw new Error('Missing inputs') - let estimatedGasBN: BigNumber + let estimatedGas: string try { - estimatedGasBN = await this.estimateWithdrawGas(input) - } catch (err) { - throw new Error(`Estimate Gas Error: ${err}`) + estimatedGas = await this.estimateWithdrawGas(input) + } catch (e) { + throw new Error(`Estimate Gas Error: ${e}`) } const stakingContract = this.getStakingContract(contractAddress) @@ -520,16 +505,14 @@ export class FoxyApi { const isDelayed = type === WithdrawType.DELAYED && amountDesired if (isDelayed && !amountDesired.gt(0)) throw new Error('Must send valid amount') - const data: string = isDelayed - ? stakingContract.methods.unstake(this.normalizeAmount(amountDesired), true).encodeABI({ - from: userAddress, - }) - : stakingContract.methods.instantUnstake(true).encodeABI({ - from: userAddress, - }) + const stakingContractCallInput: Parameters< + typeof stakingContract.interface.encodeFunctionData + > = isDelayed + ? ['unstake(uint256,bool)', [this.normalizeAmount(amountDesired), true]] + : ['instantUnstake', ['true']] + const data: string = stakingContract.interface.encodeFunctionData(...stakingContractCallInput) const { nonce, gasPrice } = await this.getGasPriceAndNonce(userAddress) - const estimatedGas = estimatedGasBN.toString() const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, @@ -546,54 +529,58 @@ export class FoxyApi { async canClaimWithdraw(input: CanClaimWithdrawParams): Promise { const { userAddress, contractAddress } = input - const tokeManagerContract = new this.web3.eth.Contract(tokeManagerAbi, tokeManagerAddress) - const tokePoolContract = new this.web3.eth.Contract(tokePoolAbi, tokePoolAddress) + const tokeManagerContract = new ethers.Contract( + tokeManagerAddress, + tokeManagerAbi, + this.provider, + ) + const tokePoolContract = new ethers.Contract(tokePoolAddress, tokePoolAbi, this.provider) const stakingContract = this.getStakingContract(contractAddress) const coolDownInfo = await (async () => { try { - const coolDown = await stakingContract.methods.coolDownInfo(userAddress).call() + const coolDown = await stakingContract.coolDownInfo(userAddress) return { ...coolDown, endEpoch: coolDown.expiry, } - } catch (err) { - logger.error(err, 'failed to get coolDowninfo') + } catch (e) { + logger.error(e, 'failed to get coolDowninfo') } })() const epoch = await (() => { try { - return stakingContract.methods.epoch().call() - } catch (err) { - logger.error(err, 'failed to get epoch') + return stakingContract.epoch() + } catch (e) { + logger.error(e, 'failed to get epoch') return {} } })() const requestedWithdrawals = await (() => { try { - return tokePoolContract.methods.requestedWithdrawals(stakingContract.options.address).call() - } catch (err) { - logger.error(err, 'failed to get requestedWithdrawals') + return tokePoolContract.requestedWithdrawals(stakingContract.address) + } catch (e) { + logger.error(e, 'failed to get requestedWithdrawals') return {} } })() const currentCycleIndex = await (() => { try { - return tokeManagerContract.methods.getCurrentCycleIndex().call() - } catch (err) { - logger.error(err, 'failed to get currentCycleIndex') + return tokeManagerContract.getCurrentCycleIndex() + } catch (e) { + logger.error(e, 'failed to get currentCycleIndex') return 0 } })() const withdrawalAmount = await (() => { try { - return stakingContract.methods.withdrawalAmount().call() - } catch (err) { - logger.error(err, 'failed to get currentCycleIndex') + return stakingContract.withdrawalAmount() + } catch (e) { + logger.error(e, 'failed to get currentCycleIndex') return 0 } })() @@ -627,11 +614,11 @@ export class FoxyApi { this.verifyAddresses([userAddress, contractAddress, addressToClaim]) if (!wallet) throw new Error('Missing inputs') - let estimatedGasBN: BigNumber + let estimatedGas: string try { - estimatedGasBN = await this.estimateClaimWithdrawGas(input) - } catch (err) { - throw new Error(`Estimate Gas Error: ${err}`) + estimatedGas = await this.estimateClaimWithdrawGas(input) + } catch (e) { + throw new Error(`Estimate Gas Error: ${e}`) } const stakingContract = this.getStakingContract(contractAddress) @@ -639,12 +626,11 @@ export class FoxyApi { const canClaim = await this.canClaimWithdraw({ userAddress, contractAddress }) if (!canClaim) throw new Error('Not ready to claim') - const data: string = stakingContract.methods.claimWithdraw(addressToClaim).encodeABI({ - from: userAddress, - }) + const data: string = stakingContract.interface.encodeFunctionData('claimWithdraw', [ + addressToClaim, + ]) const { nonce, gasPrice } = await this.getGasPriceAndNonce(userAddress) - const estimatedGas = estimatedGasBN.toString() const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, @@ -661,22 +647,26 @@ export class FoxyApi { async canSendWithdrawalRequest(input: StakingContract): Promise { const { stakingContract } = input - const tokeManagerContract = new this.web3.eth.Contract(tokeManagerAbi, tokeManagerAddress) + const tokeManagerContract = new ethers.Contract( + tokeManagerAddress, + tokeManagerAbi, + this.provider, + ) const requestWithdrawalAmount = await (() => { try { - return stakingContract.methods.requestWithdrawalAmount().call() - } catch (err) { - logger.error(err, 'failed to get requestWithdrawalAmount') + return stakingContract.requestWithdrawalAmount() + } catch (e) { + logger.error(e, 'failed to get requestWithdrawalAmount') return 0 } })() const timeLeftToRequestWithdrawal = await (() => { try { - return stakingContract.methods.timeLeftToRequestWithdrawal().call() - } catch (err) { - logger.error(err, 'failed to get timeLeftToRequestWithdrawal') + return stakingContract.timeLeftToRequestWithdrawal() + } catch (e) { + logger.error(e, 'failed to get timeLeftToRequestWithdrawal') return 0 } })() @@ -692,35 +682,35 @@ export class FoxyApi { const duration = await (() => { try { - return tokeManagerContract.methods.getCycleDuration().call() - } catch (err) { - logger.error(err, 'failed to get cycleDuration') + return tokeManagerContract.getCycleDuration() + } catch (e) { + logger.error(e, 'failed to get cycleDuration') return 0 } })() const currentCycleIndex = await (() => { try { - return tokeManagerContract.methods.getCurrentCycleIndex().call() - } catch (err) { - logger.error(err, 'failed to get currentCycleIndex') + return tokeManagerContract.getCurrentCycleIndex() + } catch (e) { + logger.error(e, 'failed to get currentCycleIndex') return 0 } })() const currentCycleStart = await (() => { try { - return tokeManagerContract.methods.getCurrentCycle().call() - } catch (err) { - logger.error(err, 'failed to get currentCycle') + return tokeManagerContract.getCurrentCycle() + } catch (e) { + logger.error(e, 'failed to get currentCycle') return 0 } })() const nextCycleStart = bnOrZero(currentCycleStart).plus(duration) - const blockNumber = await this.web3.eth.getBlockNumber() - const timestamp = (await this.web3.eth.getBlock(blockNumber)).timestamp + const blockNumber = await this.provider.getBlockNumber() + const timestamp = (await this.provider.getBlock(blockNumber)).timestamp const isTimeToRequest = bnOrZero(timestamp) .plus(timeLeftToRequestWithdrawal) @@ -736,11 +726,11 @@ export class FoxyApi { this.verifyAddresses([userAddress, contractAddress]) if (!wallet || !contractAddress) throw new Error('Missing inputs') - let estimatedGasBN: BigNumber + let estimatedGas: string try { - estimatedGasBN = await this.estimateSendWithdrawalRequestsGas(input) - } catch (err) { - throw new Error(`Estimate Gas Error: ${err}`) + estimatedGas = await this.estimateSendWithdrawalRequestsGas(input) + } catch (e) { + throw new Error(`Estimate Gas Error: ${e}`) } const stakingContract = this.getStakingContract(contractAddress) @@ -748,12 +738,8 @@ export class FoxyApi { const canSendRequest = await this.canSendWithdrawalRequest({ stakingContract }) if (!canSendRequest) throw new Error('Not ready to send request') - const data: string = stakingContract.methods.sendWithdrawalRequests().encodeABI({ - from: userAddress, - }) - + const data: string = stakingContract.interface.encodeFunctionData('sendWithdrawalRequests') const { nonce, gasPrice } = await this.getGasPriceAndNonce(userAddress) - const estimatedGas = estimatedGasBN.toString() const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, @@ -784,23 +770,20 @@ export class FoxyApi { if (!wallet) throw new Error('Missing inputs') - let estimatedGasBN: BigNumber + let estimatedGas: string try { - estimatedGasBN = await this.estimateAddLiquidityGas(input) - } catch (err) { - throw new Error(`Estimate Gas Error: ${err}`) + estimatedGas = await this.estimateAddLiquidityGas(input) + } catch (e) { + throw new Error(`Estimate Gas Error: ${e}`) } const liquidityReserveContract = this.getLiquidityReserveContract(contractAddress) - const data: string = liquidityReserveContract.methods - .addLiquidity(this.normalizeAmount(amountDesired)) - .encodeABI({ - from: userAddress, - }) + const data: string = liquidityReserveContract.interface.encodeFunctionData('addLiquidity', [ + this.normalizeAmount(amountDesired), + ]) const { nonce, gasPrice } = await this.getGasPriceAndNonce(userAddress) - const estimatedGas = estimatedGasBN.toString() const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, @@ -830,23 +813,20 @@ export class FoxyApi { if (!amountDesired.gt(0)) throw new Error('Must send valid amount') if (!wallet) throw new Error('Missing inputs') - let estimatedGasBN: BigNumber + let estimatedGas: string try { - estimatedGasBN = await this.estimateRemoveLiquidityGas(input) - } catch (err) { - throw new Error(`Estimate Gas Error: ${err}`) + estimatedGas = await this.estimateRemoveLiquidityGas(input) + } catch (e) { + throw new Error(`Estimate Gas Error: ${e}`) } const liquidityReserveContract = this.getLiquidityReserveContract(contractAddress) - const data: string = liquidityReserveContract.methods - .removeLiquidity(this.normalizeAmount(amountDesired)) - .encodeABI({ - from: userAddress, - }) + const data: string = liquidityReserveContract.interface.encodeFunctionData('removeLiquidity', [ + this.normalizeAmount(amountDesired), + ]) const { nonce, gasPrice } = await this.getGasPriceAndNonce(userAddress) - const estimatedGas = estimatedGasBN.toString() const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, @@ -870,25 +850,25 @@ export class FoxyApi { let coolDownInfo try { - const coolDown = await stakingContract.methods.coolDownInfo(userAddress).call() + const coolDown = await stakingContract.coolDownInfo(userAddress) coolDownInfo = { ...coolDown, endEpoch: coolDown.expiry, } - } catch (err) { - throw new Error(`Failed to get coolDowninfo: ${err}`) + } catch (e) { + throw new Error(`Failed to get coolDowninfo: ${e}`) } let epoch try { - epoch = await stakingContract.methods.epoch().call() - } catch (err) { - throw new Error(`Failed to get epoch: ${err}`) + epoch = await stakingContract.epoch() + } catch (e) { + throw new Error(`Failed to get epoch: ${e}`) } let currentBlock try { - currentBlock = await this.web3.eth.getBlockNumber() - } catch (err) { - throw new Error(`Failed to get block number: ${err}`) + currentBlock = await this.provider.getBlockNumber() + } catch (e) { + throw new Error(`Failed to get block number: ${e}`) } const epochsLeft = bnOrZero(coolDownInfo.endEpoch).minus(epoch.number) // epochs left until can claim const blocksLeftInCurrentEpoch = @@ -908,12 +888,12 @@ export class FoxyApi { const { tokenContractAddress, userAddress } = input this.verifyAddresses([userAddress, tokenContractAddress]) - const contract = new this.web3.eth.Contract(erc20Abi, tokenContractAddress) + const contract = new ethers.Contract(tokenContractAddress, erc20Abi, this.provider) try { - const balance = await contract.methods.balanceOf(userAddress).call() + const balance = await contract.balanceOf(userAddress) return bnOrZero(balance) - } catch (err) { - throw new Error(`Failed to get balance: ${err}`) + } catch (e) { + throw new Error(`Failed to get balance: ${e}`) } } @@ -924,28 +904,28 @@ export class FoxyApi { let liquidityReserveAddress try { - liquidityReserveAddress = await stakingContract.methods.LIQUIDITY_RESERVE().call() - } catch (err) { - throw new Error(`Failed to get liquidityReserve address ${err}`) + liquidityReserveAddress = await stakingContract.LIQUIDITY_RESERVE() + } catch (e) { + throw new Error(`Failed to get liquidityReserve address ${e}`) } const liquidityReserveContract = this.getLiquidityReserveContract(liquidityReserveAddress) try { - const feeInBasisPoints = await liquidityReserveContract.methods.fee().call() + const feeInBasisPoints = await liquidityReserveContract.fee() return bnOrZero(feeInBasisPoints).div(10000) // convert from basis points to decimal percentage - } catch (err) { - throw new Error(`Failed to get instantUnstake fee ${err}`) + } catch (e) { + throw new Error(`Failed to get instantUnstake fee ${e}`) } } async totalSupply({ tokenContractAddress }: TokenAddressInput): Promise { this.verifyAddresses([tokenContractAddress]) - const contract = new this.web3.eth.Contract(erc20Abi, tokenContractAddress) + const contract = new ethers.Contract(tokenContractAddress, erc20Abi, this.provider) try { - const totalSupply = await contract.methods.totalSupply().call() + const totalSupply = await contract.totalSupply() return bnOrZero(totalSupply) - } catch (err) { - throw new Error(`Failed to get totalSupply: ${err}`) + } catch (e) { + throw new Error(`Failed to get totalSupply: ${e}`) } } @@ -961,13 +941,13 @@ export class FoxyApi { async tvl(input: TokenAddressInput): Promise { const { tokenContractAddress } = input this.verifyAddresses([tokenContractAddress]) - const contract = new this.web3.eth.Contract(foxyAbi, tokenContractAddress) + const contract = new ethers.Contract(tokenContractAddress, foxyAbi, this.provider) try { - const balance = await contract.methods.circulatingSupply().call() + const balance = await contract.circulatingSupply() return bnOrZero(balance) - } catch (err) { - throw new Error(`Failed to get tvl: ${err}`) + } catch (e) { + throw new Error(`Failed to get tvl: ${e}`) } } @@ -976,39 +956,49 @@ export class FoxyApi { this.verifyAddresses([userAddress, contractAddress]) const stakingContract = this.getStakingContract(contractAddress) - let coolDownInfo + let coolDownInfo: [amount: string, gons: string, expiry: string] try { - coolDownInfo = await stakingContract.methods.coolDownInfo(userAddress).call() - } catch (err) { - throw new Error(`Failed to get coolDowninfo: ${err}`) + coolDownInfo = (await stakingContract.coolDownInfo(userAddress)).map( + (info: ethers.BigNumber) => info.toString(), + ) + } catch (e) { + throw new Error(`Failed to get coolDowninfo: ${e}`) } let releaseTime try { releaseTime = await this.getTimeUntilClaimable(input) - } catch (err) { - throw new Error(`Failed to getTimeUntilClaimable: ${err}`) + } catch (e) { + throw new Error(`Failed to getTimeUntilClaimable: ${e}`) } + + const [amount, gons, expiry] = coolDownInfo return { - ...coolDownInfo, + amount, + gons, + expiry, releaseTime, } } async getClaimFromTokemakArgs(input: ContractAddressInput): Promise { const { contractAddress } = input - const rewardHashContract = new this.web3.eth.Contract(tokeRewardHashAbi, tokeRewardHashAddress) + const rewardHashContract = new ethers.Contract( + tokeRewardHashAddress, + tokeRewardHashAbi, + this.provider, + ) const latestCycleIndex = await (() => { try { - return rewardHashContract.methods.latestCycleIndex().call() - } catch (err) { - throw new Error(`Failed to get latestCycleIndex, ${err}`) + return rewardHashContract.latestCycleIndex() + } catch (e) { + throw new Error(`Failed to get latestCycleIndex, ${e}`) } })() const cycleHashes = await (() => { try { - return rewardHashContract.methods.cycleHashes(latestCycleIndex).call() - } catch (err) { - throw new Error(`Failed to get latestCycleIndex, ${err}`) + return rewardHashContract.cycleHashes(latestCycleIndex) + } catch (e) { + throw new Error(`Failed to get latestCycleIndex, ${e}`) } })() @@ -1030,8 +1020,8 @@ export class FoxyApi { s, recipient: payload, } - } catch (err) { - throw new Error(`Failed to get information from Tokemak ipfs ${err}`) + } catch (e) { + throw new Error(`Failed to get information from Tokemak ipfs ${e}`) } } @@ -1039,20 +1029,19 @@ export class FoxyApi { const { tokenContractAddress, userAddress } = input this.verifyAddresses([tokenContractAddress]) - const foxyContract = new this.web3.eth.Contract(foxyAbi, tokenContractAddress) + const foxyContract = new ethers.Contract(tokenContractAddress, foxyAbi, this.provider) const fromBlock = 14381454 // genesis rebase const rebaseEvents = await (async () => { try { - const events = ( - await foxyContract.getPastEvents('LogRebase', { - fromBlock, - toBlock: 'latest', - }) - ).filter(rebase => rebase.returnValues.rebase !== '0') - return events - } catch (err) { - logger.error(err, 'failed to get rebase events') + const filter = foxyContract.filters.LogRebase() + const events = await foxyContract.queryFilter(filter, fromBlock, 'latest') + const filteredEvents = events.filter( + rebase => rebase.args?.rebase && !rebase.args.rebase.isZero(), + ) + return filteredEvents + } catch (e) { + logger.error(e, 'failed to get rebase events') return undefined } })() @@ -1061,22 +1050,17 @@ export class FoxyApi { const transferEvents = await (async () => { try { - const events = await foxyContract.getPastEvents('Transfer', { - fromBlock, - toBlock: 'latest', - }) + const filter = foxyContract.filters.Transfer() + const events = await foxyContract.queryFilter(filter, fromBlock, 'latest') return events - } catch (err) { - logger.error(err, 'failed to get transfer events') + } catch (e) { + logger.error(e, 'failed to get transfer events') return undefined } })() const events: RebaseEvent[] = rebaseEvents.map(rebaseEvent => { - const { - blockNumber, - returnValues: { epoch }, - } = rebaseEvent + const { blockNumber, args: { epoch } = { epoch: '' } } = rebaseEvent return { blockNumber, epoch, @@ -1097,23 +1081,20 @@ export class FoxyApi { // check transfer events to see if a user triggered a rebase through unstake or stake const unstakedTransferInfo = transferEvents?.filter( e => - e.blockNumber === event.blockNumber && - e.returnValues.from.toLowerCase() === userAddress, + e.blockNumber === event.blockNumber && e.args?.from.toLowerCase() === userAddress, ) - const unstakedTransferAmount = unstakedTransferInfo?.[0]?.returnValues?.value ?? 0 + const unstakedTransferAmount = unstakedTransferInfo?.[0]?.args?.value ?? 0 const stakedTransferInfo = transferEvents?.filter( - e => - e.blockNumber === event.blockNumber && - e.returnValues.to.toLowerCase() === userAddress, + e => e.blockNumber === event.blockNumber && e.args?.to.toLowerCase() === userAddress, ) - const stakedTransferAmount = stakedTransferInfo?.[0]?.returnValues?.value ?? 0 + const stakedTransferAmount = stakedTransferInfo?.[0]?.args?.value ?? 0 - const postRebaseBalanceResult = await foxyContract.methods - .balanceOf(userAddress) - .call(null, event.blockNumber) - const unadjustedPreRebaseBalance = await foxyContract.methods - .balanceOf(userAddress) - .call(null, event.blockNumber - 1) + const postRebaseBalanceResult = await foxyContract.balanceOf(userAddress, { + blockTag: event.blockNumber, + }) + const unadjustedPreRebaseBalance = await foxyContract.balanceOf(userAddress, { + blockTag: event.blockNumber - 1, + }) // unstake events can trigger rebases, if they do, adjust the amount to not include that unstake's transfer amount const preRebaseBalanceResult = bnOrZero(unadjustedPreRebaseBalance) @@ -1125,8 +1106,8 @@ export class FoxyApi { preRebaseBalance: preRebaseBalanceResult, postRebaseBalance: postRebaseBalanceResult, } - } catch (err) { - logger.error(err, 'failed to get balance of address') + } catch (e) { + logger.error(e, 'failed to get balance of address') return { preRebaseBalance: bn(0).toString(), postRebaseBalance: bn(0).toString(), @@ -1136,10 +1117,10 @@ export class FoxyApi { const blockTime = await (async () => { try { - const block = await this.web3.eth.getBlock(event.blockNumber) + const block = await this.provider.getBlock(event.blockNumber) return bnOrZero(block.timestamp).toNumber() - } catch (err) { - logger.error(err, 'failed to get timestamp of block') + } catch (e) { + logger.error(e, 'failed to get timestamp of block') return 0 } })() diff --git a/packages/investor-foxy/src/api/foxy-types.ts b/packages/investor-foxy/src/api/foxy-types.ts index ef81dde1806..4f464581859 100644 --- a/packages/investor-foxy/src/api/foxy-types.ts +++ b/packages/investor-foxy/src/api/foxy-types.ts @@ -2,7 +2,7 @@ import type { AssetId } from '@shapeshiftoss/caip' import type { HDWallet } from '@shapeshiftoss/hdwallet-core' import type { BIP44Params, WithdrawType } from '@shapeshiftoss/types' import type { BigNumber } from 'bignumber.js' -import type { Contract } from 'web3-eth-contract' +import type ethers from 'ethers' export type FoxyAddressesType = { staking: string @@ -149,7 +149,7 @@ export type RebaseHistory = { } export type StakingContract = { - stakingContract: Contract + stakingContract: ethers.ethers.Contract } // this comment only exists to publish this package - delete me if you see me diff --git a/yarn.lock b/yarn.lock index 1f985276cbc..067ac2d24be 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4180,7 +4180,7 @@ __metadata: languageName: node linkType: hard -"@ethersproject/providers@npm:5.7.2, @ethersproject/providers@npm:^5.5.3": +"@ethersproject/providers@npm:5.7.2, @ethersproject/providers@npm:^5.5.3, @ethersproject/providers@npm:^5.7.2": version: 5.7.2 resolution: "@ethersproject/providers@npm:5.7.2" dependencies: @@ -6140,12 +6140,13 @@ __metadata: version: 0.0.0-use.local resolution: "@shapeshiftoss/investor-foxy@workspace:packages/investor-foxy" dependencies: - "@ethersproject/providers": ^5.5.3 + "@ethersproject/providers": ^5.7.2 "@shapeshiftoss/caip": "workspace:^" "@shapeshiftoss/chain-adapters": "workspace:^" "@shapeshiftoss/logger": "workspace:^" "@shapeshiftoss/types": "workspace:^" "@types/readline-sync": ^1.4.4 + ethers: ^5.7.2 readline-sync: ^1.4.10 web3-core: 1.7.4 web3-utils: 1.7.4 From 5712539e2027e26acd55fc63b4095b75dd79bb9b Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Sun, 23 Apr 2023 19:33:15 +0200 Subject: [PATCH 02/29] feat: reapply web/3508 --- .../components/FoxyManager/Deposit/components/Confirm.tsx | 6 ++++-- .../components/FoxyManager/Overview/Claim/ClaimStatus.tsx | 2 +- .../components/FoxyManager/Withdraw/components/Confirm.tsx | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx index ccea6722c07..a3ec1e432f0 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx @@ -106,8 +106,10 @@ export const Confirm: React.FC = ({ onNext, accountId }) => { dispatch({ type: FoxyDepositActionType.SET_DEPOSIT, payload: { - txStatus: transactionReceipt.status === true ? 'success' : 'failed', - usedGasFeeCryptoBaseUnit: bnOrZero(gasPrice).times(transactionReceipt.gasUsed).toFixed(0), + txStatus: transactionReceipt.status ? 'success' : 'failed', + usedGasFeeCryptoBaseUnit: bnOrZero(gasPrice) + .times(transactionReceipt.gasUsed.toString()) + .toFixed(0), }, }) } catch (error) { diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx index 8865be1aa0b..4306ad06bff 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx @@ -134,7 +134,7 @@ export const ClaimStatus: React.FC = ({ accountId }) => { setState({ ...state, txStatus: transactionReceipt.status ? TxStatus.SUCCESS : TxStatus.FAILED, - usedGasFee: bnOrZero(gasPrice).times(transactionReceipt.gasUsed).toFixed(0), + usedGasFee: bnOrZero(gasPrice).times(transactionReceipt.gasUsed.toString()).toFixed(0), }) } catch (error) { moduleLogger.error(error, 'ClaimStatus error') diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx index 8ff80bf9699..6b6a4663e23 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx @@ -113,7 +113,7 @@ export const Confirm: React.FC Date: Sun, 23 Apr 2023 19:34:49 +0200 Subject: [PATCH 03/29] fix: types --- .../components/FoxyManager/Deposit/components/Confirm.tsx | 4 ++-- .../components/FoxyManager/Overview/Claim/ClaimStatus.tsx | 4 ++-- .../components/FoxyManager/Withdraw/components/Confirm.tsx | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx index a3ec1e432f0..39b4d00d97a 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx @@ -1,6 +1,7 @@ import { Alert, AlertIcon, Box, Stack, useToast } from '@chakra-ui/react' import type { AccountId } from '@shapeshiftoss/caip' import { fromAccountId } from '@shapeshiftoss/caip' +import type { ethers } from 'ethers' import { Confirm as ReusableConfirm } from 'features/defi/components/Confirm/Confirm' import { Summary } from 'features/defi/components/Summary' import { DefiStep } from 'features/defi/contexts/DefiManagerProvider/DefiCommon' @@ -8,7 +9,6 @@ import { useFoxyQuery } from 'features/defi/providers/foxy/components/FoxyManage import isNil from 'lodash/isNil' import { useCallback, useContext, useMemo } from 'react' import { useTranslate } from 'react-polyglot' -import type { TransactionReceipt } from 'web3-core/types' import { Amount } from 'components/Amount/Amount' import { AssetIcon } from 'components/AssetIcon' import type { StepComponentProps } from 'components/DeFi/components/Steps' @@ -99,7 +99,7 @@ export const Confirm: React.FC = ({ onNext, accountId }) => { const transactionReceipt = await poll({ fn: () => foxyApi.getTxReceipt({ txid }), - validate: (result: TransactionReceipt) => !isNil(result), + validate: (result: ethers.providers.TransactionReceipt) => !isNil(result), interval: 15000, maxAttempts: 30, }) diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx index 4306ad06bff..781a6414750 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx @@ -1,13 +1,13 @@ import { Box, Button, Center, Link, ModalBody, ModalFooter, Stack } from '@chakra-ui/react' import type { AccountId, AssetId, ChainId } from '@shapeshiftoss/caip' import { ASSET_REFERENCE, toAssetId } from '@shapeshiftoss/caip' +import type { ethers } from 'ethers' import { DefiProvider, DefiType } from 'features/defi/contexts/DefiManagerProvider/DefiCommon' import isNil from 'lodash/isNil' import { useCallback, useEffect, useState } from 'react' import { FaCheck, FaTimes } from 'react-icons/fa' import { useTranslate } from 'react-polyglot' import { useLocation } from 'react-router' -import type { TransactionReceipt } from 'web3-core/types' import { Amount } from 'components/Amount/Amount' import { AssetIcon } from 'components/AssetIcon' import { CircularProgress } from 'components/CircularProgress/CircularProgress' @@ -121,7 +121,7 @@ export const ClaimStatus: React.FC = ({ accountId }) => { try { const transactionReceipt = await poll({ fn: () => foxyApi.getTxReceipt({ txid }), - validate: (result: TransactionReceipt) => !isNil(result), + validate: (result: ethers.providers.TransactionReceipt) => !isNil(result), interval: 15000, maxAttempts: 30, }) diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx index 6b6a4663e23..5d6551d806d 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx @@ -2,6 +2,7 @@ import { Alert, AlertIcon, Box, Stack } from '@chakra-ui/react' import type { AccountId } from '@shapeshiftoss/caip' import { fromAccountId } from '@shapeshiftoss/caip' import { WithdrawType } from '@shapeshiftoss/types' +import type { ethers } from 'ethers' import { Confirm as ReusableConfirm } from 'features/defi/components/Confirm/Confirm' import { Summary } from 'features/defi/components/Summary' import { DefiStep } from 'features/defi/contexts/DefiManagerProvider/DefiCommon' @@ -9,7 +10,6 @@ import { useFoxyQuery } from 'features/defi/providers/foxy/components/FoxyManage import isNil from 'lodash/isNil' import { useCallback, useContext, useMemo } from 'react' import { useTranslate } from 'react-polyglot' -import type { TransactionReceipt } from 'web3-core/types' import { Amount } from 'components/Amount/Amount' import { AssetIcon } from 'components/AssetIcon' import type { StepComponentProps } from 'components/DeFi/components/Steps' @@ -104,7 +104,7 @@ export const Confirm: React.FC foxyApi.getTxReceipt({ txid }), - validate: (result: TransactionReceipt) => !isNil(result), + validate: (result: ethers.providers.TransactionReceipt) => !isNil(result), interval: 15000, maxAttempts: 30, }) From 838f7ec57218bf20f2ad7b5b362915a08dd4a36a Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Sun, 23 Apr 2023 19:44:30 +0200 Subject: [PATCH 04/29] feat: use consistent ethers version across packages --- package.json | 2 +- packages/asset-service/package.json | 2 +- packages/investor-idle/package.json | 2 +- packages/investor-yearn/package.json | 2 +- packages/market-service/package.json | 2 +- yarn.lock | 14 +++++++------- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/package.json b/package.json index d78ff532191..d1a5347fb40 100644 --- a/package.json +++ b/package.json @@ -134,7 +134,7 @@ "embla-carousel-react": "^7.0.5", "envalid": "^7.3.1", "eth-url-parser": "^1.0.4", - "ethers": "^5.5.3", + "ethers": "^5.7.2", "framer-motion": "^6.3.11", "friendly-challenge": "0.9.2", "grapheme-splitter": "^1.0.4", diff --git a/packages/asset-service/package.json b/packages/asset-service/package.json index b93b0b4912c..f98895d60fb 100644 --- a/packages/asset-service/package.json +++ b/packages/asset-service/package.json @@ -29,7 +29,7 @@ "js-pixel-fonts": "^1.5.0" }, "devDependencies": { - "@ethersproject/providers": "^5.5.3", + "@ethersproject/providers": "^5.7.2", "@yfi/sdk": "^1.2.0", "colorthief": "^2.3.2" } diff --git a/packages/investor-idle/package.json b/packages/investor-idle/package.json index 6c498e03ec4..a7ebc2b7f53 100644 --- a/packages/investor-idle/package.json +++ b/packages/investor-idle/package.json @@ -21,7 +21,7 @@ "cli": "yarn build && yarn node dist/idlecli.js" }, "dependencies": { - "@ethersproject/providers": "^5.5.3", + "@ethersproject/providers": "^5.7.2", "@shapeshiftoss/caip": "workspace:^", "@shapeshiftoss/chain-adapters": "workspace:^", "@shapeshiftoss/investor": "workspace:^", diff --git a/packages/investor-yearn/package.json b/packages/investor-yearn/package.json index 3ff0b9af293..21bb01901e6 100644 --- a/packages/investor-yearn/package.json +++ b/packages/investor-yearn/package.json @@ -21,7 +21,7 @@ "cli": "yarn build && yarn node dist/yearncli.js" }, "dependencies": { - "@ethersproject/providers": "^5.5.3", + "@ethersproject/providers": "^5.7.2", "@shapeshiftoss/caip": "workspace:^", "@shapeshiftoss/chain-adapters": "workspace:^", "@shapeshiftoss/investor": "workspace:^", diff --git a/packages/market-service/package.json b/packages/market-service/package.json index 27bae5a8325..2a209453a1b 100644 --- a/packages/market-service/package.json +++ b/packages/market-service/package.json @@ -18,7 +18,7 @@ "dev": "yarn run -T tsc --build --watch" }, "dependencies": { - "@ethersproject/providers": "^5.5.3", + "@ethersproject/providers": "^5.7.2", "@shapeshiftoss/caip": "workspace:^", "@shapeshiftoss/chain-adapters": "workspace:^", "@shapeshiftoss/investor-foxy": "workspace:^", diff --git a/yarn.lock b/yarn.lock index 067ac2d24be..38225489cfd 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4180,7 +4180,7 @@ __metadata: languageName: node linkType: hard -"@ethersproject/providers@npm:5.7.2, @ethersproject/providers@npm:^5.5.3, @ethersproject/providers@npm:^5.7.2": +"@ethersproject/providers@npm:5.7.2, @ethersproject/providers@npm:^5.7.2": version: 5.7.2 resolution: "@ethersproject/providers@npm:5.7.2" dependencies: @@ -5830,7 +5830,7 @@ __metadata: version: 0.0.0-use.local resolution: "@shapeshiftoss/asset-service@workspace:packages/asset-service" dependencies: - "@ethersproject/providers": ^5.5.3 + "@ethersproject/providers": ^5.7.2 "@shapeshiftoss/caip": "workspace:^" "@shapeshiftoss/investor-idle": "workspace:^" "@shapeshiftoss/types": "workspace:^" @@ -6157,7 +6157,7 @@ __metadata: version: 0.0.0-use.local resolution: "@shapeshiftoss/investor-idle@workspace:packages/investor-idle" dependencies: - "@ethersproject/providers": ^5.5.3 + "@ethersproject/providers": ^5.7.2 "@shapeshiftoss/caip": "workspace:^" "@shapeshiftoss/chain-adapters": "workspace:^" "@shapeshiftoss/investor": "workspace:^" @@ -6172,7 +6172,7 @@ __metadata: version: 0.0.0-use.local resolution: "@shapeshiftoss/investor-yearn@workspace:packages/investor-yearn" dependencies: - "@ethersproject/providers": ^5.5.3 + "@ethersproject/providers": ^5.7.2 "@shapeshiftoss/caip": "workspace:^" "@shapeshiftoss/chain-adapters": "workspace:^" "@shapeshiftoss/investor": "workspace:^" @@ -6202,7 +6202,7 @@ __metadata: version: 0.0.0-use.local resolution: "@shapeshiftoss/market-service@workspace:packages/market-service" dependencies: - "@ethersproject/providers": ^5.5.3 + "@ethersproject/providers": ^5.7.2 "@shapeshiftoss/caip": "workspace:^" "@shapeshiftoss/chain-adapters": "workspace:^" "@shapeshiftoss/investor-foxy": "workspace:^" @@ -6385,7 +6385,7 @@ __metadata: eslint-plugin-prettier: ^4.0.0 eslint-plugin-simple-import-sort: ^7.0.0 eth-url-parser: ^1.0.4 - ethers: ^5.5.3 + ethers: ^5.7.2 fast-json-stable-stringify: ^2.1.0 framer-motion: ^6.3.11 friendly-challenge: 0.9.2 @@ -15431,7 +15431,7 @@ __metadata: languageName: node linkType: hard -"ethers@npm:^5.4.7, ethers@npm:^5.5.3, ethers@npm:^5.6.5, ethers@npm:^5.6.9, ethers@npm:^5.7.0, ethers@npm:^5.7.2": +"ethers@npm:^5.4.7, ethers@npm:^5.6.5, ethers@npm:^5.6.9, ethers@npm:^5.7.0, ethers@npm:^5.7.2": version: 5.7.2 resolution: "ethers@npm:5.7.2" dependencies: From b8b3d3845c93747685f236c788dfda446479ef6e Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Sun, 23 Apr 2023 20:06:15 +0200 Subject: [PATCH 05/29] fix: getFoxyOpportunityByStakingAddress should use foxy staking contract address --- .../FoxyManager/Deposit/FoxyDeposit.tsx | 23 +++++++++++------ .../FoxyManager/Withdraw/FoxyWithdraw.tsx | 25 +++++++++++++------ 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/FoxyDeposit.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/FoxyDeposit.tsx index 25414b8f7f1..ba4c110db25 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/FoxyDeposit.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/FoxyDeposit.tsx @@ -2,6 +2,7 @@ import { Center } from '@chakra-ui/react' import type { AccountId } from '@shapeshiftoss/caip' import { toAssetId } from '@shapeshiftoss/caip' import { KnownChainIds } from '@shapeshiftoss/types' +import { ethers } from 'ethers' import { DefiModalContent } from 'features/defi/components/DefiModal/DefiModalContent' import { DefiModalHeader } from 'features/defi/components/DefiModal/DefiModalHeader' import type { @@ -53,9 +54,14 @@ export const FoxyDeposit: React.FC<{ const translate = useTranslate() const [state, dispatch] = useReducer(reducer, initialState) const { query, history, location } = useBrowserRouter() - const { chainId, contractAddress, assetReference, assetNamespace } = query + const { + chainId, + contractAddress: foxyContractAddress, + assetReference: foxyStakingContractAddress, + assetNamespace, + } = query // ContractAssetId - const assetId = toAssetId({ chainId, assetNamespace, assetReference }) + const assetId = toAssetId({ chainId, assetNamespace, assetReference: foxyStakingContractAddress }) const opportunityMetadataFilter = useMemo(() => ({ stakingId: assetId as StakingId }), [assetId]) const opportunityMetadata = useAppSelector(state => @@ -83,7 +89,7 @@ export const FoxyDeposit: React.FC<{ if ( !( walletState.wallet && - contractAddress && + foxyStakingContractAddress && !isFoxyAprLoading && chainAdapter && foxyApi && @@ -91,7 +97,9 @@ export const FoxyDeposit: React.FC<{ ) ) return - const foxyOpportunity = await foxyApi.getFoxyOpportunityByStakingAddress(contractAddress) + const foxyOpportunity = await foxyApi.getFoxyOpportunityByStakingAddress( + ethers.utils.getAddress(foxyStakingContractAddress), + ) dispatch({ type: FoxyDepositActionType.SET_OPPORTUNITY, payload: { ...foxyOpportunity, apy: foxyAprData?.foxyApr ?? '' }, @@ -105,10 +113,11 @@ export const FoxyDeposit: React.FC<{ foxyApi, bip44Params, chainAdapterManager, - contractAddress, + foxyContractAddress, walletState.wallet, foxyAprData?.foxyApr, isFoxyAprLoading, + foxyStakingContractAddress, ]) const handleBack = () => { @@ -136,7 +145,7 @@ export const FoxyDeposit: React.FC<{ label: translate('defi.steps.approve.title'), component: ownProps => , props: { - contractAddress, + contractAddress: foxyContractAddress, }, }, [DefiStep.Confirm]: { @@ -148,7 +157,7 @@ export const FoxyDeposit: React.FC<{ component: Status, }, } - }, [accountId, handleAccountIdChange, contractAddress, translate, stakingAsset.symbol]) + }, [accountId, handleAccountIdChange, foxyContractAddress, translate, stakingAsset.symbol]) if (loading || !stakingAsset || !marketData) { return ( diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/FoxyWithdraw.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/FoxyWithdraw.tsx index 80cbd2f6bc0..f3f800131b6 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/FoxyWithdraw.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/FoxyWithdraw.tsx @@ -1,6 +1,7 @@ import { Center } from '@chakra-ui/react' import type { AccountId } from '@shapeshiftoss/caip' import { KnownChainIds } from '@shapeshiftoss/types' +import { ethers } from 'ethers' import { DefiModalContent } from 'features/defi/components/DefiModal/DefiModalContent' import { DefiModalHeader } from 'features/defi/components/DefiModal/DefiModalHeader' import type { @@ -50,7 +51,7 @@ export const FoxyWithdraw: React.FC<{ const translate = useTranslate() const [state, dispatch] = useReducer(reducer, initialState) const { query, history, location } = useBrowserRouter() - const { assetReference: contractAddress } = query + const { assetReference: foxyStakingContractAddress } = query const { feeAssetId, underlyingAsset, underlyingAssetId, stakingAsset } = useFoxyQuery() const marketData = useAppSelector(state => selectMarketDataById(state, underlyingAssetId)) @@ -68,12 +69,22 @@ export const FoxyWithdraw: React.FC<{ useEffect(() => { ;(async () => { try { - if (!(walletState.wallet && contractAddress && chainAdapter && foxyApi && bip44Params)) + if ( + !( + walletState.wallet && + foxyStakingContractAddress && + chainAdapter && + foxyApi && + bip44Params + ) + ) return - const foxyOpportunity = await foxyApi.getFoxyOpportunityByStakingAddress(contractAddress) + const foxyOpportunity = await foxyApi.getFoxyOpportunityByStakingAddress( + ethers.utils.getAddress(foxyStakingContractAddress), + ) // Get foxy fee for instant sends const foxyFeePercentage = await foxyApi.instantUnstakeFee({ - contractAddress, + contractAddress: foxyStakingContractAddress, }) dispatch({ @@ -89,7 +100,7 @@ export const FoxyWithdraw: React.FC<{ moduleLogger.error(error, 'FoxyWithdraw error:') } })() - }, [foxyApi, bip44Params, chainAdapter, contractAddress, walletState.wallet]) + }, [foxyApi, bip44Params, chainAdapter, foxyStakingContractAddress, walletState.wallet]) const StepConfig: DefiStepProps = useMemo(() => { return { @@ -105,7 +116,7 @@ export const FoxyWithdraw: React.FC<{ [DefiStep.Approve]: { label: translate('defi.steps.approve.title'), component: ownProps => , - props: { contractAddress }, + props: { contractAddress: foxyStakingContractAddress }, }, [DefiStep.Confirm]: { label: translate('defi.steps.confirm.title'), @@ -116,7 +127,7 @@ export const FoxyWithdraw: React.FC<{ component: ownProps => , }, } - }, [accountId, handleAccountIdChange, contractAddress, translate, stakingAsset.symbol]) + }, [accountId, handleAccountIdChange, foxyStakingContractAddress, translate, stakingAsset.symbol]) const handleBack = () => { history.push({ From 645d5f1f389d323acead79d2b91f95f20191b61e Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Sun, 23 Apr 2023 22:12:17 +0200 Subject: [PATCH 06/29] feat(investor-foxy): estimate fees from node --- packages/investor-foxy/src/api/api.ts | 216 +++++++++++------- packages/investor-foxy/src/api/foxy-types.ts | 6 +- .../investor-foxy/src/utils/buildTxToSign.ts | 15 +- 3 files changed, 146 insertions(+), 91 deletions(-) diff --git a/packages/investor-foxy/src/api/api.ts b/packages/investor-foxy/src/api/api.ts index b4c5c5e1e7e..a78ab905fd6 100644 --- a/packages/investor-foxy/src/api/api.ts +++ b/packages/investor-foxy/src/api/api.ts @@ -1,7 +1,7 @@ import { JsonRpcBatchProvider } from '@ethersproject/providers' import type { ChainReference } from '@shapeshiftoss/caip' import { CHAIN_NAMESPACE, CHAIN_REFERENCE, toAssetId } from '@shapeshiftoss/caip' -import type { ChainAdapter } from '@shapeshiftoss/chain-adapters' +import type { ChainAdapter, FeeDataEstimate } from '@shapeshiftoss/chain-adapters' import { Logger } from '@shapeshiftoss/logger' import { KnownChainIds, WithdrawType } from '@shapeshiftoss/types' import axios from 'axios' @@ -181,22 +181,15 @@ export class FoxyApi { return liquidityReserveContract } - private async getGasPriceAndNonce( - userAddress: string, - ): Promise<{ nonce: string; gasPrice: string }> { + private async getNonce(userAddress: string): Promise<{ nonce: string }> { let nonce try { nonce = (await this.provider.getTransactionCount(userAddress)).toString() } catch (e) { throw new Error(`Get nonce Error: ${e}`) } - let gasPrice: string - try { - gasPrice = (await this.provider.getGasPrice()).toString() - } catch (e) { - throw new Error(`Get gasPrice Error: ${e}`) - } - return { nonce, gasPrice } + + return { nonce } } async getFoxyOpportunities() { @@ -251,7 +244,9 @@ export class FoxyApi { return this.provider.getTransactionReceipt(txid) } - async estimateClaimWithdrawGas(input: ClaimWithdrawal): Promise { + async estimateClaimWithdrawGas( + input: ClaimWithdrawal, + ): Promise> { const { claimAddress, userAddress, contractAddress } = input const addressToClaim = claimAddress ?? userAddress this.verifyAddresses([addressToClaim, userAddress, contractAddress]) @@ -259,32 +254,49 @@ export class FoxyApi { const stakingContract = this.getStakingContract(contractAddress) try { - const estimatedGas = await stakingContract.estimateGas.claimWithdraw(addressToClaim, { - from: userAddress, + const data = stakingContract.interface.encodeFunctionData('claimWithdraw', [addressToClaim]) + const estimatedFees = await this.adapter.getFeeData({ + to: contractAddress, + value: '0', + chainSpecific: { + contractData: data, + from: userAddress, + }, }) - return estimatedGas.toString() + + return estimatedFees } catch (e) { throw new Error(`Failed to get gas ${e}`) } } - async estimateSendWithdrawalRequestsGas(input: TxInputWithoutAmountAndWallet): Promise { + async estimateSendWithdrawalRequestsGas( + input: TxInputWithoutAmountAndWallet, + ): Promise> { const { userAddress, contractAddress } = input this.verifyAddresses([userAddress, contractAddress]) const stakingContract = this.getStakingContract(contractAddress) try { - const estimatedGas = await stakingContract.estimateGas.sendWithdrawalRequests([], { - from: userAddress, + const data = stakingContract.interface.encodeFunctionData('sendWithdrawalRequests', []) + const estimatedFees = await this.adapter.getFeeData({ + to: contractAddress, + value: '0', + chainSpecific: { + contractData: data, + from: userAddress, + }, }) - return estimatedGas.toString() + return estimatedFees } catch (e) { throw new Error(`Failed to get gas ${e}`) } } - async estimateAddLiquidityGas(input: EstimateGasTxInput): Promise { + async estimateAddLiquidityGas( + input: EstimateGasTxInput, + ): Promise> { const { amountDesired, userAddress, contractAddress } = input this.verifyAddresses([userAddress, contractAddress]) if (!amountDesired.gt(0)) throw new Error('Must send valid amount') @@ -292,17 +304,26 @@ export class FoxyApi { const liquidityReserveContract = this.getLiquidityReserveContract(contractAddress) try { - const estimatedGas = await liquidityReserveContract.estimateGas.addLiquidity( + const data = liquidityReserveContract.interface.encodeFunctionData('addLiquidity', [ this.normalizeAmount(amountDesired), - { from: userAddress }, - ) - return estimatedGas.toString() + ]) + const estimatedFees = await this.adapter.getFeeData({ + to: contractAddress, + value: '0', + chainSpecific: { + contractData: data, + from: userAddress, + }, + }) + return estimatedFees } catch (e) { throw new Error(`Failed to get gas ${e}`) } } - async estimateRemoveLiquidityGas(input: EstimateGasTxInput): Promise { + async estimateRemoveLiquidityGas( + input: EstimateGasTxInput, + ): Promise> { const { amountDesired, userAddress, contractAddress } = input this.verifyAddresses([userAddress, contractAddress]) if (!amountDesired.gt(0)) throw new Error('Must send valid amount') @@ -310,17 +331,27 @@ export class FoxyApi { const liquidityReserveContract = this.getLiquidityReserveContract(contractAddress) try { - const estimatedGas = await liquidityReserveContract.estimateGas.removeLiquidity( + const data = liquidityReserveContract.encodeFunctionData('removeLiquidity', [ this.normalizeAmount(amountDesired), - { from: userAddress }, - ) - return estimatedGas.toString() + ]) + + const estimatedFees = await this.adapter.getFeeData({ + to: contractAddress, + value: '0', + chainSpecific: { + contractData: data, + from: userAddress, + }, + }) + return estimatedFees } catch (e) { throw new Error(`Failed to get gas ${e}`) } } - async estimateWithdrawGas(input: WithdrawEstimateGasInput): Promise { + async estimateWithdrawGas( + input: WithdrawEstimateGasInput, + ): Promise> { const { amountDesired, userAddress, contractAddress, type } = input this.verifyAddresses([userAddress, contractAddress]) @@ -330,38 +361,58 @@ export class FoxyApi { if (isDelayed && !amountDesired.gt(0)) throw new Error('Must send valid amount') try { - const estimatedGas = isDelayed - ? await stakingContract.estimateGas['unstake(uint256,bool)']( + const data = isDelayed + ? stakingContract.interface.encodeFunctionData('unstake(uint256,bool)', [ this.normalizeAmount(amountDesired), true, - { from: userAddress }, - ) - : await stakingContract.estimateGas.instantUnstake(true, { from: userAddress }) - return estimatedGas.toString() + ]) + : stakingContract.interface.encodeFunctionData('instantUnstake', [true]) + + const estimatedFees = await this.adapter.getFeeData({ + to: contractAddress, + value: '0', + chainSpecific: { + contractData: data, + from: userAddress, + }, + }) + return estimatedFees } catch (e) { throw new Error(`Failed to get gas ${e}`) } } - async estimateApproveGas(input: EstimateGasApproveInput): Promise { + async estimateApproveGas( + input: EstimateGasApproveInput, + ): Promise> { const { userAddress, tokenContractAddress, contractAddress } = input this.verifyAddresses([userAddress, contractAddress, tokenContractAddress]) const depositTokenContract = new ethers.Contract(tokenContractAddress, erc20Abi, this.provider) try { - const estimatedGas = await depositTokenContract.estimateGas.approve( + const data = depositTokenContract.interface.encodeFunctionData('approve', [ contractAddress, MAX_ALLOWANCE, - { from: userAddress }, - ) - return estimatedGas.toString() + ]) + const estimatedFees = await this.adapter.getFeeData({ + to: contractAddress, + value: '0', + chainSpecific: { + contractData: data, + from: userAddress, + }, + }) + + return estimatedFees } catch (e) { throw new Error(`Failed to get gas ${e}`) } } - async estimateDepositGas(input: EstimateGasTxInput): Promise { + async estimateDepositGas( + input: EstimateGasTxInput, + ): Promise> { const { amountDesired, userAddress, contractAddress } = input this.verifyAddresses([userAddress, contractAddress]) if (!amountDesired.gt(0)) throw new Error('Must send valid amount') @@ -369,11 +420,21 @@ export class FoxyApi { const stakingContract = this.getStakingContract(contractAddress) try { - const estimatedGas = await stakingContract.estimateGas['stake(uint256)']( + const data = stakingContract.interface.encodeFunctionData('stake(uint256)', [ this.normalizeAmount(amountDesired), - { from: userAddress }, - ) - return estimatedGas.toString() + userAddress, + ]) + + const estimatedFees = await this.adapter.getFeeData({ + to: contractAddress, + value: '0', + chainSpecific: { + contractData: data, + from: userAddress, + }, + }) + + return estimatedFees } catch (e) { throw new Error(`Failed to get gas ${e}`) } @@ -392,9 +453,9 @@ export class FoxyApi { this.verifyAddresses([userAddress, contractAddress, tokenContractAddress]) if (!wallet) throw new Error('Missing inputs') - let estimatedGas: string + let estimatedFees: FeeDataEstimate try { - estimatedGas = await this.estimateApproveGas(input) + estimatedFees = await this.estimateApproveGas(input) } catch (e) { throw new Error(`Estimate Gas Error: ${e}`) } @@ -404,14 +465,13 @@ export class FoxyApi { amount ? numberToHex(bnOrZero(amount).toString()) : MAX_ALLOWANCE, ]) - const { nonce, gasPrice } = await this.getGasPriceAndNonce(userAddress) + const { nonce } = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, chainId: chainReferenceAsNumber, data, - estimatedGas, - gasPrice, + estimatedFees, nonce, to: tokenContractAddress, value: '0', @@ -451,9 +511,9 @@ export class FoxyApi { if (!amountDesired.gt(0)) throw new Error('Must send valid amount') if (!wallet) throw new Error('Missing inputs') - let estimatedGas: string + let estimatedFees: FeeDataEstimate try { - estimatedGas = await this.estimateDepositGas(input) + estimatedFees = await this.estimateDepositGas(input) } catch (e) { throw new Error(`Estimate Gas Error: ${e}`) } @@ -465,14 +525,13 @@ export class FoxyApi { userAddress, ]) - const { nonce, gasPrice } = await this.getGasPriceAndNonce(userAddress) + const { nonce } = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, chainId: chainReferenceAsNumber, data, - estimatedGas, - gasPrice, + estimatedFees, nonce, to: contractAddress, value: '0', @@ -493,9 +552,9 @@ export class FoxyApi { this.verifyAddresses([userAddress, contractAddress]) if (!wallet) throw new Error('Missing inputs') - let estimatedGas: string + let estimatedFees: FeeDataEstimate try { - estimatedGas = await this.estimateWithdrawGas(input) + estimatedFees = await this.estimateWithdrawGas(input) } catch (e) { throw new Error(`Estimate Gas Error: ${e}`) } @@ -512,14 +571,13 @@ export class FoxyApi { : ['instantUnstake', ['true']] const data: string = stakingContract.interface.encodeFunctionData(...stakingContractCallInput) - const { nonce, gasPrice } = await this.getGasPriceAndNonce(userAddress) + const { nonce } = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, chainId: chainReferenceAsNumber, data, - estimatedGas, - gasPrice, + estimatedFees, nonce, to: contractAddress, value: '0', @@ -614,9 +672,9 @@ export class FoxyApi { this.verifyAddresses([userAddress, contractAddress, addressToClaim]) if (!wallet) throw new Error('Missing inputs') - let estimatedGas: string + let estimatedFees: FeeDataEstimate try { - estimatedGas = await this.estimateClaimWithdrawGas(input) + estimatedFees = await this.estimateClaimWithdrawGas(input) } catch (e) { throw new Error(`Estimate Gas Error: ${e}`) } @@ -630,14 +688,13 @@ export class FoxyApi { addressToClaim, ]) - const { nonce, gasPrice } = await this.getGasPriceAndNonce(userAddress) + const { nonce } = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, chainId: chainReferenceAsNumber, data, - estimatedGas, - gasPrice, + estimatedFees, nonce, to: contractAddress, value: '0', @@ -726,9 +783,9 @@ export class FoxyApi { this.verifyAddresses([userAddress, contractAddress]) if (!wallet || !contractAddress) throw new Error('Missing inputs') - let estimatedGas: string + let estimatedFees: FeeDataEstimate try { - estimatedGas = await this.estimateSendWithdrawalRequestsGas(input) + estimatedFees = await this.estimateSendWithdrawalRequestsGas(input) } catch (e) { throw new Error(`Estimate Gas Error: ${e}`) } @@ -739,14 +796,13 @@ export class FoxyApi { if (!canSendRequest) throw new Error('Not ready to send request') const data: string = stakingContract.interface.encodeFunctionData('sendWithdrawalRequests') - const { nonce, gasPrice } = await this.getGasPriceAndNonce(userAddress) + const { nonce } = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, chainId: chainReferenceAsNumber, data, - estimatedGas, - gasPrice, + estimatedFees, nonce, to: contractAddress, value: '0', @@ -770,9 +826,9 @@ export class FoxyApi { if (!wallet) throw new Error('Missing inputs') - let estimatedGas: string + let estimatedFees: FeeDataEstimate try { - estimatedGas = await this.estimateAddLiquidityGas(input) + estimatedFees = await this.estimateAddLiquidityGas(input) } catch (e) { throw new Error(`Estimate Gas Error: ${e}`) } @@ -783,14 +839,13 @@ export class FoxyApi { this.normalizeAmount(amountDesired), ]) - const { nonce, gasPrice } = await this.getGasPriceAndNonce(userAddress) + const { nonce } = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, chainId: chainReferenceAsNumber, data, - estimatedGas, - gasPrice, + estimatedFees, nonce, to: contractAddress, value: '0', @@ -813,9 +868,9 @@ export class FoxyApi { if (!amountDesired.gt(0)) throw new Error('Must send valid amount') if (!wallet) throw new Error('Missing inputs') - let estimatedGas: string + let estimatedFees: FeeDataEstimate try { - estimatedGas = await this.estimateRemoveLiquidityGas(input) + estimatedFees = await this.estimateRemoveLiquidityGas(input) } catch (e) { throw new Error(`Estimate Gas Error: ${e}`) } @@ -826,14 +881,13 @@ export class FoxyApi { this.normalizeAmount(amountDesired), ]) - const { nonce, gasPrice } = await this.getGasPriceAndNonce(userAddress) + const { nonce } = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, chainId: chainReferenceAsNumber, data, - estimatedGas, - gasPrice, + estimatedFees, nonce, to: contractAddress, value: '0', diff --git a/packages/investor-foxy/src/api/foxy-types.ts b/packages/investor-foxy/src/api/foxy-types.ts index 4f464581859..b86a5b1ca45 100644 --- a/packages/investor-foxy/src/api/foxy-types.ts +++ b/packages/investor-foxy/src/api/foxy-types.ts @@ -1,6 +1,7 @@ import type { AssetId } from '@shapeshiftoss/caip' +import type { FeeDataEstimate } from '@shapeshiftoss/chain-adapters' import type { HDWallet } from '@shapeshiftoss/hdwallet-core' -import type { BIP44Params, WithdrawType } from '@shapeshiftoss/types' +import type { BIP44Params, KnownChainIds, WithdrawType } from '@shapeshiftoss/types' import type { BigNumber } from 'bignumber.js' import type ethers from 'ethers' @@ -102,8 +103,7 @@ export type SignAndBroadcastPayload = { bip44Params: BIP44Params chainId: number data: string - estimatedGas: string - gasPrice: string + estimatedFees: FeeDataEstimate nonce: string to: string value: string diff --git a/packages/investor-foxy/src/utils/buildTxToSign.ts b/packages/investor-foxy/src/utils/buildTxToSign.ts index 37c3843b67f..9bb2fc5c607 100644 --- a/packages/investor-foxy/src/utils/buildTxToSign.ts +++ b/packages/investor-foxy/src/utils/buildTxToSign.ts @@ -1,14 +1,16 @@ +import type { FeeDataEstimate } from '@shapeshiftoss/chain-adapters' import { toAddressNList } from '@shapeshiftoss/chain-adapters' import type { ETHSignTx } from '@shapeshiftoss/hdwallet-core' -import type { BIP44Params } from '@shapeshiftoss/types' +import type { BIP44Params, KnownChainIds } from '@shapeshiftoss/types' import { numberToHex } from 'web3-utils' +import { bnOrZero } from './bignumber' + type BuildTxToSignInput = { bip44Params: BIP44Params chainId: number data: string - estimatedGas: string - gasPrice: string + estimatedFees: FeeDataEstimate nonce: string value: string to: string @@ -18,8 +20,7 @@ export const buildTxToSign = ({ bip44Params, chainId = 1, data, - estimatedGas, - gasPrice, + estimatedFees, nonce, to, value, @@ -30,6 +31,6 @@ export const buildTxToSign = ({ chainId, // TODO: implement for multiple chains data, nonce: numberToHex(nonce), - gasPrice: numberToHex(gasPrice), - gasLimit: numberToHex(estimatedGas), + gasPrice: numberToHex(bnOrZero(estimatedFees.fast.chainSpecific.gasPrice).toString()), + gasLimit: numberToHex(bnOrZero(estimatedFees.fast.chainSpecific.gasLimit).toString()), }) From 27e3021802c536d71e11a6c75124040ed444834d Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Sun, 23 Apr 2023 22:19:27 +0200 Subject: [PATCH 07/29] wip: consume feeDataEstimate in FOxy view-layer instead of dumb previous gasLimit/gasPrice from ethers --- .../Deposit/components/Approve.tsx | 23 +++++----- .../Deposit/components/Deposit.tsx | 42 ++++++++++--------- 2 files changed, 35 insertions(+), 30 deletions(-) diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Approve.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Approve.tsx index a65168ab6fc..21b84a67051 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Approve.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Approve.tsx @@ -68,17 +68,18 @@ export const Approve: React.FC = ({ accountId, onNext }) => { async (deposit: DepositValues) => { if (!accountAddress || !assetReference || !foxyApi) return try { - const [gasLimit, gasPrice] = await Promise.all([ - foxyApi.estimateDepositGas({ - tokenContractAddress: assetReference, - contractAddress, - amountDesired: bnOrZero(deposit.cryptoAmount) - .times(bn(10).pow(asset.precision)) - .decimalPlaces(0), - userAddress: accountAddress, - }), - foxyApi.getGasPrice(), - ]) + const feeDataEstimate = await foxyApi.estimateDepositGas({ + tokenContractAddress: assetReference, + contractAddress, + amountDesired: bnOrZero(deposit.cryptoAmount) + .times(bn(10).pow(asset.precision)) + .decimalPlaces(0), + userAddress: accountAddress, + }) + + const { + chainSpecific: { gasPrice, gasLimit }, + } = feeDataEstimate.fast return bnOrZero(gasPrice).times(gasLimit).toFixed(0) } catch (error) { moduleLogger.error( diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Deposit.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Deposit.tsx index 2ba9a77c8c8..baaa2ca10c5 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Deposit.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Deposit.tsx @@ -69,14 +69,16 @@ export const Deposit: React.FC = ({ const getApproveGasEstimate = async () => { if (!accountAddress || !assetReference || !foxyApi) return try { - const [gasLimit, gasPrice] = await Promise.all([ - foxyApi.estimateApproveGas({ - tokenContractAddress: assetReference, - contractAddress, - userAddress: accountAddress, - }), - foxyApi.getGasPrice(), - ]) + const feeDataEstimate = await foxyApi.estimateApproveGas({ + tokenContractAddress: assetReference, + contractAddress, + userAddress: accountAddress, + }) + + const { + chainSpecific: { gasPrice, gasLimit }, + } = feeDataEstimate.fast + return bnOrZero(gasPrice).times(gasLimit).toFixed(0) } catch (error) { moduleLogger.error( @@ -95,17 +97,19 @@ export const Deposit: React.FC = ({ const getDepositGasEstimateCryptoBaseUnit = async (deposit: DepositValues) => { if (!accountAddress || !assetReference || !foxyApi) return try { - const [gasLimit, gasPrice] = await Promise.all([ - foxyApi.estimateDepositGas({ - tokenContractAddress: assetReference, - contractAddress, - amountDesired: bnOrZero(deposit.cryptoAmount) - .times(`1e+${asset.precision}`) - .decimalPlaces(0), - userAddress: accountAddress, - }), - foxyApi.getGasPrice(), - ]) + const feeDataEstimate = await foxyApi.estimateDepositGas({ + tokenContractAddress: assetReference, + contractAddress, + amountDesired: bnOrZero(deposit.cryptoAmount) + .times(`1e+${asset.precision}`) + .decimalPlaces(0), + userAddress: accountAddress, + }) + + const { + chainSpecific: { gasPrice, gasLimit }, + } = feeDataEstimate.fast + return bnOrZero(gasPrice).times(gasLimit).toFixed(0) } catch (error) { moduleLogger.error( From 76033d3ca0e0c95a88f64f53b6dfb3b9b9d7a6de Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Sun, 23 Apr 2023 22:22:33 +0200 Subject: [PATCH 08/29] fix: stake(uint256) arity --- packages/investor-foxy/src/api/api.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/investor-foxy/src/api/api.ts b/packages/investor-foxy/src/api/api.ts index a78ab905fd6..c9214fa5394 100644 --- a/packages/investor-foxy/src/api/api.ts +++ b/packages/investor-foxy/src/api/api.ts @@ -422,7 +422,6 @@ export class FoxyApi { try { const data = stakingContract.interface.encodeFunctionData('stake(uint256)', [ this.normalizeAmount(amountDesired), - userAddress, ]) const estimatedFees = await this.adapter.getFeeData({ From cc56ac4a166eb093f502a3a35a871bd70edc383c Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Sun, 23 Apr 2023 22:34:04 +0200 Subject: [PATCH 09/29] feat: safeGasLimit 5% buffer --- packages/investor-foxy/src/api/api.ts | 46 +++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/packages/investor-foxy/src/api/api.ts b/packages/investor-foxy/src/api/api.ts index c9214fa5394..3b88b8b4995 100644 --- a/packages/investor-foxy/src/api/api.ts +++ b/packages/investor-foxy/src/api/api.ts @@ -264,6 +264,12 @@ export class FoxyApi { }, }) + const { + chainSpecific: { gasLimit: gasLimitBase }, + } = estimatedFees.fast + const safeGasLimit = bnOrZero(gasLimitBase).times('1.05').toFixed(0) + estimatedFees.fast.chainSpecific.gasLimit = safeGasLimit + return estimatedFees } catch (e) { throw new Error(`Failed to get gas ${e}`) @@ -288,6 +294,13 @@ export class FoxyApi { from: userAddress, }, }) + + const { + chainSpecific: { gasLimit: gasLimitBase }, + } = estimatedFees.fast + const safeGasLimit = bnOrZero(gasLimitBase).times('1.05').toFixed(0) + estimatedFees.fast.chainSpecific.gasLimit = safeGasLimit + return estimatedFees } catch (e) { throw new Error(`Failed to get gas ${e}`) @@ -315,6 +328,13 @@ export class FoxyApi { from: userAddress, }, }) + + const { + chainSpecific: { gasLimit: gasLimitBase }, + } = estimatedFees.fast + const safeGasLimit = bnOrZero(gasLimitBase).times('1.05').toFixed(0) + estimatedFees.fast.chainSpecific.gasLimit = safeGasLimit + return estimatedFees } catch (e) { throw new Error(`Failed to get gas ${e}`) @@ -343,6 +363,13 @@ export class FoxyApi { from: userAddress, }, }) + + const { + chainSpecific: { gasLimit: gasLimitBase }, + } = estimatedFees.fast + const safeGasLimit = bnOrZero(gasLimitBase).times('1.05').toFixed(0) + estimatedFees.fast.chainSpecific.gasLimit = safeGasLimit + return estimatedFees } catch (e) { throw new Error(`Failed to get gas ${e}`) @@ -376,6 +403,13 @@ export class FoxyApi { from: userAddress, }, }) + + const { + chainSpecific: { gasLimit: gasLimitBase }, + } = estimatedFees.fast + const safeGasLimit = bnOrZero(gasLimitBase).times('1.05').toFixed(0) + estimatedFees.fast.chainSpecific.gasLimit = safeGasLimit + return estimatedFees } catch (e) { throw new Error(`Failed to get gas ${e}`) @@ -404,6 +438,12 @@ export class FoxyApi { }, }) + const { + chainSpecific: { gasLimit: gasLimitBase }, + } = estimatedFees.fast + const safeGasLimit = bnOrZero(gasLimitBase).times('1.05').toFixed(0) + estimatedFees.fast.chainSpecific.gasLimit = safeGasLimit + return estimatedFees } catch (e) { throw new Error(`Failed to get gas ${e}`) @@ -433,6 +473,12 @@ export class FoxyApi { }, }) + const { + chainSpecific: { gasLimit: gasLimitBase }, + } = estimatedFees.fast + const safeGasLimit = bnOrZero(gasLimitBase).times('1.05').toFixed(0) + estimatedFees.fast.chainSpecific.gasLimit = safeGasLimit + return estimatedFees } catch (e) { throw new Error(`Failed to get gas ${e}`) From d18ca4fbcf33ac205da96eb1e310fe31dc9c9c8e Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Mon, 24 Apr 2023 10:53:37 +0200 Subject: [PATCH 10/29] feat: fully plumb through web --- .../Overview/Claim/ClaimConfirm.tsx | 7 ++- .../Withdraw/components/Approve.tsx | 28 +++++------ .../Withdraw/components/Withdraw.tsx | 46 ++++++++++--------- 3 files changed, 45 insertions(+), 36 deletions(-) diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimConfirm.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimConfirm.tsx index 8ed9f9f8a69..609f0397920 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimConfirm.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimConfirm.tsx @@ -146,7 +146,7 @@ export const ClaimConfirm = ({ accountNumber, }) setUserAddress(userAddress) - const [gasLimit, gasPrice, canClaimWithdraw] = await Promise.all([ + const [feeDataEstimate, canClaimWithdraw] = await Promise.all([ foxyApi.estimateClaimWithdrawGas({ claimAddress: userAddress, userAddress, @@ -154,10 +154,13 @@ export const ClaimConfirm = ({ wallet: walletState.wallet, bip44Params, }), - foxyApi.getGasPrice(), foxyApi.canClaimWithdraw({ contractAddress, userAddress }), ]) + const { + chainSpecific: { gasPrice, gasLimit }, + } = feeDataEstimate.fast + setCanClaim(canClaimWithdraw) const gasEstimate = bnOrZero(gasPrice).times(gasLimit).toFixed(0) setEstimatedGas(gasEstimate) diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Approve.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Approve.tsx index 0037948171a..c05a943ea1b 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Approve.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Approve.tsx @@ -67,19 +67,21 @@ export const Approve: React.FC = ({ accountId, onNext }) => { if (!(rewardId && userAddress && state?.withdraw && foxyApi && dispatch && bip44Params)) return try { - const [gasLimit, gasPrice] = await Promise.all([ - foxyApi.estimateWithdrawGas({ - tokenContractAddress: rewardId, - contractAddress, - amountDesired: bnOrZero( - bn(withdraw.cryptoAmount).times(`1e+${asset.precision}`), - ).decimalPlaces(0), - userAddress, - type: state.withdraw.withdrawType, - bip44Params, - }), - foxyApi.getGasPrice(), - ]) + const feeDataEstimate = await foxyApi.estimateWithdrawGas({ + tokenContractAddress: rewardId, + contractAddress, + amountDesired: bnOrZero( + bn(withdraw.cryptoAmount).times(`1e+${asset.precision}`), + ).decimalPlaces(0), + userAddress, + type: state.withdraw.withdrawType, + bip44Params, + }) + + const { + chainSpecific: { gasPrice, gasLimit }, + } = feeDataEstimate.fast + const returVal = bnOrZero(bn(gasPrice).times(gasLimit)).toFixed(0) return returVal } catch (error) { diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Withdraw.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Withdraw.tsx index 5d20a0fccda..b5df8553ffd 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Withdraw.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Withdraw.tsx @@ -104,14 +104,16 @@ export const Withdraw: React.FC< if (!accountAddress) return try { - const [gasLimit, gasPrice] = await Promise.all([ - foxyApi.estimateApproveGas({ - tokenContractAddress: rewardId, - contractAddress, - userAddress: accountAddress, - }), - foxyApi.getGasPrice(), - ]) + const feeDataEstimate = await foxyApi.estimateApproveGas({ + tokenContractAddress: rewardId, + contractAddress, + userAddress: accountAddress, + }) + + const { + chainSpecific: { gasPrice, gasLimit }, + } = feeDataEstimate.fast + return bnOrZero(bn(gasPrice).times(gasLimit)).toFixed(0) } catch (error) { moduleLogger.error(error, { fn: 'getApproveEstimate' }, 'getApproveEstimate error') @@ -128,19 +130,21 @@ export const Withdraw: React.FC< if (!accountAddress) return try { - const [gasLimit, gasPrice] = await Promise.all([ - foxyApi.estimateWithdrawGas({ - tokenContractAddress: rewardId, - contractAddress, - amountDesired: bnOrZero( - bn(withdraw.cryptoAmount).times(bn(10).pow(asset.precision)), - ).decimalPlaces(0), - userAddress: accountAddress, - type: withdraw.withdrawType, - bip44Params, - }), - foxyApi.getGasPrice(), - ]) + const feeDataEstimate = await foxyApi.estimateWithdrawGas({ + tokenContractAddress: rewardId, + contractAddress, + amountDesired: bnOrZero( + bn(withdraw.cryptoAmount).times(bn(10).pow(asset.precision)), + ).decimalPlaces(0), + userAddress: accountAddress, + type: withdraw.withdrawType, + bip44Params, + }) + + const { + chainSpecific: { gasPrice, gasLimit }, + } = feeDataEstimate.fast + return bnOrZero(bn(gasPrice).times(gasLimit)).toFixed(0) } catch (error) { moduleLogger.error( From 7fbc499b02a9583604fcd448f79dfcd98db19915 Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Mon, 24 Apr 2023 11:05:42 +0200 Subject: [PATCH 11/29] feat: bye bye investor-foxy getGasPrice(), you will not be missed --- packages/investor-foxy/src/api/api.ts | 5 ----- .../FoxyManager/Deposit/components/Confirm.tsx | 13 +++++++++---- .../FoxyManager/Overview/Claim/ClaimStatus.tsx | 14 +++++++++++--- .../FoxyManager/Withdraw/components/Confirm.tsx | 14 ++++++++++---- 4 files changed, 30 insertions(+), 16 deletions(-) diff --git a/packages/investor-foxy/src/api/api.ts b/packages/investor-foxy/src/api/api.ts index 3b88b8b4995..f621833f1d2 100644 --- a/packages/investor-foxy/src/api/api.ts +++ b/packages/investor-foxy/src/api/api.ts @@ -234,11 +234,6 @@ export class FoxyApi { } } - async getGasPrice(): Promise { - const gasPrice = await this.provider.getGasPrice() - return gasPrice.toString() - } - getTxReceipt({ txid }: TxReceipt): Promise { if (!txid) throw new Error('Must pass txid') return this.provider.getTransactionReceipt(txid) diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx index 39b4d00d97a..86f370e0674 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx @@ -1,6 +1,7 @@ import { Alert, AlertIcon, Box, Stack, useToast } from '@chakra-ui/react' import type { AccountId } from '@shapeshiftoss/caip' -import { fromAccountId } from '@shapeshiftoss/caip' +import { ethChainId, fromAccountId } from '@shapeshiftoss/caip' +import type { EvmBaseAdapter, EvmChainId } from '@shapeshiftoss/chain-adapters' import type { ethers } from 'ethers' import { Confirm as ReusableConfirm } from 'features/defi/components/Confirm/Confirm' import { Summary } from 'features/defi/components/Summary' @@ -14,6 +15,7 @@ import { AssetIcon } from 'components/AssetIcon' import type { StepComponentProps } from 'components/DeFi/components/Steps' import { Row } from 'components/Row/Row' import { RawText, Text } from 'components/Text' +import { getChainAdapterManager } from 'context/PluginProvider/chainAdapterSingleton' import { useWallet } from 'hooks/useWallet/useWallet' import { bn, bnOrZero } from 'lib/bignumber/bignumber' import { logger } from 'lib/logger' @@ -81,7 +83,10 @@ export const Confirm: React.FC = ({ onNext, accountId }) => { return try { dispatch({ type: FoxyDepositActionType.SET_LOADING, payload: true }) - const [txid, gasPrice] = await Promise.all([ + const chainAdapterManager = getChainAdapterManager() + const adapter = chainAdapterManager.get(ethChainId) as unknown as EvmBaseAdapter + + const [txid, gasFees] = await Promise.all([ foxyApi.deposit({ amountDesired: bnOrZero(state?.deposit.cryptoAmount) .times(bn(10).pow(asset.precision)) @@ -92,7 +97,7 @@ export const Confirm: React.FC = ({ onNext, accountId }) => { wallet: walletState.wallet, bip44Params, }), - foxyApi.getGasPrice(), + adapter.getGasFeeData(), ]) dispatch({ type: FoxyDepositActionType.SET_TXID, payload: txid }) onNext(DefiStep.Status) @@ -107,7 +112,7 @@ export const Confirm: React.FC = ({ onNext, accountId }) => { type: FoxyDepositActionType.SET_DEPOSIT, payload: { txStatus: transactionReceipt.status ? 'success' : 'failed', - usedGasFeeCryptoBaseUnit: bnOrZero(gasPrice) + usedGasFeeCryptoBaseUnit: bnOrZero(gasFees.fast.gasPrice) .times(transactionReceipt.gasUsed.toString()) .toFixed(0), }, diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx index 781a6414750..82922974b5e 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx @@ -1,6 +1,7 @@ import { Box, Button, Center, Link, ModalBody, ModalFooter, Stack } from '@chakra-ui/react' import type { AccountId, AssetId, ChainId } from '@shapeshiftoss/caip' -import { ASSET_REFERENCE, toAssetId } from '@shapeshiftoss/caip' +import { ASSET_REFERENCE, ethChainId, toAssetId } from '@shapeshiftoss/caip' +import type { EvmBaseAdapter, EvmChainId } from '@shapeshiftoss/chain-adapters' import type { ethers } from 'ethers' import { DefiProvider, DefiType } from 'features/defi/contexts/DefiManagerProvider/DefiCommon' import isNil from 'lodash/isNil' @@ -16,6 +17,7 @@ import { MiddleEllipsis } from 'components/MiddleEllipsis/MiddleEllipsis' import { Row } from 'components/Row/Row' import { SlideTransition } from 'components/SlideTransition' import { RawText } from 'components/Text' +import { getChainAdapterManager } from 'context/PluginProvider/chainAdapterSingleton' import { useBrowserRouter } from 'hooks/useBrowserRouter/useBrowserRouter' import { bnOrZero } from 'lib/bignumber/bignumber' import { logger } from 'lib/logger' @@ -125,7 +127,11 @@ export const ClaimStatus: React.FC = ({ accountId }) => { interval: 15000, maxAttempts: 30, }) - const gasPrice = await foxyApi.getGasPrice() + + const chainAdapterManager = getChainAdapterManager() + const adapter = chainAdapterManager.get(ethChainId) as unknown as EvmBaseAdapter + + const gasFees = await adapter.getGasFeeData() if (transactionReceipt.status) { refetchFoxyBalances() @@ -134,7 +140,9 @@ export const ClaimStatus: React.FC = ({ accountId }) => { setState({ ...state, txStatus: transactionReceipt.status ? TxStatus.SUCCESS : TxStatus.FAILED, - usedGasFee: bnOrZero(gasPrice).times(transactionReceipt.gasUsed.toString()).toFixed(0), + usedGasFee: bnOrZero(gasFees.fast.gasPrice) + .times(transactionReceipt.gasUsed.toString()) + .toFixed(0), }) } catch (error) { moduleLogger.error(error, 'ClaimStatus error') diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx index 5d6551d806d..3b3fcacd128 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx @@ -1,6 +1,7 @@ import { Alert, AlertIcon, Box, Stack } from '@chakra-ui/react' import type { AccountId } from '@shapeshiftoss/caip' -import { fromAccountId } from '@shapeshiftoss/caip' +import { ethChainId, fromAccountId } from '@shapeshiftoss/caip' +import type { EvmBaseAdapter, EvmChainId } from '@shapeshiftoss/chain-adapters' import { WithdrawType } from '@shapeshiftoss/types' import type { ethers } from 'ethers' import { Confirm as ReusableConfirm } from 'features/defi/components/Confirm/Confirm' @@ -15,6 +16,7 @@ import { AssetIcon } from 'components/AssetIcon' import type { StepComponentProps } from 'components/DeFi/components/Steps' import { Row } from 'components/Row/Row' import { RawText, Text } from 'components/Text' +import { getChainAdapterManager } from 'context/PluginProvider/chainAdapterSingleton' import { useWallet } from 'hooks/useWallet/useWallet' import { bn, bnOrZero } from 'lib/bignumber/bignumber' import { logger } from 'lib/logger' @@ -85,7 +87,11 @@ export const Confirm: React.FC + + const [txid, gasFees] = await Promise.all([ foxyApi.withdraw({ tokenContractAddress: rewardId, userAddress: accountAddress, @@ -97,7 +103,7 @@ export const Confirm: React.FC Date: Mon, 24 Apr 2023 11:14:32 +0200 Subject: [PATCH 12/29] feat: gas -> fees vernacular --- packages/investor-foxy/src/api/api.ts | 44 +++++++++---------- packages/investor-foxy/src/api/foxy-types.ts | 6 +-- .../Deposit/components/Approve.tsx | 2 +- .../Deposit/components/Deposit.tsx | 4 +- .../Overview/Claim/ClaimConfirm.tsx | 2 +- .../Withdraw/components/Approve.tsx | 2 +- .../Withdraw/components/Withdraw.tsx | 4 +- 7 files changed, 32 insertions(+), 32 deletions(-) diff --git a/packages/investor-foxy/src/api/api.ts b/packages/investor-foxy/src/api/api.ts index f621833f1d2..f1780f28af3 100644 --- a/packages/investor-foxy/src/api/api.ts +++ b/packages/investor-foxy/src/api/api.ts @@ -32,8 +32,9 @@ import type { CanClaimWithdrawParams, ClaimWithdrawal, ContractAddressInput, - EstimateGasApproveInput, - EstimateGasTxInput, + EstimateApproveFeesInput, + EstimateFeesTxInput, + EstimateWithdrawFeesInput, FoxyAddressesType, FoxyOpportunityInputData, GetTokeRewardAmount, @@ -47,7 +48,6 @@ import type { TxInputWithoutAmount, TxInputWithoutAmountAndWallet, TxReceipt, - WithdrawEstimateGasInput, WithdrawInfo, WithdrawInput, } from './foxy-types' @@ -239,7 +239,7 @@ export class FoxyApi { return this.provider.getTransactionReceipt(txid) } - async estimateClaimWithdrawGas( + async estimateClaimWithdrawFees( input: ClaimWithdrawal, ): Promise> { const { claimAddress, userAddress, contractAddress } = input @@ -271,7 +271,7 @@ export class FoxyApi { } } - async estimateSendWithdrawalRequestsGas( + async estimateSendWithdrawalRequestsFees( input: TxInputWithoutAmountAndWallet, ): Promise> { const { userAddress, contractAddress } = input @@ -302,8 +302,8 @@ export class FoxyApi { } } - async estimateAddLiquidityGas( - input: EstimateGasTxInput, + async estimateAddLiquidityFees( + input: EstimateFeesTxInput, ): Promise> { const { amountDesired, userAddress, contractAddress } = input this.verifyAddresses([userAddress, contractAddress]) @@ -336,8 +336,8 @@ export class FoxyApi { } } - async estimateRemoveLiquidityGas( - input: EstimateGasTxInput, + async estimateRemoveLiquidityFees( + input: EstimateFeesTxInput, ): Promise> { const { amountDesired, userAddress, contractAddress } = input this.verifyAddresses([userAddress, contractAddress]) @@ -371,8 +371,8 @@ export class FoxyApi { } } - async estimateWithdrawGas( - input: WithdrawEstimateGasInput, + async estimateWithdrawFees( + input: EstimateWithdrawFeesInput, ): Promise> { const { amountDesired, userAddress, contractAddress, type } = input this.verifyAddresses([userAddress, contractAddress]) @@ -411,8 +411,8 @@ export class FoxyApi { } } - async estimateApproveGas( - input: EstimateGasApproveInput, + async estimateApproveFees( + input: EstimateApproveFeesInput, ): Promise> { const { userAddress, tokenContractAddress, contractAddress } = input this.verifyAddresses([userAddress, contractAddress, tokenContractAddress]) @@ -445,8 +445,8 @@ export class FoxyApi { } } - async estimateDepositGas( - input: EstimateGasTxInput, + async estimateDepositFees( + input: EstimateFeesTxInput, ): Promise> { const { amountDesired, userAddress, contractAddress } = input this.verifyAddresses([userAddress, contractAddress]) @@ -495,7 +495,7 @@ export class FoxyApi { let estimatedFees: FeeDataEstimate try { - estimatedFees = await this.estimateApproveGas(input) + estimatedFees = await this.estimateApproveFees(input) } catch (e) { throw new Error(`Estimate Gas Error: ${e}`) } @@ -553,7 +553,7 @@ export class FoxyApi { let estimatedFees: FeeDataEstimate try { - estimatedFees = await this.estimateDepositGas(input) + estimatedFees = await this.estimateDepositFees(input) } catch (e) { throw new Error(`Estimate Gas Error: ${e}`) } @@ -594,7 +594,7 @@ export class FoxyApi { let estimatedFees: FeeDataEstimate try { - estimatedFees = await this.estimateWithdrawGas(input) + estimatedFees = await this.estimateWithdrawFees(input) } catch (e) { throw new Error(`Estimate Gas Error: ${e}`) } @@ -714,7 +714,7 @@ export class FoxyApi { let estimatedFees: FeeDataEstimate try { - estimatedFees = await this.estimateClaimWithdrawGas(input) + estimatedFees = await this.estimateClaimWithdrawFees(input) } catch (e) { throw new Error(`Estimate Gas Error: ${e}`) } @@ -825,7 +825,7 @@ export class FoxyApi { let estimatedFees: FeeDataEstimate try { - estimatedFees = await this.estimateSendWithdrawalRequestsGas(input) + estimatedFees = await this.estimateSendWithdrawalRequestsFees(input) } catch (e) { throw new Error(`Estimate Gas Error: ${e}`) } @@ -868,7 +868,7 @@ export class FoxyApi { let estimatedFees: FeeDataEstimate try { - estimatedFees = await this.estimateAddLiquidityGas(input) + estimatedFees = await this.estimateAddLiquidityFees(input) } catch (e) { throw new Error(`Estimate Gas Error: ${e}`) } @@ -910,7 +910,7 @@ export class FoxyApi { let estimatedFees: FeeDataEstimate try { - estimatedFees = await this.estimateRemoveLiquidityGas(input) + estimatedFees = await this.estimateRemoveLiquidityFees(input) } catch (e) { throw new Error(`Estimate Gas Error: ${e}`) } diff --git a/packages/investor-foxy/src/api/foxy-types.ts b/packages/investor-foxy/src/api/foxy-types.ts index b86a5b1ca45..72cbba14a48 100644 --- a/packages/investor-foxy/src/api/foxy-types.ts +++ b/packages/investor-foxy/src/api/foxy-types.ts @@ -31,7 +31,7 @@ export type ApproveInput = { wallet: HDWallet } -export type EstimateGasApproveInput = Pick< +export type EstimateApproveFeesInput = Pick< ApproveInput, 'userAddress' | 'tokenContractAddress' | 'contractAddress' > @@ -58,7 +58,7 @@ export type WithdrawInput = Omit & { amountDesired?: BigNumber } -export type WithdrawEstimateGasInput = Omit +export type EstimateWithdrawFeesInput = Omit export type FoxyOpportunityInputData = { tvl: BigNumber @@ -70,7 +70,7 @@ export type FoxyOpportunityInputData = { liquidityReserve: string } -export type EstimateGasTxInput = Pick< +export type EstimateFeesTxInput = Pick< TxInput, 'tokenContractAddress' | 'contractAddress' | 'userAddress' | 'amountDesired' > diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Approve.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Approve.tsx index 21b84a67051..9d11d79251c 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Approve.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Approve.tsx @@ -68,7 +68,7 @@ export const Approve: React.FC = ({ accountId, onNext }) => { async (deposit: DepositValues) => { if (!accountAddress || !assetReference || !foxyApi) return try { - const feeDataEstimate = await foxyApi.estimateDepositGas({ + const feeDataEstimate = await foxyApi.estimateDepositFees({ tokenContractAddress: assetReference, contractAddress, amountDesired: bnOrZero(deposit.cryptoAmount) diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Deposit.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Deposit.tsx index baaa2ca10c5..03082cb70aa 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Deposit.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Deposit.tsx @@ -69,7 +69,7 @@ export const Deposit: React.FC = ({ const getApproveGasEstimate = async () => { if (!accountAddress || !assetReference || !foxyApi) return try { - const feeDataEstimate = await foxyApi.estimateApproveGas({ + const feeDataEstimate = await foxyApi.estimateApproveFees({ tokenContractAddress: assetReference, contractAddress, userAddress: accountAddress, @@ -97,7 +97,7 @@ export const Deposit: React.FC = ({ const getDepositGasEstimateCryptoBaseUnit = async (deposit: DepositValues) => { if (!accountAddress || !assetReference || !foxyApi) return try { - const feeDataEstimate = await foxyApi.estimateDepositGas({ + const feeDataEstimate = await foxyApi.estimateDepositFees({ tokenContractAddress: assetReference, contractAddress, amountDesired: bnOrZero(deposit.cryptoAmount) diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimConfirm.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimConfirm.tsx index 609f0397920..5b9efd1d3a9 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimConfirm.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimConfirm.tsx @@ -147,7 +147,7 @@ export const ClaimConfirm = ({ }) setUserAddress(userAddress) const [feeDataEstimate, canClaimWithdraw] = await Promise.all([ - foxyApi.estimateClaimWithdrawGas({ + foxyApi.estimateClaimWithdrawFees({ claimAddress: userAddress, userAddress, contractAddress, diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Approve.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Approve.tsx index c05a943ea1b..f254430a857 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Approve.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Approve.tsx @@ -67,7 +67,7 @@ export const Approve: React.FC = ({ accountId, onNext }) => { if (!(rewardId && userAddress && state?.withdraw && foxyApi && dispatch && bip44Params)) return try { - const feeDataEstimate = await foxyApi.estimateWithdrawGas({ + const feeDataEstimate = await foxyApi.estimateWithdrawFees({ tokenContractAddress: rewardId, contractAddress, amountDesired: bnOrZero( diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Withdraw.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Withdraw.tsx index b5df8553ffd..08965081c37 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Withdraw.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Withdraw.tsx @@ -104,7 +104,7 @@ export const Withdraw: React.FC< if (!accountAddress) return try { - const feeDataEstimate = await foxyApi.estimateApproveGas({ + const feeDataEstimate = await foxyApi.estimateApproveFees({ tokenContractAddress: rewardId, contractAddress, userAddress: accountAddress, @@ -130,7 +130,7 @@ export const Withdraw: React.FC< if (!accountAddress) return try { - const feeDataEstimate = await foxyApi.estimateWithdrawGas({ + const feeDataEstimate = await foxyApi.estimateWithdrawFees({ tokenContractAddress: rewardId, contractAddress, amountDesired: bnOrZero( From 1d43399e8bc1a78c86ebe20e69f6768179a329a2 Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Mon, 24 Apr 2023 11:17:53 +0200 Subject: [PATCH 13/29] chore: cleanup getNonce --- packages/investor-foxy/src/api/api.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/investor-foxy/src/api/api.ts b/packages/investor-foxy/src/api/api.ts index f1780f28af3..1b8493d6f39 100644 --- a/packages/investor-foxy/src/api/api.ts +++ b/packages/investor-foxy/src/api/api.ts @@ -181,7 +181,7 @@ export class FoxyApi { return liquidityReserveContract } - private async getNonce(userAddress: string): Promise<{ nonce: string }> { + private async getNonce(userAddress: string): Promise { let nonce try { nonce = (await this.provider.getTransactionCount(userAddress)).toString() @@ -189,7 +189,7 @@ export class FoxyApi { throw new Error(`Get nonce Error: ${e}`) } - return { nonce } + return nonce } async getFoxyOpportunities() { @@ -505,7 +505,7 @@ export class FoxyApi { amount ? numberToHex(bnOrZero(amount).toString()) : MAX_ALLOWANCE, ]) - const { nonce } = await this.getNonce(userAddress) + const nonce = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, @@ -565,7 +565,7 @@ export class FoxyApi { userAddress, ]) - const { nonce } = await this.getNonce(userAddress) + const nonce = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, @@ -611,7 +611,7 @@ export class FoxyApi { : ['instantUnstake', ['true']] const data: string = stakingContract.interface.encodeFunctionData(...stakingContractCallInput) - const { nonce } = await this.getNonce(userAddress) + const nonce = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, @@ -728,7 +728,7 @@ export class FoxyApi { addressToClaim, ]) - const { nonce } = await this.getNonce(userAddress) + const nonce = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, @@ -836,7 +836,7 @@ export class FoxyApi { if (!canSendRequest) throw new Error('Not ready to send request') const data: string = stakingContract.interface.encodeFunctionData('sendWithdrawalRequests') - const { nonce } = await this.getNonce(userAddress) + const nonce = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, @@ -879,7 +879,7 @@ export class FoxyApi { this.normalizeAmount(amountDesired), ]) - const { nonce } = await this.getNonce(userAddress) + const nonce = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, @@ -921,7 +921,7 @@ export class FoxyApi { this.normalizeAmount(amountDesired), ]) - const { nonce } = await this.getNonce(userAddress) + const nonce = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, From a891d2cdd45bc9db72eefea97274c511f4cc2847 Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Mon, 24 Apr 2023 11:43:31 +0200 Subject: [PATCH 14/29] feat: remove investor-foxy's buildTxToSign and use buildCustomTx instead, removing a bunch more useless duplicate logic while at it --- packages/investor-foxy/src/api/api.ts | 28 ++++++++++++--- packages/investor-foxy/src/api/foxy-types.ts | 8 ++--- .../investor-foxy/src/utils/buildTxToSign.ts | 36 ------------------- packages/investor-foxy/src/utils/index.ts | 1 - .../Deposit/components/Approve.tsx | 5 +++ .../Deposit/components/Confirm.tsx | 4 +++ .../Overview/Claim/ClaimConfirm.tsx | 6 ++++ .../Withdraw/components/Approve.tsx | 4 +++ .../Withdraw/components/Confirm.tsx | 4 +++ src/state/apis/foxy/foxyApiSingleton.ts | 4 +-- 10 files changed, 52 insertions(+), 48 deletions(-) delete mode 100644 packages/investor-foxy/src/utils/buildTxToSign.ts diff --git a/packages/investor-foxy/src/api/api.ts b/packages/investor-foxy/src/api/api.ts index 1b8493d6f39..0328361d8fd 100644 --- a/packages/investor-foxy/src/api/api.ts +++ b/packages/investor-foxy/src/api/api.ts @@ -1,7 +1,7 @@ import { JsonRpcBatchProvider } from '@ethersproject/providers' import type { ChainReference } from '@shapeshiftoss/caip' import { CHAIN_NAMESPACE, CHAIN_REFERENCE, toAssetId } from '@shapeshiftoss/caip' -import type { ChainAdapter, FeeDataEstimate } from '@shapeshiftoss/chain-adapters' +import type { EvmBaseAdapter, FeeDataEstimate } from '@shapeshiftoss/chain-adapters' import { Logger } from '@shapeshiftoss/logger' import { KnownChainIds, WithdrawType } from '@shapeshiftoss/types' import axios from 'axios' @@ -24,7 +24,7 @@ import { tokePoolAddress, tokeRewardHashAddress, } from '../constants' -import { bn, bnOrZero, buildTxToSign } from '../utils' +import { bn, bnOrZero } from '../utils' import type { AllowanceInput, ApproveInput, @@ -62,7 +62,7 @@ type EthereumChainReference = | typeof CHAIN_REFERENCE.EthereumRopsten export type ConstructorArgs = { - adapter: ChainAdapter + adapter: EvmBaseAdapter providerUrl: string foxyAddresses: FoxyAddressesType chainReference?: EthereumChainReference @@ -86,7 +86,7 @@ export const transformData = ({ tvl, apy, expired, ...contractData }: FoxyOpport const TOKE_IPFS_URL = 'https://ipfs.tokemaklabs.xyz/ipfs' export class FoxyApi { - public adapter: ChainAdapter + public adapter: EvmBaseAdapter public provider: JsonRpcBatchProvider private providerUrl: string public jsonRpcProvider: JsonRpcBatchProvider @@ -125,9 +125,27 @@ export class FoxyApi { return ethers.BigNumber.from(amount.toFixed()) } + // TODO(gomes): This is rank. Move me to web for sanity sake. private async signAndBroadcastTx(input: SignAndBroadcastTx): Promise { const { payload, wallet, dryRun } = input - const txToSign = buildTxToSign(payload) + + const { + chainSpecific: { gasPrice, gasLimit, maxFeePerGas, maxPriorityFeePerGas }, + } = payload.estimatedFees.fast + const shouldUseEIP1559Fees = + (await wallet.ethSupportsEIP1559()) && + maxFeePerGas !== undefined && + maxPriorityFeePerGas !== undefined + + const { txToSign } = await this.adapter.buildCustomTx({ + to: payload.to, + value: payload.value, + gasLimit, + wallet, + data: payload.data, + accountNumber: payload.bip44Params.accountNumber, + ...(shouldUseEIP1559Fees ? { maxFeePerGas, maxPriorityFeePerGas } : { gasPrice }), + }) if (wallet.supportsOfflineSigning()) { const signedTx = await this.adapter.signTransaction({ txToSign, wallet }) if (dryRun) return signedTx diff --git a/packages/investor-foxy/src/api/foxy-types.ts b/packages/investor-foxy/src/api/foxy-types.ts index 72cbba14a48..c0aed1ac3e7 100644 --- a/packages/investor-foxy/src/api/foxy-types.ts +++ b/packages/investor-foxy/src/api/foxy-types.ts @@ -1,6 +1,6 @@ import type { AssetId } from '@shapeshiftoss/caip' import type { FeeDataEstimate } from '@shapeshiftoss/chain-adapters' -import type { HDWallet } from '@shapeshiftoss/hdwallet-core' +import type { ETHWallet } from '@shapeshiftoss/hdwallet-core' import type { BIP44Params, KnownChainIds, WithdrawType } from '@shapeshiftoss/types' import type { BigNumber } from 'bignumber.js' import type ethers from 'ethers' @@ -28,7 +28,7 @@ export type ApproveInput = { tokenContractAddress: string contractAddress: string userAddress: string - wallet: HDWallet + wallet: ETHWallet } export type EstimateApproveFeesInput = Pick< @@ -42,7 +42,7 @@ export type TxInput = { tokenContractAddress?: string userAddress: string contractAddress: string - wallet: HDWallet + wallet: ETHWallet amountDesired: BigNumber } @@ -111,7 +111,7 @@ export type SignAndBroadcastPayload = { export type SignAndBroadcastTx = { payload: SignAndBroadcastPayload - wallet: HDWallet + wallet: ETHWallet dryRun: boolean } diff --git a/packages/investor-foxy/src/utils/buildTxToSign.ts b/packages/investor-foxy/src/utils/buildTxToSign.ts deleted file mode 100644 index 9bb2fc5c607..00000000000 --- a/packages/investor-foxy/src/utils/buildTxToSign.ts +++ /dev/null @@ -1,36 +0,0 @@ -import type { FeeDataEstimate } from '@shapeshiftoss/chain-adapters' -import { toAddressNList } from '@shapeshiftoss/chain-adapters' -import type { ETHSignTx } from '@shapeshiftoss/hdwallet-core' -import type { BIP44Params, KnownChainIds } from '@shapeshiftoss/types' -import { numberToHex } from 'web3-utils' - -import { bnOrZero } from './bignumber' - -type BuildTxToSignInput = { - bip44Params: BIP44Params - chainId: number - data: string - estimatedFees: FeeDataEstimate - nonce: string - value: string - to: string -} - -export const buildTxToSign = ({ - bip44Params, - chainId = 1, - data, - estimatedFees, - nonce, - to, - value, -}: BuildTxToSignInput): ETHSignTx => ({ - addressNList: toAddressNList(bip44Params), - value: numberToHex(value), - to, - chainId, // TODO: implement for multiple chains - data, - nonce: numberToHex(nonce), - gasPrice: numberToHex(bnOrZero(estimatedFees.fast.chainSpecific.gasPrice).toString()), - gasLimit: numberToHex(bnOrZero(estimatedFees.fast.chainSpecific.gasLimit).toString()), -}) diff --git a/packages/investor-foxy/src/utils/index.ts b/packages/investor-foxy/src/utils/index.ts index dfd9ab73da5..fcd8f6c533e 100644 --- a/packages/investor-foxy/src/utils/index.ts +++ b/packages/investor-foxy/src/utils/index.ts @@ -1,2 +1 @@ export * from './bignumber' -export * from './buildTxToSign' diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Approve.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Approve.tsx index 9d11d79251c..c30474b284d 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Approve.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Approve.tsx @@ -1,6 +1,7 @@ import { useToast } from '@chakra-ui/react' import type { AccountId } from '@shapeshiftoss/caip' import { fromAccountId } from '@shapeshiftoss/caip' +import { supportsETH } from '@shapeshiftoss/hdwallet-core' import { Approve as ReusableApprove } from 'features/defi/components/Approve/Approve' import { ApprovePreFooter } from 'features/defi/components/Approve/ApprovePreFooter' import type { DepositValues } from 'features/defi/components/Deposit/Deposit' @@ -112,6 +113,10 @@ export const Approve: React.FC = ({ accountId, onNext }) => { return try { dispatch({ type: FoxyDepositActionType.SET_LOADING, payload: true }) + + if (!supportsETH(walletState.wallet)) + throw new Error(`handleApprove: wallet does not support ethereum`) + await foxyApi.approve({ tokenContractAddress: assetReference, contractAddress, diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx index 86f370e0674..a6e4f2e7ef3 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx @@ -2,6 +2,7 @@ import { Alert, AlertIcon, Box, Stack, useToast } from '@chakra-ui/react' import type { AccountId } from '@shapeshiftoss/caip' import { ethChainId, fromAccountId } from '@shapeshiftoss/caip' import type { EvmBaseAdapter, EvmChainId } from '@shapeshiftoss/chain-adapters' +import { supportsETH } from '@shapeshiftoss/hdwallet-core' import type { ethers } from 'ethers' import { Confirm as ReusableConfirm } from 'features/defi/components/Confirm/Confirm' import { Summary } from 'features/defi/components/Summary' @@ -86,6 +87,9 @@ export const Confirm: React.FC = ({ onNext, accountId }) => { const chainAdapterManager = getChainAdapterManager() const adapter = chainAdapterManager.get(ethChainId) as unknown as EvmBaseAdapter + if (!supportsETH(walletState.wallet)) + throw new Error(`handleDeposit: wallet does not support ethereum`) + const [txid, gasFees] = await Promise.all([ foxyApi.deposit({ amountDesired: bnOrZero(state?.deposit.cryptoAmount) diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimConfirm.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimConfirm.tsx index 5b9efd1d3a9..f2f720bd775 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimConfirm.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimConfirm.tsx @@ -10,6 +10,7 @@ import { } from '@chakra-ui/react' import type { AccountId, AssetId, ChainId } from '@shapeshiftoss/caip' import { ASSET_REFERENCE, toAssetId } from '@shapeshiftoss/caip' +import { supportsETH } from '@shapeshiftoss/hdwallet-core' import { KnownChainIds } from '@shapeshiftoss/types' import { useCallback, useEffect, useMemo, useState } from 'react' import { useTranslate } from 'react-polyglot' @@ -93,6 +94,8 @@ export const ClaimConfirm = ({ if (!(walletState.wallet && contractAddress && userAddress && foxyApi && bip44Params)) return setLoading(true) try { + if (!supportsETH(walletState.wallet)) + throw new Error(`handleConfirm: wallet does not support ethereum`) const txid = await foxyApi.claimWithdraw({ claimAddress: userAddress, userAddress, @@ -140,6 +143,9 @@ export const ClaimConfirm = ({ try { const chainAdapter = await chainAdapterManager.get(KnownChainIds.EthereumMainnet) if (!(walletState.wallet && contractAddress && foxyApi && chainAdapter)) return + if (!supportsETH(walletState.wallet)) + throw new Error(`ClaimConfirm::useEffect: wallet does not support ethereum`) + const { accountNumber } = bip44Params const userAddress = await chainAdapter.getAddress({ wallet: walletState.wallet, diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Approve.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Approve.tsx index f254430a857..f3fb4510d18 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Approve.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Approve.tsx @@ -1,6 +1,7 @@ import { useToast } from '@chakra-ui/react' import type { AccountId } from '@shapeshiftoss/caip' import { fromAccountId } from '@shapeshiftoss/caip' +import { supportsETH } from '@shapeshiftoss/hdwallet-core' import { Approve as ReusableApprove } from 'features/defi/components/Approve/Approve' import { ApprovePreFooter } from 'features/defi/components/Approve/ApprovePreFooter' import type { WithdrawValues } from 'features/defi/components/Withdraw/Withdraw' @@ -125,7 +126,10 @@ export const Approve: React.FC = ({ accountId, onNext }) => { ) ) return + try { + if (!supportsETH(walletState.wallet)) + throw new Error(`handleApprove: wallet does not support ethereum`) dispatch({ type: FoxyWithdrawActionType.SET_LOADING, payload: true }) await foxyApi.approve({ tokenContractAddress: rewardId, diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx index 3b3fcacd128..156d09dde1a 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx @@ -2,6 +2,7 @@ import { Alert, AlertIcon, Box, Stack } from '@chakra-ui/react' import type { AccountId } from '@shapeshiftoss/caip' import { ethChainId, fromAccountId } from '@shapeshiftoss/caip' import type { EvmBaseAdapter, EvmChainId } from '@shapeshiftoss/chain-adapters' +import { supportsETH } from '@shapeshiftoss/hdwallet-core' import { WithdrawType } from '@shapeshiftoss/types' import type { ethers } from 'ethers' import { Confirm as ReusableConfirm } from 'features/defi/components/Confirm/Confirm' @@ -91,6 +92,9 @@ export const Confirm: React.FC + if (!supportsETH(walletState.wallet)) + throw new Error(`handleConfirm: wallet does not support ethereum`) + const [txid, gasFees] = await Promise.all([ foxyApi.withdraw({ tokenContractAddress: rewardId, diff --git a/src/state/apis/foxy/foxyApiSingleton.ts b/src/state/apis/foxy/foxyApiSingleton.ts index d590b36db6e..520f02992d5 100644 --- a/src/state/apis/foxy/foxyApiSingleton.ts +++ b/src/state/apis/foxy/foxyApiSingleton.ts @@ -1,4 +1,4 @@ -import type { ChainAdapter } from '@shapeshiftoss/chain-adapters' +import type { EvmBaseAdapter } from '@shapeshiftoss/chain-adapters' import { foxyAddresses, FoxyApi } from '@shapeshiftoss/investor-foxy' import { KnownChainIds } from '@shapeshiftoss/types' import { getConfig } from 'config' @@ -22,7 +22,7 @@ export const getFoxyApi = (): FoxyApi => { const foxyApi = new FoxyApi({ adapter: getChainAdapterManager().get( KnownChainIds.EthereumMainnet, - ) as ChainAdapter, + ) as unknown as EvmBaseAdapter, providerUrl: getConfig()[RPC_PROVIDER_ENV], foxyAddresses, }) From a8cbcfbeb07fdff6770c63b6bdfb7a539db85729 Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Mon, 24 Apr 2023 11:52:01 +0200 Subject: [PATCH 15/29] feat: more cleanup, remove getNonce, why tf did we need this --- packages/investor-foxy/src/api/api.ts | 27 +------------------- packages/investor-foxy/src/api/foxy-types.ts | 1 - 2 files changed, 1 insertion(+), 27 deletions(-) diff --git a/packages/investor-foxy/src/api/api.ts b/packages/investor-foxy/src/api/api.ts index 0328361d8fd..7bb84a89c55 100644 --- a/packages/investor-foxy/src/api/api.ts +++ b/packages/investor-foxy/src/api/api.ts @@ -125,7 +125,7 @@ export class FoxyApi { return ethers.BigNumber.from(amount.toFixed()) } - // TODO(gomes): This is rank. Move me to web for sanity sake. + // TODO(gomes): This is rank and should really belong in web for sanity sake. private async signAndBroadcastTx(input: SignAndBroadcastTx): Promise { const { payload, wallet, dryRun } = input @@ -199,17 +199,6 @@ export class FoxyApi { return liquidityReserveContract } - private async getNonce(userAddress: string): Promise { - let nonce - try { - nonce = (await this.provider.getTransactionCount(userAddress)).toString() - } catch (e) { - throw new Error(`Get nonce Error: ${e}`) - } - - return nonce - } - async getFoxyOpportunities() { try { const opportunities = await Promise.all( @@ -523,14 +512,12 @@ export class FoxyApi { amount ? numberToHex(bnOrZero(amount).toString()) : MAX_ALLOWANCE, ]) - const nonce = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, chainId: chainReferenceAsNumber, data, estimatedFees, - nonce, to: tokenContractAddress, value: '0', } @@ -583,14 +570,12 @@ export class FoxyApi { userAddress, ]) - const nonce = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, chainId: chainReferenceAsNumber, data, estimatedFees, - nonce, to: contractAddress, value: '0', } @@ -629,14 +614,12 @@ export class FoxyApi { : ['instantUnstake', ['true']] const data: string = stakingContract.interface.encodeFunctionData(...stakingContractCallInput) - const nonce = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, chainId: chainReferenceAsNumber, data, estimatedFees, - nonce, to: contractAddress, value: '0', } @@ -746,14 +729,12 @@ export class FoxyApi { addressToClaim, ]) - const nonce = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, chainId: chainReferenceAsNumber, data, estimatedFees, - nonce, to: contractAddress, value: '0', } @@ -854,14 +835,12 @@ export class FoxyApi { if (!canSendRequest) throw new Error('Not ready to send request') const data: string = stakingContract.interface.encodeFunctionData('sendWithdrawalRequests') - const nonce = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, chainId: chainReferenceAsNumber, data, estimatedFees, - nonce, to: contractAddress, value: '0', } @@ -897,14 +876,12 @@ export class FoxyApi { this.normalizeAmount(amountDesired), ]) - const nonce = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, chainId: chainReferenceAsNumber, data, estimatedFees, - nonce, to: contractAddress, value: '0', } @@ -939,14 +916,12 @@ export class FoxyApi { this.normalizeAmount(amountDesired), ]) - const nonce = await this.getNonce(userAddress) const chainReferenceAsNumber = Number(this.ethereumChainReference) const payload = { bip44Params, chainId: chainReferenceAsNumber, data, estimatedFees, - nonce, to: contractAddress, value: '0', } diff --git a/packages/investor-foxy/src/api/foxy-types.ts b/packages/investor-foxy/src/api/foxy-types.ts index c0aed1ac3e7..dc7946c565b 100644 --- a/packages/investor-foxy/src/api/foxy-types.ts +++ b/packages/investor-foxy/src/api/foxy-types.ts @@ -104,7 +104,6 @@ export type SignAndBroadcastPayload = { chainId: number data: string estimatedFees: FeeDataEstimate - nonce: string to: string value: string } From 0806b0db442378a53b77e7514166a845343e4a7d Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Mon, 24 Apr 2023 12:46:44 +0200 Subject: [PATCH 16/29] feat: consistently use JsonRpcBatchProvider --- .../src/generateAssetData/ethereum/yearnVaults.ts | 4 ++-- packages/caip/src/adapters/yearn/utils.ts | 4 ++-- packages/investor-yearn/src/YearnInvestor.ts | 4 ++-- .../unchained-client/src/evm/bnbsmartchain/parser/bep20.ts | 5 +++-- packages/unchained-client/src/evm/ethereum/parser/uniV2.ts | 6 +++--- packages/unchained-client/src/evm/ethereum/parser/weth.ts | 6 +++--- packages/unchained-client/src/evm/parser/erc20.ts | 5 +++-- packages/unchained-client/src/evm/parser/index.ts | 6 +++--- .../components/FoxyManager/Withdraw/components/Confirm.tsx | 2 +- src/plugins/walletConnectToDapps/hooks/useGetAbi.tsx | 3 ++- 10 files changed, 24 insertions(+), 21 deletions(-) diff --git a/packages/asset-service/src/generateAssetData/ethereum/yearnVaults.ts b/packages/asset-service/src/generateAssetData/ethereum/yearnVaults.ts index 17603da3c27..7ea4442670f 100644 --- a/packages/asset-service/src/generateAssetData/ethereum/yearnVaults.ts +++ b/packages/asset-service/src/generateAssetData/ethereum/yearnVaults.ts @@ -1,4 +1,4 @@ -import { JsonRpcProvider } from '@ethersproject/providers' +import { JsonRpcBatchProvider } from '@ethersproject/providers' import { ethChainId as chainId, toAssetId } from '@shapeshiftoss/caip' import type { Token, Vault } from '@yfi/sdk' import { Yearn } from '@yfi/sdk' @@ -9,7 +9,7 @@ import { ethereum } from '../baseAssets' import { colorMap } from '../colorMap' const network = 1 // 1 for mainnet -const provider = new JsonRpcProvider(process.env.ETHEREUM_NODE_URL) +const provider = new JsonRpcBatchProvider(process.env.ETHEREUM_NODE_URL) export const yearnSdk = new Yearn(network, { provider }) const explorerData = { diff --git a/packages/caip/src/adapters/yearn/utils.ts b/packages/caip/src/adapters/yearn/utils.ts index bd2f7a5aff4..c1927c39ff6 100644 --- a/packages/caip/src/adapters/yearn/utils.ts +++ b/packages/caip/src/adapters/yearn/utils.ts @@ -1,5 +1,5 @@ +import { JsonRpcBatchProvider } from '@ethersproject/providers' /* eslint-disable @shapeshiftoss/logger/no-native-console */ -import { JsonRpcProvider } from '@ethersproject/providers' import type { Token, Vault } from '@yfi/sdk' import { Yearn } from '@yfi/sdk' import fs from 'fs' @@ -11,7 +11,7 @@ import { toChainId } from '../../chainId/chainId' import { CHAIN_NAMESPACE, CHAIN_REFERENCE } from '../../constants' const network = 1 // 1 for mainnet -const provider = new JsonRpcProvider(process.env.REACT_APP_ETHEREUM_NODE_URL) +const provider = new JsonRpcBatchProvider(process.env.REACT_APP_ETHEREUM_NODE_URL) const yearnSdk = new Yearn(network, { provider }) export const writeFiles = async (data: Record>) => { diff --git a/packages/investor-yearn/src/YearnInvestor.ts b/packages/investor-yearn/src/YearnInvestor.ts index f31329da6ab..aef4d438044 100644 --- a/packages/investor-yearn/src/YearnInvestor.ts +++ b/packages/investor-yearn/src/YearnInvestor.ts @@ -1,4 +1,4 @@ -import { JsonRpcProvider } from '@ethersproject/providers' +import { JsonRpcBatchProvider } from '@ethersproject/providers' import type { ChainAdapter } from '@shapeshiftoss/chain-adapters' import type { Investor } from '@shapeshiftoss/investor' import type { KnownChainIds } from '@shapeshiftoss/types' @@ -31,7 +31,7 @@ export class YearnInvestor implements Investor implements SubParser { - provider: ethers.providers.JsonRpcProvider + provider: JsonRpcBatchProvider readonly chainId: ChainId readonly abiInterface = new ethers.utils.Interface(bep20) diff --git a/packages/unchained-client/src/evm/ethereum/parser/uniV2.ts b/packages/unchained-client/src/evm/ethereum/parser/uniV2.ts index 4006b88c755..2f2c4a4d3ca 100644 --- a/packages/unchained-client/src/evm/ethereum/parser/uniV2.ts +++ b/packages/unchained-client/src/evm/ethereum/parser/uniV2.ts @@ -1,3 +1,4 @@ +import type { JsonRpcBatchProvider } from '@ethersproject/providers' import type { ChainId } from '@shapeshiftoss/caip' import { fromChainId, toAssetId } from '@shapeshiftoss/caip' import { ethers } from 'ethers' @@ -23,12 +24,11 @@ export interface TxMetadata extends BaseTxMetadata { export interface ParserArgs { chainId: ChainId - provider: ethers.providers.JsonRpcProvider + provider: JsonRpcBatchProvider } export class Parser implements SubParser { - provider: ethers.providers.JsonRpcProvider - + provider: JsonRpcBatchProvider readonly chainId: ChainId readonly wethContract: string readonly abiInterface = new ethers.utils.Interface(UNIV2_ABI) diff --git a/packages/unchained-client/src/evm/ethereum/parser/weth.ts b/packages/unchained-client/src/evm/ethereum/parser/weth.ts index 1310dd86e12..349fd6adfe6 100644 --- a/packages/unchained-client/src/evm/ethereum/parser/weth.ts +++ b/packages/unchained-client/src/evm/ethereum/parser/weth.ts @@ -1,3 +1,4 @@ +import type { JsonRpcBatchProvider } from '@ethersproject/providers' import type { ChainId } from '@shapeshiftoss/caip' import { fromChainId, toAssetId } from '@shapeshiftoss/caip' import { ethers } from 'ethers' @@ -16,12 +17,11 @@ export interface TxMetadata extends BaseTxMetadata { export interface ParserArgs { chainId: ChainId - provider: ethers.providers.JsonRpcProvider + provider: JsonRpcBatchProvider } export class Parser implements SubParser { - provider: ethers.providers.JsonRpcProvider - + provider: JsonRpcBatchProvider readonly chainId: ChainId readonly wethContract: string readonly abiInterface = new ethers.utils.Interface(WETH_ABI) diff --git a/packages/unchained-client/src/evm/parser/erc20.ts b/packages/unchained-client/src/evm/parser/erc20.ts index 7f799af86a7..f7d298f1d68 100644 --- a/packages/unchained-client/src/evm/parser/erc20.ts +++ b/packages/unchained-client/src/evm/parser/erc20.ts @@ -1,3 +1,4 @@ +import type { JsonRpcBatchProvider } from '@ethersproject/providers' import type { ChainId } from '@shapeshiftoss/caip' import { toAssetId } from '@shapeshiftoss/caip' import type { BigNumber } from 'ethers' @@ -16,11 +17,11 @@ export interface TxMetadata extends BaseTxMetadata { interface ParserArgs { chainId: ChainId - provider: ethers.providers.JsonRpcProvider + provider: JsonRpcBatchProvider } export class Parser implements SubParser { - provider: ethers.providers.JsonRpcProvider + provider: JsonRpcBatchProvider readonly chainId: ChainId readonly abiInterface = new ethers.utils.Interface(ERC20_ABI) diff --git a/packages/unchained-client/src/evm/parser/index.ts b/packages/unchained-client/src/evm/parser/index.ts index 9c1c0d1c269..962245c4d1f 100644 --- a/packages/unchained-client/src/evm/parser/index.ts +++ b/packages/unchained-client/src/evm/parser/index.ts @@ -1,3 +1,4 @@ +import { JsonRpcBatchProvider } from '@ethersproject/providers' import type { AssetId, ChainId } from '@shapeshiftoss/caip' import { ASSET_NAMESPACE, ASSET_REFERENCE, ethChainId, toAssetId } from '@shapeshiftoss/caip' import { BigNumber } from 'bignumber.js' @@ -21,14 +22,13 @@ export class BaseTransactionParser { chainId: ChainId assetId: AssetId - protected readonly provider: ethers.providers.JsonRpcProvider - + protected readonly provider: JsonRpcBatchProvider private parsers: SubParser[] = [] constructor(args: TransactionParserArgs) { this.chainId = args.chainId this.assetId = args.assetId - this.provider = new ethers.providers.JsonRpcProvider(args.rpcUrl) + this.provider = new JsonRpcBatchProvider(args.rpcUrl) } /** diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx index 156d09dde1a..b91be0ef513 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx @@ -155,7 +155,7 @@ export const Confirm: React.FC onNext(DefiStep.Info)} headerText='modals.confirm.withdraw.header' onConfirm={handleConfirm} - isDisabled={!hasEnoughBalanceForGas} + isDisabled={false} loading={state.loading} loadingText={translate('common.confirm')} > diff --git a/src/plugins/walletConnectToDapps/hooks/useGetAbi.tsx b/src/plugins/walletConnectToDapps/hooks/useGetAbi.tsx index 641565b3db3..d95d4d152eb 100644 --- a/src/plugins/walletConnectToDapps/hooks/useGetAbi.tsx +++ b/src/plugins/walletConnectToDapps/hooks/useGetAbi.tsx @@ -1,3 +1,4 @@ +import { JsonRpcBatchProvider } from '@ethersproject/providers' import { skipToken } from '@reduxjs/toolkit/query' import { getConfig } from 'config' import { ethers } from 'ethers' @@ -14,7 +15,7 @@ export const useGetAbi = ( const { to: contractAddress, data } = transactionParams const provider = useMemo( - () => new ethers.providers.JsonRpcProvider(getConfig().REACT_APP_ETHEREUM_NODE_URL), + () => new JsonRpcBatchProvider(getConfig().REACT_APP_ETHEREUM_NODE_URL), [], ) From 73d52952190a60300b9e0b19869d733ad973d6ad Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Mon, 24 Apr 2023 12:56:58 +0200 Subject: [PATCH 17/29] feat: actually remove web3 deps from investor-foxy --- packages/investor-foxy/package.json | 4 +--- packages/investor-foxy/src/api/api.ts | 3 +-- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/packages/investor-foxy/package.json b/packages/investor-foxy/package.json index a0bcb98f158..4725c07ffb9 100644 --- a/packages/investor-foxy/package.json +++ b/packages/investor-foxy/package.json @@ -27,9 +27,7 @@ "@shapeshiftoss/logger": "workspace:^", "@shapeshiftoss/types": "workspace:^", "ethers": "^5.7.2", - "readline-sync": "^1.4.10", - "web3-core": "1.7.4", - "web3-utils": "1.7.4" + "readline-sync": "^1.4.10" }, "devDependencies": { "@types/readline-sync": "^1.4.4" diff --git a/packages/investor-foxy/src/api/api.ts b/packages/investor-foxy/src/api/api.ts index 7bb84a89c55..44a66d889ac 100644 --- a/packages/investor-foxy/src/api/api.ts +++ b/packages/investor-foxy/src/api/api.ts @@ -8,7 +8,6 @@ import axios from 'axios' import type { BigNumber } from 'bignumber.js' import { ethers } from 'ethers' import { toLower } from 'lodash' -import { numberToHex } from 'web3-utils' import { erc20Abi } from '../abi/erc20-abi' import { foxyAbi } from '../abi/foxy-abi' @@ -509,7 +508,7 @@ export class FoxyApi { const depositTokenContract = new ethers.Contract(tokenContractAddress, erc20Abi, this.provider) const data: string = depositTokenContract.interface.encodeFunctionData('approve', [ contractAddress, - amount ? numberToHex(bnOrZero(amount).toString()) : MAX_ALLOWANCE, + amount ? this.normalizeAmount(bnOrZero(amount)) : MAX_ALLOWANCE, ]) const chainReferenceAsNumber = Number(this.ethereumChainReference) From 615d8ddf8177ee4ec687f3af1aca63a56ce6c389 Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Mon, 24 Apr 2023 13:07:05 +0200 Subject: [PATCH 18/29] fix: big derp --- packages/investor-foxy/src/api/api.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/investor-foxy/src/api/api.ts b/packages/investor-foxy/src/api/api.ts index 44a66d889ac..57eaf6d9aa4 100644 --- a/packages/investor-foxy/src/api/api.ts +++ b/packages/investor-foxy/src/api/api.ts @@ -431,7 +431,7 @@ export class FoxyApi { MAX_ALLOWANCE, ]) const estimatedFees = await this.adapter.getFeeData({ - to: contractAddress, + to: tokenContractAddress, value: '0', chainSpecific: { contractData: data, From 2a3ef7401921fad57223a77e8a8dbf7f8cb46831 Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Mon, 24 Apr 2023 13:07:39 +0200 Subject: [PATCH 19/29] feat: regenerate yarn.lock --- yarn.lock | 2 -- 1 file changed, 2 deletions(-) diff --git a/yarn.lock b/yarn.lock index 38225489cfd..b216a71fda9 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6148,8 +6148,6 @@ __metadata: "@types/readline-sync": ^1.4.4 ethers: ^5.7.2 readline-sync: ^1.4.10 - web3-core: 1.7.4 - web3-utils: 1.7.4 languageName: unknown linkType: soft From 5903028f8c2376a666ab9480aec528e750b2508e Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Mon, 24 Apr 2023 18:07:29 +0200 Subject: [PATCH 20/29] feat: excuse my LSP --- packages/caip/src/adapters/yearn/utils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/caip/src/adapters/yearn/utils.ts b/packages/caip/src/adapters/yearn/utils.ts index c1927c39ff6..fa28578b846 100644 --- a/packages/caip/src/adapters/yearn/utils.ts +++ b/packages/caip/src/adapters/yearn/utils.ts @@ -1,5 +1,5 @@ -import { JsonRpcBatchProvider } from '@ethersproject/providers' /* eslint-disable @shapeshiftoss/logger/no-native-console */ +import { JsonRpcBatchProvider } from '@ethersproject/providers' import type { Token, Vault } from '@yfi/sdk' import { Yearn } from '@yfi/sdk' import fs from 'fs' From 0b8f0771b5434e077875e8af5e6956d71e4d1efb Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Mon, 24 Apr 2023 18:24:35 +0200 Subject: [PATCH 21/29] feat: one ethers to rule them all --- package.json | 1 + packages/asset-service/package.json | 1 - packages/investor-foxy/package.json | 2 -- packages/investor-idle/package.json | 1 - packages/investor-yearn/package.json | 1 - packages/market-service/package.json | 1 - yarn.lock | 9 ++------- 7 files changed, 3 insertions(+), 13 deletions(-) diff --git a/package.json b/package.json index d1a5347fb40..a7d09377590 100644 --- a/package.json +++ b/package.json @@ -73,6 +73,7 @@ "@chakra-ui/tag": "^2.0.2", "@emotion/react": "^11.9.3", "@emotion/styled": "^11.9.3", + "@ethersproject/providers": "5.7.2", "@formatjs/intl-getcanonicallocales": "^2.0.2", "@formatjs/intl-locale": "^3.0.2", "@formatjs/intl-numberformat": "^8.0.2", diff --git a/packages/asset-service/package.json b/packages/asset-service/package.json index f98895d60fb..b742328d827 100644 --- a/packages/asset-service/package.json +++ b/packages/asset-service/package.json @@ -29,7 +29,6 @@ "js-pixel-fonts": "^1.5.0" }, "devDependencies": { - "@ethersproject/providers": "^5.7.2", "@yfi/sdk": "^1.2.0", "colorthief": "^2.3.2" } diff --git a/packages/investor-foxy/package.json b/packages/investor-foxy/package.json index 4725c07ffb9..26bf7a9cb21 100644 --- a/packages/investor-foxy/package.json +++ b/packages/investor-foxy/package.json @@ -21,12 +21,10 @@ "cli": "yarn build && yarn node dist/foxycli.js" }, "dependencies": { - "@ethersproject/providers": "^5.7.2", "@shapeshiftoss/caip": "workspace:^", "@shapeshiftoss/chain-adapters": "workspace:^", "@shapeshiftoss/logger": "workspace:^", "@shapeshiftoss/types": "workspace:^", - "ethers": "^5.7.2", "readline-sync": "^1.4.10" }, "devDependencies": { diff --git a/packages/investor-idle/package.json b/packages/investor-idle/package.json index a7ebc2b7f53..62d528edaa0 100644 --- a/packages/investor-idle/package.json +++ b/packages/investor-idle/package.json @@ -21,7 +21,6 @@ "cli": "yarn build && yarn node dist/idlecli.js" }, "dependencies": { - "@ethersproject/providers": "^5.7.2", "@shapeshiftoss/caip": "workspace:^", "@shapeshiftoss/chain-adapters": "workspace:^", "@shapeshiftoss/investor": "workspace:^", diff --git a/packages/investor-yearn/package.json b/packages/investor-yearn/package.json index 21bb01901e6..94156bb281e 100644 --- a/packages/investor-yearn/package.json +++ b/packages/investor-yearn/package.json @@ -21,7 +21,6 @@ "cli": "yarn build && yarn node dist/yearncli.js" }, "dependencies": { - "@ethersproject/providers": "^5.7.2", "@shapeshiftoss/caip": "workspace:^", "@shapeshiftoss/chain-adapters": "workspace:^", "@shapeshiftoss/investor": "workspace:^", diff --git a/packages/market-service/package.json b/packages/market-service/package.json index 2a209453a1b..80d0ced2fc4 100644 --- a/packages/market-service/package.json +++ b/packages/market-service/package.json @@ -18,7 +18,6 @@ "dev": "yarn run -T tsc --build --watch" }, "dependencies": { - "@ethersproject/providers": "^5.7.2", "@shapeshiftoss/caip": "workspace:^", "@shapeshiftoss/chain-adapters": "workspace:^", "@shapeshiftoss/investor-foxy": "workspace:^", diff --git a/yarn.lock b/yarn.lock index b216a71fda9..8e16cd173cb 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4180,7 +4180,7 @@ __metadata: languageName: node linkType: hard -"@ethersproject/providers@npm:5.7.2, @ethersproject/providers@npm:^5.7.2": +"@ethersproject/providers@npm:5.7.2": version: 5.7.2 resolution: "@ethersproject/providers@npm:5.7.2" dependencies: @@ -5830,7 +5830,6 @@ __metadata: version: 0.0.0-use.local resolution: "@shapeshiftoss/asset-service@workspace:packages/asset-service" dependencies: - "@ethersproject/providers": ^5.7.2 "@shapeshiftoss/caip": "workspace:^" "@shapeshiftoss/investor-idle": "workspace:^" "@shapeshiftoss/types": "workspace:^" @@ -6140,13 +6139,11 @@ __metadata: version: 0.0.0-use.local resolution: "@shapeshiftoss/investor-foxy@workspace:packages/investor-foxy" dependencies: - "@ethersproject/providers": ^5.7.2 "@shapeshiftoss/caip": "workspace:^" "@shapeshiftoss/chain-adapters": "workspace:^" "@shapeshiftoss/logger": "workspace:^" "@shapeshiftoss/types": "workspace:^" "@types/readline-sync": ^1.4.4 - ethers: ^5.7.2 readline-sync: ^1.4.10 languageName: unknown linkType: soft @@ -6155,7 +6152,6 @@ __metadata: version: 0.0.0-use.local resolution: "@shapeshiftoss/investor-idle@workspace:packages/investor-idle" dependencies: - "@ethersproject/providers": ^5.7.2 "@shapeshiftoss/caip": "workspace:^" "@shapeshiftoss/chain-adapters": "workspace:^" "@shapeshiftoss/investor": "workspace:^" @@ -6170,7 +6166,6 @@ __metadata: version: 0.0.0-use.local resolution: "@shapeshiftoss/investor-yearn@workspace:packages/investor-yearn" dependencies: - "@ethersproject/providers": ^5.7.2 "@shapeshiftoss/caip": "workspace:^" "@shapeshiftoss/chain-adapters": "workspace:^" "@shapeshiftoss/investor": "workspace:^" @@ -6200,7 +6195,6 @@ __metadata: version: 0.0.0-use.local resolution: "@shapeshiftoss/market-service@workspace:packages/market-service" dependencies: - "@ethersproject/providers": ^5.7.2 "@shapeshiftoss/caip": "workspace:^" "@shapeshiftoss/chain-adapters": "workspace:^" "@shapeshiftoss/investor-foxy": "workspace:^" @@ -6273,6 +6267,7 @@ __metadata: "@commitlint/config-conventional": ^15.0.0 "@emotion/react": ^11.9.3 "@emotion/styled": ^11.9.3 + "@ethersproject/providers": 5.7.2 "@formatjs/intl-getcanonicallocales": ^2.0.2 "@formatjs/intl-locale": ^3.0.2 "@formatjs/intl-numberformat": ^8.0.2 From 7a1ca4a0f1aa5a879a3a88a10e29578a3c5d75cd Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Mon, 24 Apr 2023 18:26:30 +0200 Subject: [PATCH 22/29] feat: import from ethers vs ethers/lib --- packages/investor-foxy/src/abi/erc20-abi.ts | 2 +- packages/investor-foxy/src/abi/foxy-abi.ts | 2 +- packages/investor-foxy/src/abi/foxy-staking-abi.ts | 2 +- packages/investor-foxy/src/abi/liquidity-reserve-abi.ts | 2 +- packages/investor-foxy/src/abi/toke-manager-abi.ts | 2 +- packages/investor-foxy/src/abi/toke-pool-abi.ts | 2 +- packages/investor-foxy/src/abi/toke-reward-hash-abi.ts | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/investor-foxy/src/abi/erc20-abi.ts b/packages/investor-foxy/src/abi/erc20-abi.ts index 6d3c608bff2..ae7e19c78ef 100644 --- a/packages/investor-foxy/src/abi/erc20-abi.ts +++ b/packages/investor-foxy/src/abi/erc20-abi.ts @@ -1,4 +1,4 @@ -import type { ContractInterface } from 'ethers/lib/ethers' +import type { ContractInterface } from 'ethers' export const erc20Abi: ContractInterface = [ { diff --git a/packages/investor-foxy/src/abi/foxy-abi.ts b/packages/investor-foxy/src/abi/foxy-abi.ts index 8a0a8563606..99522a88a09 100644 --- a/packages/investor-foxy/src/abi/foxy-abi.ts +++ b/packages/investor-foxy/src/abi/foxy-abi.ts @@ -1,4 +1,4 @@ -import type { ContractInterface } from 'ethers/lib/ethers' +import type { ContractInterface } from 'ethers' export const foxyAbi: ContractInterface = [ { diff --git a/packages/investor-foxy/src/abi/foxy-staking-abi.ts b/packages/investor-foxy/src/abi/foxy-staking-abi.ts index eb667ab58ef..0d62f0aae71 100644 --- a/packages/investor-foxy/src/abi/foxy-staking-abi.ts +++ b/packages/investor-foxy/src/abi/foxy-staking-abi.ts @@ -1,4 +1,4 @@ -import type { ContractInterface } from 'ethers/lib/ethers' +import type { ContractInterface } from 'ethers' export const foxyStakingAbi: ContractInterface = [ { diff --git a/packages/investor-foxy/src/abi/liquidity-reserve-abi.ts b/packages/investor-foxy/src/abi/liquidity-reserve-abi.ts index fedefe5c43c..4cea3c40602 100644 --- a/packages/investor-foxy/src/abi/liquidity-reserve-abi.ts +++ b/packages/investor-foxy/src/abi/liquidity-reserve-abi.ts @@ -1,4 +1,4 @@ -import type { ContractInterface } from 'ethers/lib/ethers' +import type { ContractInterface } from 'ethers' export const liquidityReserveAbi: ContractInterface = [ { diff --git a/packages/investor-foxy/src/abi/toke-manager-abi.ts b/packages/investor-foxy/src/abi/toke-manager-abi.ts index ab0a29c8a9e..a4a5250015e 100644 --- a/packages/investor-foxy/src/abi/toke-manager-abi.ts +++ b/packages/investor-foxy/src/abi/toke-manager-abi.ts @@ -1,4 +1,4 @@ -import type { ContractInterface } from 'ethers/lib/ethers' +import type { ContractInterface } from 'ethers' export const tokeManagerAbi: ContractInterface = [ { inputs: [], stateMutability: 'nonpayable', type: 'constructor' }, diff --git a/packages/investor-foxy/src/abi/toke-pool-abi.ts b/packages/investor-foxy/src/abi/toke-pool-abi.ts index c33909307f1..4ef28248b05 100644 --- a/packages/investor-foxy/src/abi/toke-pool-abi.ts +++ b/packages/investor-foxy/src/abi/toke-pool-abi.ts @@ -1,4 +1,4 @@ -import type { ContractInterface } from 'ethers/lib/ethers' +import type { ContractInterface } from 'ethers' export const tokePoolAbi: ContractInterface = [ { diff --git a/packages/investor-foxy/src/abi/toke-reward-hash-abi.ts b/packages/investor-foxy/src/abi/toke-reward-hash-abi.ts index f16d0a4687b..c2d62f9274c 100644 --- a/packages/investor-foxy/src/abi/toke-reward-hash-abi.ts +++ b/packages/investor-foxy/src/abi/toke-reward-hash-abi.ts @@ -1,4 +1,4 @@ -import type { ContractInterface } from 'ethers/lib/ethers' +import type { ContractInterface } from 'ethers' export const tokeRewardHashAbi: ContractInterface = [ { inputs: [], stateMutability: 'nonpayable', type: 'constructor' }, From e62a24dd681691a60478bc17ae8c3760581208e4 Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Mon, 24 Apr 2023 18:28:24 +0200 Subject: [PATCH 23/29] feat: that damn LSP --- packages/investor-foxy/src/api/foxy-types.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/investor-foxy/src/api/foxy-types.ts b/packages/investor-foxy/src/api/foxy-types.ts index dc7946c565b..ce166d5ef06 100644 --- a/packages/investor-foxy/src/api/foxy-types.ts +++ b/packages/investor-foxy/src/api/foxy-types.ts @@ -3,7 +3,7 @@ import type { FeeDataEstimate } from '@shapeshiftoss/chain-adapters' import type { ETHWallet } from '@shapeshiftoss/hdwallet-core' import type { BIP44Params, KnownChainIds, WithdrawType } from '@shapeshiftoss/types' import type { BigNumber } from 'bignumber.js' -import type ethers from 'ethers' +import type { Contract } from 'ethers' export type FoxyAddressesType = { staking: string @@ -148,7 +148,7 @@ export type RebaseHistory = { } export type StakingContract = { - stakingContract: ethers.ethers.Contract + stakingContract: Contract } // this comment only exists to publish this package - delete me if you see me From 41f4280cb74fc1c5e51c4fa66abb5ac95b090c16 Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Mon, 24 Apr 2023 18:34:58 +0200 Subject: [PATCH 24/29] feat: rm @ethersproject/providers dep --- __mocks__/ethers.ts | 1 + package.json | 1 - .../src/generateAssetData/ethereum/yearnVaults.ts | 4 ++-- packages/caip/src/adapters/yearn/utils.ts | 4 ++-- packages/investor-foxy/src/api/api.ts | 9 ++++----- packages/investor-yearn/src/YearnInvestor.ts | 4 ++-- packages/market-service/src/market-service-manager.ts | 1 - .../src/evm/bnbsmartchain/parser/bep20.ts | 5 ++--- .../unchained-client/src/evm/ethereum/parser/uniV2.ts | 5 ++--- .../unchained-client/src/evm/ethereum/parser/weth.ts | 5 ++--- packages/unchained-client/src/evm/parser/erc20.ts | 5 ++--- packages/unchained-client/src/evm/parser/index.ts | 5 ++--- src/plugins/walletConnectToDapps/hooks/useGetAbi.tsx | 3 +-- yarn.lock | 1 - 14 files changed, 22 insertions(+), 31 deletions(-) diff --git a/__mocks__/ethers.ts b/__mocks__/ethers.ts index 7da501f0f23..bdf627aea50 100644 --- a/__mocks__/ethers.ts +++ b/__mocks__/ethers.ts @@ -3,6 +3,7 @@ const ethers = { ...jest.requireActual('ethers').ethers, providers: { JsonRpcProvider: jest.fn(), + JsonRpcBatchProvider: jest.fn(), }, Contract: jest.fn().mockImplementation(address => ({ decimals: () => { diff --git a/package.json b/package.json index a7d09377590..d1a5347fb40 100644 --- a/package.json +++ b/package.json @@ -73,7 +73,6 @@ "@chakra-ui/tag": "^2.0.2", "@emotion/react": "^11.9.3", "@emotion/styled": "^11.9.3", - "@ethersproject/providers": "5.7.2", "@formatjs/intl-getcanonicallocales": "^2.0.2", "@formatjs/intl-locale": "^3.0.2", "@formatjs/intl-numberformat": "^8.0.2", diff --git a/packages/asset-service/src/generateAssetData/ethereum/yearnVaults.ts b/packages/asset-service/src/generateAssetData/ethereum/yearnVaults.ts index 7ea4442670f..fc74776baec 100644 --- a/packages/asset-service/src/generateAssetData/ethereum/yearnVaults.ts +++ b/packages/asset-service/src/generateAssetData/ethereum/yearnVaults.ts @@ -1,7 +1,7 @@ -import { JsonRpcBatchProvider } from '@ethersproject/providers' import { ethChainId as chainId, toAssetId } from '@shapeshiftoss/caip' import type { Token, Vault } from '@yfi/sdk' import { Yearn } from '@yfi/sdk' +import { ethers } from 'ethers' import toLower from 'lodash/toLower' import type { Asset } from '../../service/AssetService' @@ -9,7 +9,7 @@ import { ethereum } from '../baseAssets' import { colorMap } from '../colorMap' const network = 1 // 1 for mainnet -const provider = new JsonRpcBatchProvider(process.env.ETHEREUM_NODE_URL) +const provider = new ethers.providers.JsonRpcBatchProvider(process.env.ETHEREUM_NODE_URL) export const yearnSdk = new Yearn(network, { provider }) const explorerData = { diff --git a/packages/caip/src/adapters/yearn/utils.ts b/packages/caip/src/adapters/yearn/utils.ts index fa28578b846..9882d69cb09 100644 --- a/packages/caip/src/adapters/yearn/utils.ts +++ b/packages/caip/src/adapters/yearn/utils.ts @@ -1,7 +1,7 @@ /* eslint-disable @shapeshiftoss/logger/no-native-console */ -import { JsonRpcBatchProvider } from '@ethersproject/providers' import type { Token, Vault } from '@yfi/sdk' import { Yearn } from '@yfi/sdk' +import { ethers } from 'ethers' import fs from 'fs' import toLower from 'lodash/toLower' import uniqBy from 'lodash/uniqBy' @@ -11,7 +11,7 @@ import { toChainId } from '../../chainId/chainId' import { CHAIN_NAMESPACE, CHAIN_REFERENCE } from '../../constants' const network = 1 // 1 for mainnet -const provider = new JsonRpcBatchProvider(process.env.REACT_APP_ETHEREUM_NODE_URL) +const provider = new ethers.providers.JsonRpcBatchProvider(process.env.REACT_APP_ETHEREUM_NODE_URL) const yearnSdk = new Yearn(network, { provider }) export const writeFiles = async (data: Record>) => { diff --git a/packages/investor-foxy/src/api/api.ts b/packages/investor-foxy/src/api/api.ts index 57eaf6d9aa4..8c25b383607 100644 --- a/packages/investor-foxy/src/api/api.ts +++ b/packages/investor-foxy/src/api/api.ts @@ -1,4 +1,3 @@ -import { JsonRpcBatchProvider } from '@ethersproject/providers' import type { ChainReference } from '@shapeshiftoss/caip' import { CHAIN_NAMESPACE, CHAIN_REFERENCE, toAssetId } from '@shapeshiftoss/caip' import type { EvmBaseAdapter, FeeDataEstimate } from '@shapeshiftoss/chain-adapters' @@ -86,9 +85,9 @@ const TOKE_IPFS_URL = 'https://ipfs.tokemaklabs.xyz/ipfs' export class FoxyApi { public adapter: EvmBaseAdapter - public provider: JsonRpcBatchProvider + public provider: ethers.providers.JsonRpcBatchProvider private providerUrl: string - public jsonRpcProvider: JsonRpcBatchProvider + public jsonRpcProvider: ethers.providers.JsonRpcBatchProvider private foxyStakingContracts: ethers.Contract[] private liquidityReserveContracts: ethers.Contract[] private readonly ethereumChainReference: ChainReference @@ -101,8 +100,8 @@ export class FoxyApi { chainReference = CHAIN_REFERENCE.EthereumMainnet, }: ConstructorArgs) { this.adapter = adapter - this.provider = new JsonRpcBatchProvider(providerUrl) - this.jsonRpcProvider = new JsonRpcBatchProvider(providerUrl) + this.provider = new ethers.providers.JsonRpcBatchProvider(providerUrl) + this.jsonRpcProvider = new ethers.providers.JsonRpcBatchProvider(providerUrl) this.foxyStakingContracts = foxyAddresses.map( addresses => new ethers.Contract(addresses.staking, foxyStakingAbi, this.provider), ) diff --git a/packages/investor-yearn/src/YearnInvestor.ts b/packages/investor-yearn/src/YearnInvestor.ts index aef4d438044..f0dc75c1497 100644 --- a/packages/investor-yearn/src/YearnInvestor.ts +++ b/packages/investor-yearn/src/YearnInvestor.ts @@ -1,8 +1,8 @@ -import { JsonRpcBatchProvider } from '@ethersproject/providers' import type { ChainAdapter } from '@shapeshiftoss/chain-adapters' import type { Investor } from '@shapeshiftoss/investor' import type { KnownChainIds } from '@shapeshiftoss/types' import { type ChainId, type VaultMetadata, Yearn } from '@yfi/sdk' +import { ethers } from 'ethers' import { find } from 'lodash' import filter from 'lodash/filter' import Web3 from 'web3' @@ -31,7 +31,7 @@ export class YearnInvestor implements Investor implements SubParser { - provider: JsonRpcBatchProvider + provider: ethers.providers.JsonRpcBatchProvider readonly chainId: ChainId readonly abiInterface = new ethers.utils.Interface(bep20) diff --git a/packages/unchained-client/src/evm/ethereum/parser/uniV2.ts b/packages/unchained-client/src/evm/ethereum/parser/uniV2.ts index 2f2c4a4d3ca..02929d69afb 100644 --- a/packages/unchained-client/src/evm/ethereum/parser/uniV2.ts +++ b/packages/unchained-client/src/evm/ethereum/parser/uniV2.ts @@ -1,4 +1,3 @@ -import type { JsonRpcBatchProvider } from '@ethersproject/providers' import type { ChainId } from '@shapeshiftoss/caip' import { fromChainId, toAssetId } from '@shapeshiftoss/caip' import { ethers } from 'ethers' @@ -24,11 +23,11 @@ export interface TxMetadata extends BaseTxMetadata { export interface ParserArgs { chainId: ChainId - provider: JsonRpcBatchProvider + provider: ethers.providers.JsonRpcBatchProvider } export class Parser implements SubParser { - provider: JsonRpcBatchProvider + provider: ethers.providers.JsonRpcBatchProvider readonly chainId: ChainId readonly wethContract: string readonly abiInterface = new ethers.utils.Interface(UNIV2_ABI) diff --git a/packages/unchained-client/src/evm/ethereum/parser/weth.ts b/packages/unchained-client/src/evm/ethereum/parser/weth.ts index 349fd6adfe6..704cc270d00 100644 --- a/packages/unchained-client/src/evm/ethereum/parser/weth.ts +++ b/packages/unchained-client/src/evm/ethereum/parser/weth.ts @@ -1,4 +1,3 @@ -import type { JsonRpcBatchProvider } from '@ethersproject/providers' import type { ChainId } from '@shapeshiftoss/caip' import { fromChainId, toAssetId } from '@shapeshiftoss/caip' import { ethers } from 'ethers' @@ -17,11 +16,11 @@ export interface TxMetadata extends BaseTxMetadata { export interface ParserArgs { chainId: ChainId - provider: JsonRpcBatchProvider + provider: ethers.providers.JsonRpcBatchProvider } export class Parser implements SubParser { - provider: JsonRpcBatchProvider + provider: ethers.providers.JsonRpcBatchProvider readonly chainId: ChainId readonly wethContract: string readonly abiInterface = new ethers.utils.Interface(WETH_ABI) diff --git a/packages/unchained-client/src/evm/parser/erc20.ts b/packages/unchained-client/src/evm/parser/erc20.ts index f7d298f1d68..51a17cfa4b6 100644 --- a/packages/unchained-client/src/evm/parser/erc20.ts +++ b/packages/unchained-client/src/evm/parser/erc20.ts @@ -1,4 +1,3 @@ -import type { JsonRpcBatchProvider } from '@ethersproject/providers' import type { ChainId } from '@shapeshiftoss/caip' import { toAssetId } from '@shapeshiftoss/caip' import type { BigNumber } from 'ethers' @@ -17,11 +16,11 @@ export interface TxMetadata extends BaseTxMetadata { interface ParserArgs { chainId: ChainId - provider: JsonRpcBatchProvider + provider: ethers.providers.JsonRpcBatchProvider } export class Parser implements SubParser { - provider: JsonRpcBatchProvider + provider: ethers.providers.JsonRpcBatchProvider readonly chainId: ChainId readonly abiInterface = new ethers.utils.Interface(ERC20_ABI) diff --git a/packages/unchained-client/src/evm/parser/index.ts b/packages/unchained-client/src/evm/parser/index.ts index 962245c4d1f..982c8f1e801 100644 --- a/packages/unchained-client/src/evm/parser/index.ts +++ b/packages/unchained-client/src/evm/parser/index.ts @@ -1,4 +1,3 @@ -import { JsonRpcBatchProvider } from '@ethersproject/providers' import type { AssetId, ChainId } from '@shapeshiftoss/caip' import { ASSET_NAMESPACE, ASSET_REFERENCE, ethChainId, toAssetId } from '@shapeshiftoss/caip' import { BigNumber } from 'bignumber.js' @@ -22,13 +21,13 @@ export class BaseTransactionParser { chainId: ChainId assetId: AssetId - protected readonly provider: JsonRpcBatchProvider + protected readonly provider: ethers.providers.JsonRpcBatchProvider private parsers: SubParser[] = [] constructor(args: TransactionParserArgs) { this.chainId = args.chainId this.assetId = args.assetId - this.provider = new JsonRpcBatchProvider(args.rpcUrl) + this.provider = new ethers.providers.JsonRpcBatchProvider(args.rpcUrl) } /** diff --git a/src/plugins/walletConnectToDapps/hooks/useGetAbi.tsx b/src/plugins/walletConnectToDapps/hooks/useGetAbi.tsx index d95d4d152eb..8da4098f4df 100644 --- a/src/plugins/walletConnectToDapps/hooks/useGetAbi.tsx +++ b/src/plugins/walletConnectToDapps/hooks/useGetAbi.tsx @@ -1,4 +1,3 @@ -import { JsonRpcBatchProvider } from '@ethersproject/providers' import { skipToken } from '@reduxjs/toolkit/query' import { getConfig } from 'config' import { ethers } from 'ethers' @@ -15,7 +14,7 @@ export const useGetAbi = ( const { to: contractAddress, data } = transactionParams const provider = useMemo( - () => new JsonRpcBatchProvider(getConfig().REACT_APP_ETHEREUM_NODE_URL), + () => new ethers.providers.JsonRpcBatchProvider(getConfig().REACT_APP_ETHEREUM_NODE_URL), [], ) diff --git a/yarn.lock b/yarn.lock index 8e16cd173cb..81bea864737 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6267,7 +6267,6 @@ __metadata: "@commitlint/config-conventional": ^15.0.0 "@emotion/react": ^11.9.3 "@emotion/styled": ^11.9.3 - "@ethersproject/providers": 5.7.2 "@formatjs/intl-getcanonicallocales": ^2.0.2 "@formatjs/intl-locale": ^3.0.2 "@formatjs/intl-numberformat": ^8.0.2 From 246b77aa195c3b6cb4132356add931c0170407ac Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Mon, 24 Apr 2023 23:44:32 +0200 Subject: [PATCH 25/29] fix: derp --- .../foxy/components/FoxyManager/Withdraw/components/Confirm.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx index b91be0ef513..156d09dde1a 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx @@ -155,7 +155,7 @@ export const Confirm: React.FC onNext(DefiStep.Info)} headerText='modals.confirm.withdraw.header' onConfirm={handleConfirm} - isDisabled={false} + isDisabled={!hasEnoughBalanceForGas} loading={state.loading} loadingText={translate('common.confirm')} > From c883f3a2b8b04166e62a65d131805d75af8bb2fa Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Tue, 25 Apr 2023 11:20:50 +0200 Subject: [PATCH 26/29] feat: use gasUsed from ethers' TransactionReceipt --- .../Deposit/components/Confirm.tsx | 33 +++++++---------- .../Overview/Claim/ClaimStatus.tsx | 13 ++----- .../Withdraw/components/Confirm.tsx | 36 +++++++------------ 3 files changed, 27 insertions(+), 55 deletions(-) diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx index a6e4f2e7ef3..2c68123ea03 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx @@ -1,7 +1,6 @@ import { Alert, AlertIcon, Box, Stack, useToast } from '@chakra-ui/react' import type { AccountId } from '@shapeshiftoss/caip' -import { ethChainId, fromAccountId } from '@shapeshiftoss/caip' -import type { EvmBaseAdapter, EvmChainId } from '@shapeshiftoss/chain-adapters' +import { fromAccountId } from '@shapeshiftoss/caip' import { supportsETH } from '@shapeshiftoss/hdwallet-core' import type { ethers } from 'ethers' import { Confirm as ReusableConfirm } from 'features/defi/components/Confirm/Confirm' @@ -16,7 +15,6 @@ import { AssetIcon } from 'components/AssetIcon' import type { StepComponentProps } from 'components/DeFi/components/Steps' import { Row } from 'components/Row/Row' import { RawText, Text } from 'components/Text' -import { getChainAdapterManager } from 'context/PluginProvider/chainAdapterSingleton' import { useWallet } from 'hooks/useWallet/useWallet' import { bn, bnOrZero } from 'lib/bignumber/bignumber' import { logger } from 'lib/logger' @@ -84,25 +82,20 @@ export const Confirm: React.FC = ({ onNext, accountId }) => { return try { dispatch({ type: FoxyDepositActionType.SET_LOADING, payload: true }) - const chainAdapterManager = getChainAdapterManager() - const adapter = chainAdapterManager.get(ethChainId) as unknown as EvmBaseAdapter if (!supportsETH(walletState.wallet)) throw new Error(`handleDeposit: wallet does not support ethereum`) - const [txid, gasFees] = await Promise.all([ - foxyApi.deposit({ - amountDesired: bnOrZero(state?.deposit.cryptoAmount) - .times(bn(10).pow(asset.precision)) - .decimalPlaces(0), - tokenContractAddress: assetReference, - userAddress: accountAddress, - contractAddress, - wallet: walletState.wallet, - bip44Params, - }), - adapter.getGasFeeData(), - ]) + const txid = await foxyApi.deposit({ + amountDesired: bnOrZero(state?.deposit.cryptoAmount) + .times(bn(10).pow(asset.precision)) + .decimalPlaces(0), + tokenContractAddress: assetReference, + userAddress: accountAddress, + contractAddress, + wallet: walletState.wallet, + bip44Params, + }) dispatch({ type: FoxyDepositActionType.SET_TXID, payload: txid }) onNext(DefiStep.Status) @@ -116,9 +109,7 @@ export const Confirm: React.FC = ({ onNext, accountId }) => { type: FoxyDepositActionType.SET_DEPOSIT, payload: { txStatus: transactionReceipt.status ? 'success' : 'failed', - usedGasFeeCryptoBaseUnit: bnOrZero(gasFees.fast.gasPrice) - .times(transactionReceipt.gasUsed.toString()) - .toFixed(0), + usedGasFeeCryptoBaseUnit: transactionReceipt.gasUsed.toString(), }, }) } catch (error) { diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx index 82922974b5e..29a870fd12f 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx @@ -1,7 +1,6 @@ import { Box, Button, Center, Link, ModalBody, ModalFooter, Stack } from '@chakra-ui/react' import type { AccountId, AssetId, ChainId } from '@shapeshiftoss/caip' -import { ASSET_REFERENCE, ethChainId, toAssetId } from '@shapeshiftoss/caip' -import type { EvmBaseAdapter, EvmChainId } from '@shapeshiftoss/chain-adapters' +import { ASSET_REFERENCE, toAssetId } from '@shapeshiftoss/caip' import type { ethers } from 'ethers' import { DefiProvider, DefiType } from 'features/defi/contexts/DefiManagerProvider/DefiCommon' import isNil from 'lodash/isNil' @@ -17,7 +16,6 @@ import { MiddleEllipsis } from 'components/MiddleEllipsis/MiddleEllipsis' import { Row } from 'components/Row/Row' import { SlideTransition } from 'components/SlideTransition' import { RawText } from 'components/Text' -import { getChainAdapterManager } from 'context/PluginProvider/chainAdapterSingleton' import { useBrowserRouter } from 'hooks/useBrowserRouter/useBrowserRouter' import { bnOrZero } from 'lib/bignumber/bignumber' import { logger } from 'lib/logger' @@ -128,11 +126,6 @@ export const ClaimStatus: React.FC = ({ accountId }) => { maxAttempts: 30, }) - const chainAdapterManager = getChainAdapterManager() - const adapter = chainAdapterManager.get(ethChainId) as unknown as EvmBaseAdapter - - const gasFees = await adapter.getGasFeeData() - if (transactionReceipt.status) { refetchFoxyBalances() } @@ -140,9 +133,7 @@ export const ClaimStatus: React.FC = ({ accountId }) => { setState({ ...state, txStatus: transactionReceipt.status ? TxStatus.SUCCESS : TxStatus.FAILED, - usedGasFee: bnOrZero(gasFees.fast.gasPrice) - .times(transactionReceipt.gasUsed.toString()) - .toFixed(0), + usedGasFee: transactionReceipt.gasUsed.toString(), }) } catch (error) { moduleLogger.error(error, 'ClaimStatus error') diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx index 156d09dde1a..87a9d84d1a8 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Withdraw/components/Confirm.tsx @@ -1,7 +1,6 @@ import { Alert, AlertIcon, Box, Stack } from '@chakra-ui/react' import type { AccountId } from '@shapeshiftoss/caip' -import { ethChainId, fromAccountId } from '@shapeshiftoss/caip' -import type { EvmBaseAdapter, EvmChainId } from '@shapeshiftoss/chain-adapters' +import { fromAccountId } from '@shapeshiftoss/caip' import { supportsETH } from '@shapeshiftoss/hdwallet-core' import { WithdrawType } from '@shapeshiftoss/types' import type { ethers } from 'ethers' @@ -17,7 +16,6 @@ import { AssetIcon } from 'components/AssetIcon' import type { StepComponentProps } from 'components/DeFi/components/Steps' import { Row } from 'components/Row/Row' import { RawText, Text } from 'components/Text' -import { getChainAdapterManager } from 'context/PluginProvider/chainAdapterSingleton' import { useWallet } from 'hooks/useWallet/useWallet' import { bn, bnOrZero } from 'lib/bignumber/bignumber' import { logger } from 'lib/logger' @@ -89,26 +87,20 @@ export const Confirm: React.FC - if (!supportsETH(walletState.wallet)) throw new Error(`handleConfirm: wallet does not support ethereum`) - const [txid, gasFees] = await Promise.all([ - foxyApi.withdraw({ - tokenContractAddress: rewardId, - userAddress: accountAddress, - contractAddress, - wallet: walletState.wallet, - amountDesired: bnOrZero(state.withdraw.cryptoAmount) - .times(bn(10).pow(underlyingAsset.precision)) - .decimalPlaces(0), - type: state.withdraw.withdrawType, - bip44Params, - }), - adapter.getGasFeeData(), - ]) + const txid = await foxyApi.withdraw({ + tokenContractAddress: rewardId, + userAddress: accountAddress, + contractAddress, + wallet: walletState.wallet, + amountDesired: bnOrZero(state.withdraw.cryptoAmount) + .times(bn(10).pow(underlyingAsset.precision)) + .decimalPlaces(0), + type: state.withdraw.withdrawType, + bip44Params, + }) dispatch({ type: FoxyWithdrawActionType.SET_TXID, payload: txid }) onNext(DefiStep.Status) @@ -122,9 +114,7 @@ export const Confirm: React.FC Date: Tue, 25 Apr 2023 19:17:10 +0200 Subject: [PATCH 27/29] fix: use ethers effectiveGasPrice --- .../FoxyManager/Deposit/components/Confirm.tsx | 4 +++- .../FoxyManager/Overview/Claim/ClaimStatus.tsx | 16 +++++++++++----- .../FoxyManager/Withdraw/components/Confirm.tsx | 4 +++- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx index 2c68123ea03..d9b89ad4e2c 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Deposit/components/Confirm.tsx @@ -109,7 +109,9 @@ export const Confirm: React.FC = ({ onNext, accountId }) => { type: FoxyDepositActionType.SET_DEPOSIT, payload: { txStatus: transactionReceipt.status ? 'success' : 'failed', - usedGasFeeCryptoBaseUnit: transactionReceipt.gasUsed.toString(), + usedGasFeeCryptoBaseUnit: transactionReceipt.effectiveGasPrice + .mul(transactionReceipt.gasUsed) + .toString(), }, }) } catch (error) { diff --git a/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx b/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx index 29a870fd12f..9f6c3775d1b 100644 --- a/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx +++ b/src/features/defi/providers/foxy/components/FoxyManager/Overview/Claim/ClaimStatus.tsx @@ -44,7 +44,7 @@ enum TxStatus { type ClaimState = { txStatus: TxStatus - usedGasFee?: string + usedGasFeeCryptoBaseUnit?: string } const StatusInfo = { @@ -133,14 +133,16 @@ export const ClaimStatus: React.FC = ({ accountId }) => { setState({ ...state, txStatus: transactionReceipt.status ? TxStatus.SUCCESS : TxStatus.FAILED, - usedGasFee: transactionReceipt.gasUsed.toString(), + usedGasFeeCryptoBaseUnit: transactionReceipt.effectiveGasPrice + .mul(transactionReceipt.gasUsed) + .toString(), }) } catch (error) { moduleLogger.error(error, 'ClaimStatus error') setState({ ...state, txStatus: TxStatus.FAILED, - usedGasFee: estimatedGas, + usedGasFeeCryptoBaseUnit: estimatedGas, }) } })() @@ -219,7 +221,9 @@ export const ClaimStatus: React.FC = ({ accountId }) => { = ({ accountId }) => { Date: Tue, 25 Apr 2023 19:25:49 +0200 Subject: [PATCH 28/29] feat: consistent naming --- packages/investor-foxy/src/api/api.ts | 56 +++++++++++++-------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/packages/investor-foxy/src/api/api.ts b/packages/investor-foxy/src/api/api.ts index 8c25b383607..3832e294920 100644 --- a/packages/investor-foxy/src/api/api.ts +++ b/packages/investor-foxy/src/api/api.ts @@ -255,7 +255,7 @@ export class FoxyApi { try { const data = stakingContract.interface.encodeFunctionData('claimWithdraw', [addressToClaim]) - const estimatedFees = await this.adapter.getFeeData({ + const feeData = await this.adapter.getFeeData({ to: contractAddress, value: '0', chainSpecific: { @@ -266,11 +266,11 @@ export class FoxyApi { const { chainSpecific: { gasLimit: gasLimitBase }, - } = estimatedFees.fast + } = feeData.fast const safeGasLimit = bnOrZero(gasLimitBase).times('1.05').toFixed(0) - estimatedFees.fast.chainSpecific.gasLimit = safeGasLimit + feeData.fast.chainSpecific.gasLimit = safeGasLimit - return estimatedFees + return feeData } catch (e) { throw new Error(`Failed to get gas ${e}`) } @@ -286,7 +286,7 @@ export class FoxyApi { try { const data = stakingContract.interface.encodeFunctionData('sendWithdrawalRequests', []) - const estimatedFees = await this.adapter.getFeeData({ + const feeData = await this.adapter.getFeeData({ to: contractAddress, value: '0', chainSpecific: { @@ -297,11 +297,11 @@ export class FoxyApi { const { chainSpecific: { gasLimit: gasLimitBase }, - } = estimatedFees.fast + } = feeData.fast const safeGasLimit = bnOrZero(gasLimitBase).times('1.05').toFixed(0) - estimatedFees.fast.chainSpecific.gasLimit = safeGasLimit + feeData.fast.chainSpecific.gasLimit = safeGasLimit - return estimatedFees + return feeData } catch (e) { throw new Error(`Failed to get gas ${e}`) } @@ -320,7 +320,7 @@ export class FoxyApi { const data = liquidityReserveContract.interface.encodeFunctionData('addLiquidity', [ this.normalizeAmount(amountDesired), ]) - const estimatedFees = await this.adapter.getFeeData({ + const feeData = await this.adapter.getFeeData({ to: contractAddress, value: '0', chainSpecific: { @@ -331,11 +331,11 @@ export class FoxyApi { const { chainSpecific: { gasLimit: gasLimitBase }, - } = estimatedFees.fast + } = feeData.fast const safeGasLimit = bnOrZero(gasLimitBase).times('1.05').toFixed(0) - estimatedFees.fast.chainSpecific.gasLimit = safeGasLimit + feeData.fast.chainSpecific.gasLimit = safeGasLimit - return estimatedFees + return feeData } catch (e) { throw new Error(`Failed to get gas ${e}`) } @@ -355,7 +355,7 @@ export class FoxyApi { this.normalizeAmount(amountDesired), ]) - const estimatedFees = await this.adapter.getFeeData({ + const feeData = await this.adapter.getFeeData({ to: contractAddress, value: '0', chainSpecific: { @@ -366,11 +366,11 @@ export class FoxyApi { const { chainSpecific: { gasLimit: gasLimitBase }, - } = estimatedFees.fast + } = feeData.fast const safeGasLimit = bnOrZero(gasLimitBase).times('1.05').toFixed(0) - estimatedFees.fast.chainSpecific.gasLimit = safeGasLimit + feeData.fast.chainSpecific.gasLimit = safeGasLimit - return estimatedFees + return feeData } catch (e) { throw new Error(`Failed to get gas ${e}`) } @@ -395,7 +395,7 @@ export class FoxyApi { ]) : stakingContract.interface.encodeFunctionData('instantUnstake', [true]) - const estimatedFees = await this.adapter.getFeeData({ + const feeData = await this.adapter.getFeeData({ to: contractAddress, value: '0', chainSpecific: { @@ -406,11 +406,11 @@ export class FoxyApi { const { chainSpecific: { gasLimit: gasLimitBase }, - } = estimatedFees.fast + } = feeData.fast const safeGasLimit = bnOrZero(gasLimitBase).times('1.05').toFixed(0) - estimatedFees.fast.chainSpecific.gasLimit = safeGasLimit + feeData.fast.chainSpecific.gasLimit = safeGasLimit - return estimatedFees + return feeData } catch (e) { throw new Error(`Failed to get gas ${e}`) } @@ -429,7 +429,7 @@ export class FoxyApi { contractAddress, MAX_ALLOWANCE, ]) - const estimatedFees = await this.adapter.getFeeData({ + const feeData = await this.adapter.getFeeData({ to: tokenContractAddress, value: '0', chainSpecific: { @@ -440,11 +440,11 @@ export class FoxyApi { const { chainSpecific: { gasLimit: gasLimitBase }, - } = estimatedFees.fast + } = feeData.fast const safeGasLimit = bnOrZero(gasLimitBase).times('1.05').toFixed(0) - estimatedFees.fast.chainSpecific.gasLimit = safeGasLimit + feeData.fast.chainSpecific.gasLimit = safeGasLimit - return estimatedFees + return feeData } catch (e) { throw new Error(`Failed to get gas ${e}`) } @@ -464,7 +464,7 @@ export class FoxyApi { this.normalizeAmount(amountDesired), ]) - const estimatedFees = await this.adapter.getFeeData({ + const feeData = await this.adapter.getFeeData({ to: contractAddress, value: '0', chainSpecific: { @@ -475,11 +475,11 @@ export class FoxyApi { const { chainSpecific: { gasLimit: gasLimitBase }, - } = estimatedFees.fast + } = feeData.fast const safeGasLimit = bnOrZero(gasLimitBase).times('1.05').toFixed(0) - estimatedFees.fast.chainSpecific.gasLimit = safeGasLimit + feeData.fast.chainSpecific.gasLimit = safeGasLimit - return estimatedFees + return feeData } catch (e) { throw new Error(`Failed to get gas ${e}`) } From 61a91a6a77367db06354fdf9d2307a5d07cb75ea Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Tue, 25 Apr 2023 19:32:36 +0200 Subject: [PATCH 29/29] feat: disgusting code, get out --- packages/investor-foxy/src/api/api.ts | 67 +++++---------------------- 1 file changed, 11 insertions(+), 56 deletions(-) diff --git a/packages/investor-foxy/src/api/api.ts b/packages/investor-foxy/src/api/api.ts index 3832e294920..d10fefc058e 100644 --- a/packages/investor-foxy/src/api/api.ts +++ b/packages/investor-foxy/src/api/api.ts @@ -172,13 +172,9 @@ export class FoxyApi { } private verifyAddresses(addresses: string[]) { - try { - addresses.forEach(address => { - this.checksumAddress(address) - }) - } catch (e) { - throw new Error(`Verify Address: ${e}`) - } + addresses.forEach(address => { + this.checksumAddress(address) + }) } private getStakingContract(contractAddress: string): ethers.Contract { @@ -498,12 +494,7 @@ export class FoxyApi { this.verifyAddresses([userAddress, contractAddress, tokenContractAddress]) if (!wallet) throw new Error('Missing inputs') - let estimatedFees: FeeDataEstimate - try { - estimatedFees = await this.estimateApproveFees(input) - } catch (e) { - throw new Error(`Estimate Gas Error: ${e}`) - } + const estimatedFees = await this.estimateApproveFees(input) const depositTokenContract = new ethers.Contract(tokenContractAddress, erc20Abi, this.provider) const data: string = depositTokenContract.interface.encodeFunctionData('approve', [ contractAddress, @@ -532,12 +523,7 @@ export class FoxyApi { this.provider, ) - let allowance - try { - allowance = await depositTokenContract.allowance(userAddress, contractAddress) - } catch (e) { - throw new Error(`Failed to get allowance ${e}`) - } + const allowance = await depositTokenContract.allowance(userAddress, contractAddress) return allowance.toString() } @@ -554,12 +540,7 @@ export class FoxyApi { if (!amountDesired.gt(0)) throw new Error('Must send valid amount') if (!wallet) throw new Error('Missing inputs') - let estimatedFees: FeeDataEstimate - try { - estimatedFees = await this.estimateDepositFees(input) - } catch (e) { - throw new Error(`Estimate Gas Error: ${e}`) - } + const estimatedFees = await this.estimateDepositFees(input) const stakingContract = this.getStakingContract(contractAddress) @@ -593,12 +574,7 @@ export class FoxyApi { this.verifyAddresses([userAddress, contractAddress]) if (!wallet) throw new Error('Missing inputs') - let estimatedFees: FeeDataEstimate - try { - estimatedFees = await this.estimateWithdrawFees(input) - } catch (e) { - throw new Error(`Estimate Gas Error: ${e}`) - } + const estimatedFees = await this.estimateWithdrawFees(input) const stakingContract = this.getStakingContract(contractAddress) @@ -711,12 +687,7 @@ export class FoxyApi { this.verifyAddresses([userAddress, contractAddress, addressToClaim]) if (!wallet) throw new Error('Missing inputs') - let estimatedFees: FeeDataEstimate - try { - estimatedFees = await this.estimateClaimWithdrawFees(input) - } catch (e) { - throw new Error(`Estimate Gas Error: ${e}`) - } + const estimatedFees = await this.estimateClaimWithdrawFees(input) const stakingContract = this.getStakingContract(contractAddress) @@ -820,12 +791,7 @@ export class FoxyApi { this.verifyAddresses([userAddress, contractAddress]) if (!wallet || !contractAddress) throw new Error('Missing inputs') - let estimatedFees: FeeDataEstimate - try { - estimatedFees = await this.estimateSendWithdrawalRequestsFees(input) - } catch (e) { - throw new Error(`Estimate Gas Error: ${e}`) - } + const estimatedFees = await this.estimateSendWithdrawalRequestsFees(input) const stakingContract = this.getStakingContract(contractAddress) @@ -861,13 +827,7 @@ export class FoxyApi { if (!wallet) throw new Error('Missing inputs') - let estimatedFees: FeeDataEstimate - try { - estimatedFees = await this.estimateAddLiquidityFees(input) - } catch (e) { - throw new Error(`Estimate Gas Error: ${e}`) - } - + const estimatedFees = await this.estimateAddLiquidityFees(input) const liquidityReserveContract = this.getLiquidityReserveContract(contractAddress) const data: string = liquidityReserveContract.interface.encodeFunctionData('addLiquidity', [ @@ -901,12 +861,7 @@ export class FoxyApi { if (!amountDesired.gt(0)) throw new Error('Must send valid amount') if (!wallet) throw new Error('Missing inputs') - let estimatedFees: FeeDataEstimate - try { - estimatedFees = await this.estimateRemoveLiquidityFees(input) - } catch (e) { - throw new Error(`Estimate Gas Error: ${e}`) - } + const estimatedFees = await this.estimateRemoveLiquidityFees(input) const liquidityReserveContract = this.getLiquidityReserveContract(contractAddress)