Skip to content
This repository has been archived by the owner on Jun 24, 2022. It is now read-only.

Commit

Permalink
Updated gas estimation for gchain (#2391)
Browse files Browse the repository at this point in the history
* Using hardcoded gas values for gchain

* Using Blockscout's gas oracle on gchain instead of hardcoded values

* Adding 20% extra margin for gas estimation

* Sorting the imports a little bit

Co-authored-by: Leandro <[email protected]>
  • Loading branch information
alfetopito and Leandro authored Feb 7, 2022
1 parent 6763fc2 commit af1a7c6
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 16 deletions.
39 changes: 31 additions & 8 deletions src/custom/api/gnosisProtocol/api.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
import { SupportedChainId as ChainId, SupportedChainId } from 'constants/chains'
import { OrderKind, QuoteQuery } from '@gnosis.pm/gp-v2-contracts'
import { stringify } from 'qs'
import { getSigningSchemeApiValue, OrderCreation, OrderCancellation, SigningSchemeValue } from 'utils/signatures'
import { APP_DATA_HASH } from 'constants/index'
import { getSigningSchemeApiValue, OrderCancellation, OrderCreation, SigningSchemeValue } from 'utils/signatures'
import { APP_DATA_HASH, GAS_FEE_ENDPOINTS } from 'constants/index'
import { registerOnWindow } from 'utils/misc'
import { isLocal, isDev, isPr, isBarn } from '../../utils/environments'
import { isBarn, isDev, isLocal, isPr } from '../../utils/environments'
import OperatorError, {
ApiErrorCodeDetails,
ApiErrorCodes,
ApiErrorObject,
} from 'api/gnosisProtocol/errors/OperatorError'
import QuoteError, {
GpQuoteErrorCodes,
GpQuoteErrorDetails,
GpQuoteErrorObject,
mapOperatorErrorToQuoteError,
GpQuoteErrorDetails,
} from 'api/gnosisProtocol/errors/QuoteError'
import { toErc20Address } from 'utils/tokens'
import { FeeQuoteParams, PriceInformation, PriceQuoteParams, SimpleGetQuoteResponse } from 'utils/price'

import { DEFAULT_NETWORK_FOR_LISTS } from 'constants/lists'
import { GAS_FEE_ENDPOINTS } from 'constants/index'
import * as Sentry from '@sentry/browser'
import { ZERO_ADDRESS } from 'constants/misc'
import { getAppDataHash } from 'constants/appDataHash'
Expand Down Expand Up @@ -472,18 +471,42 @@ export async function getPriceStrategy(chainId: ChainId): Promise<PriceStrategy>
}
}

// Reference https://www.xdaichain.com/for-developers/developer-resources/gas-price-oracle
export interface GChainFeeEndpointResponse {
average: number
fast: number
slow: number
}
// Values are returned as floats in gwei
const ONE_GWEI = 1_000_000_000

export interface GasFeeEndpointResponse {
lastUpdate: string
lowest: string
safeLow: string
safeLow?: string
standard: string
fast: string
fastest: string
fastest?: string
}

export async function getGasPrices(chainId: ChainId = DEFAULT_NETWORK_FOR_LISTS): Promise<GasFeeEndpointResponse> {
const response = await fetch(GAS_FEE_ENDPOINTS[chainId])
return response.json()
const json = await response.json()

if (chainId === SupportedChainId.XDAI) {
// Different endpoint for GChain with a different format. Need to transform it
return _transformGChainGasPrices(json)
}
return json
}

function _transformGChainGasPrices({ slow, average, fast }: GChainFeeEndpointResponse): GasFeeEndpointResponse {
return {
lastUpdate: new Date().toISOString(),
lowest: Math.floor(slow * ONE_GWEI).toString(),
standard: Math.floor(average * ONE_GWEI).toString(),
fast: Math.floor(fast * ONE_GWEI).toString(),
}
}

// Register some globals for convenience
Expand Down
3 changes: 1 addition & 2 deletions src/custom/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,7 @@ export const GAS_FEE_ENDPOINTS = {
// [ChainId.GOERLI]: 'https://safe-relay.goerli.gnosis.io/api/v1/gas-station/',
// no kovan = main
// [ChainId.KOVAN]: 'https://safe-relay.kovan.gnosis.io/api/v1/gas-station/',
// TODO: xdai? = main
[ChainId.XDAI]: 'https://safe-relay.gnosis.io/api/v1/gas-station/',
[ChainId.XDAI]: 'https://blockscout.com/xdai/mainnet/api/v1/gas-price-oracle',
}

export const UNSUPPORTED_TOKENS_FAQ_URL = '/faq#what-token-pairs-does-cowswap-allow-to-trade'
Expand Down
16 changes: 10 additions & 6 deletions src/custom/pages/Claim/InvestmentFlow/InvestOption.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useCallback, useMemo, useState, useEffect } from 'react'
import { CurrencyAmount, Percent } from '@uniswap/sdk-core'
import { BigNumber } from '@ethersproject/bignumber'
import SVG from 'react-inlinesvg'

import CowProtocolLogo from 'components/CowProtocolLogo'
import {
Expand All @@ -14,9 +15,10 @@ import {
WarningWrapper,
} from '../styled'
import { formatMax, formatSmartLocaleAware } from 'utils/format'
import { calculateGasMargin } from 'utils/calculateGasMargin'
import Row from 'components/Row'
import CheckCircle from 'assets/cow-swap/check.svg'
import { InvestmentFlowProps } from '.'
import ImportantIcon from 'assets/cow-swap/important.svg'
import { ApprovalState, useApproveCallbackFromClaim } from 'hooks/useApproveCallback'
import { useCurrencyBalance } from 'state/wallet/hooks'
import { useActiveWeb3React } from 'hooks/web3'
Expand All @@ -36,8 +38,7 @@ import { EnhancedUserClaimData } from '../types'
import { OperationType } from 'components/TransactionConfirmationModal'
import { ONE_HUNDRED_PERCENT } from 'constants/misc'
import { IS_TESTING_ENV } from '../const'
import ImportantIcon from 'assets/cow-swap/important.svg'
import SVG from 'react-inlinesvg'
import { InvestmentFlowProps } from '.'

const ErrorMessages = {
NoBalance: (symbol = '') =>
Expand Down Expand Up @@ -129,17 +130,20 @@ export default function InvestOption({ claim, optionIndex, openModal, closeModal
}

const gasCost = useMemo(() => {
if (!estimatedGas || !isNative) {
if (!estimatedGas || !isNative || !chainId) {
return
}

// Based on how much gas will be used (estimatedGas) and current gas prices (if available)
// calculate how much that would cost in native currency.
// We pick `fast` to be conservative. Also, it's non-blocking, so the user is aware but can proceed
const amount = BigNumber.from(estimatedGas).mul(gasPrice?.fast || AVG_APPROVE_COST_GWEI)
const amount = calculateGasMargin(
chainId,
BigNumber.from(estimatedGas).mul(gasPrice?.fast || AVG_APPROVE_COST_GWEI)
)

return CurrencyAmount.fromRawAmount(token, amount.toString())
}, [estimatedGas, gasPrice?.fast, isNative, token])
}, [chainId, estimatedGas, gasPrice?.fast, isNative, token])

// on invest max amount click handler
const setMaxAmount = useCallback(() => {
Expand Down

0 comments on commit af1a7c6

Please sign in to comment.