Skip to content

Commit

Permalink
wip: support native ether (#1262)
Browse files Browse the repository at this point in the history
* upgrade proxy kit version

* enable proxy upgrades

* preserve default token ordering

* add ether to funding dropdown

* add upgrade proxy component

* update createMarket method

* remove weth abi

* prevent early proxy upgrade message

* disable create market button if proxy is not deployed or it needs an upgrade

* add proxy upgrade button states

* handle native ether in fetchAccountBalance

* monkey patch cpk to fix transaction encoding

* add useCpkProxy and use RemoteData

* enable native eth funding on existing markets

* make update proxy message user friendly

* update proxy message and lock file

* update cpk to v2.2.0-alpha.1

* enable native ether for buys

* add extra gas for deploy + upgrade proxy

* update lockfile

* add sokol contracts

* return encodeMultiSendCallData and fix some conditionals

* rename to pseudoNativeAssetAddress

* add getWrapToken

* add getTargetSafeImplementation

* remove value amount if safeApp

* replace getToken with getWrapToken

* update useTokens hook

* update gas values for native asset txs

* fix missed conditional

* use transaction v2 for single transaction

* generalise UpgradeProxy and fix disabled buttons

* update mainnet contracts

* moar gas for create tx

* fix approval in addFunding

* update contracts

* update arbitration address

* fix bad merge

* replace UpgradeProxy component

* update contract

* update realitio timeout

* update contracts

* add sokol details

* lowercase WSPOA address

* native xdai

* allowance margins

* update xdai target safe implementation

Co-authored-by: liaojikunwork <[email protected]>
Co-authored-by: Thomas Pulber <[email protected]>
  • Loading branch information
3 people authored Jan 5, 2021
1 parent e9b5ee3 commit 359673d
Show file tree
Hide file tree
Showing 18 changed files with 535 additions and 100 deletions.
2 changes: 2 additions & 0 deletions app/src/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ export const GRAPH_RINKEBY_HTTP = 'https://api.thegraph.com/subgraphs/name/proto
export const GRAPH_RINKEBY_WS = 'wss://api.thegraph.com/subgraphs/name/protofire/omen-rinkeby'
export const GRAPH_SOKOL_HTTP = 'https://api.thegraph.com/subgraphs/name/protofire/omen-sokol'
export const GRAPH_SOKOL_WS = 'wss://api.thegraph.com/subgraphs/name/protofire/omen-sokol'
export const GRAPH_XDAI_HTTP = 'https://api.thegraph.com/subgraphs/name/protofire/omen-xdai'
export const GRAPH_XDAI_WS = 'wss://api.thegraph.com/subgraphs/name/protofire/omen-xdai'

export const KLEROS_CURATE_GRAPH_MAINNET_HTTP = 'https://api.thegraph.com/subgraphs/name/kleros/curate'
export const KLEROS_CURATE_GRAPH_MAINNET_WS = 'wss://api.thegraph.com/subgraphs/name/kleros/curate'
Expand Down
5 changes: 3 additions & 2 deletions app/src/components/market/common/currency_selector/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,13 @@ interface Props {
balance?: string
placeholder?: Maybe<string>
addAll?: boolean
addNativeAsset?: boolean
}

export const CurrencySelector: React.FC<Props> = props => {
const {
addAll = false,
addNativeAsset = false,
balance,
context,
currency,
Expand All @@ -50,7 +52,7 @@ export const CurrencySelector: React.FC<Props> = props => {
...restProps
} = props

const tokens = useTokens(context)
const tokens = useTokens(context, addNativeAsset)

const currencyDropdownData: Array<DropdownItemProps> = []

Expand All @@ -73,7 +75,6 @@ export const CurrencySelector: React.FC<Props> = props => {
}
},
})

currentItem = 0
}

Expand Down
8 changes: 7 additions & 1 deletion app/src/components/market/common/outcome_table/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import { BigNumber } from 'ethers/utils'
import React, { useCallback } from 'react'
import styled, { css } from 'styled-components'

import { useConnectedWeb3Context } from '../../../../hooks'
import { getOutcomeColor } from '../../../../theme/utils'
import { getWrapToken, pseudoNativeAssetAddress } from '../../../../util/networks'
import { formatBigNumber, formatNumber, mulBN } from '../../../../util/tools'
import { BalanceItem, BondItem, OutcomeTableValue, Token, TokenEthereum } from '../../../../util/types'
import { RadioInput, TD, TH, THead, TR, Table } from '../../../common'
Expand Down Expand Up @@ -125,6 +127,10 @@ export const OutcomeTable = (props: Props) => {

const TableCellsAlign = ['left', 'left', 'right', 'right', 'right', 'right', 'right']

const context = useConnectedWeb3Context()
const wrapSymbol = getWrapToken(context.networkId).symbol
const symbol = collateral.address === pseudoNativeAssetAddress ? wrapSymbol : collateral.symbol

const renderTableHeader = () => {
return (
<THead>
Expand All @@ -137,7 +143,7 @@ export const OutcomeTable = (props: Props) => {
style={isBond && index === 1 ? { width: '53%' } : {}}
textAlign={TableCellsAlign[index]}
>
{value} {value === OutcomeTableValue.CurrentPrice && `(${collateral.symbol})`}
{value} {value === OutcomeTableValue.CurrentPrice && `(${symbol})`}
</THStyled>
) : null
})}
Expand Down
48 changes: 44 additions & 4 deletions app/src/components/market/sections/market_buy/market_buy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ import {
useConnectedWeb3Context,
useContracts,
useCpkAllowance,
useCpkProxy,
} from '../../../../hooks'
import { MarketMakerService } from '../../../../services'
import { getLogger } from '../../../../util/logger'
import { getNativeAsset, getWrapToken, pseudoNativeAssetAddress } from '../../../../util/networks'
import { RemoteData } from '../../../../util/remote_data'
import { computeBalanceAfterTrade, formatBigNumber, formatNumber, mulBN } from '../../../../util/tools'
import { MarketDetailsTab, MarketMakerData, OutcomeTableValue, Status, Ternary, Token } from '../../../../util/types'
Expand Down Expand Up @@ -60,7 +62,7 @@ interface Props extends RouteComponentProps<any> {
const MarketBuyWrapper: React.FC<Props> = (props: Props) => {
const context = useConnectedWeb3Context()
const cpk = useConnectedCPKContext()
const { library: provider } = context
const { library: provider, networkId } = context
const signer = useMemo(() => provider.getSigner(), [provider])

const { buildMarketMaker } = useContracts(context)
Expand All @@ -85,6 +87,10 @@ const MarketBuyWrapper: React.FC<Props> = (props: Props) => {
const hasEnoughAllowance = RemoteData.mapToTernary(allowance, allowance => allowance.gte(amount || Zero))
const hasZeroAllowance = RemoteData.mapToTernary(allowance, allowance => allowance.isZero())

const [upgradeFinished, setUpgradeFinished] = useState(false)
const { proxyIsUpToDate, updateProxy } = useCpkProxy()
const isUpdated = RemoteData.hasData(proxyIsUpToDate) ? proxyIsUpToDate.data : false

useEffect(() => {
setIsNegativeAmount(formatBigNumber(amount || Zero, collateral.decimals).includes('-'))
}, [amount, collateral.decimals])
Expand Down Expand Up @@ -145,6 +151,19 @@ const MarketBuyWrapper: React.FC<Props> = (props: Props) => {
setAllowanceFinished(true)
}

const showUpgrade =
(!isUpdated && collateral.address === pseudoNativeAssetAddress) ||
(upgradeFinished && collateral.address === pseudoNativeAssetAddress)

const upgradeProxy = async () => {
if (!cpk) {
return
}

await updateProxy()
setUpgradeFinished(true)
}

const finish = async () => {
try {
if (!cpk) {
Expand All @@ -158,6 +177,7 @@ const MarketBuyWrapper: React.FC<Props> = (props: Props) => {

await cpk.buyOutcomes({
amount: amount || Zero,
collateral,
outcomeIndex,
marketMaker,
})
Expand Down Expand Up @@ -185,6 +205,7 @@ const MarketBuyWrapper: React.FC<Props> = (props: Props) => {
}

const showSetAllowance =
collateral.address !== pseudoNativeAssetAddress &&
!cpk?.cpk.isSafeApp() &&
(allowanceFinished || hasZeroAllowance === Ternary.True || hasEnoughAllowance === Ternary.False)

Expand Down Expand Up @@ -218,14 +239,23 @@ const MarketBuyWrapper: React.FC<Props> = (props: Props) => {
!amount ||
(status !== Status.Ready && status !== Status.Error) ||
amount?.isZero() ||
(!cpk?.cpk.isSafeApp() && hasEnoughAllowance !== Ternary.True) ||
(!cpk?.cpk.isSafeApp() && collateral.address !== pseudoNativeAssetAddress && hasEnoughAllowance !== Ternary.True) ||
amountError !== null ||
isNegativeAmount
isNegativeAmount ||
(!isUpdated && collateral.address === pseudoNativeAssetAddress)

const wrapAddress = getWrapToken(networkId).address

const currencyFilters =
collateral.address === wrapAddress || collateral.address === pseudoNativeAssetAddress
? [wrapAddress, pseudoNativeAssetAddress.toLowerCase()]
: []

const switchOutcome = (value: number) => {
setNewShares(balances.map((balance, i) => (i === outcomeIndex ? balance.shares.add(tradedShares) : balance.shares)))
setOutcomeIndex(value)
}

return (
<>
<OutcomeTable
Expand Down Expand Up @@ -256,10 +286,12 @@ const MarketBuyWrapper: React.FC<Props> = (props: Props) => {
<div>
<CurrenciesWrapper>
<CurrencySelector
addNativeAsset
balance={formatBigNumber(maybeCollateralBalance || Zero, collateral.decimals, 5)}
context={context}
currency={collateral.address}
disabled
disabled={currencyFilters.length ? false : true}
filters={currencyFilters}
onSelect={(token: Token | null) => {
if (token) {
setCollateral(token)
Expand Down Expand Up @@ -335,6 +367,14 @@ const MarketBuyWrapper: React.FC<Props> = (props: Props) => {
onUnlock={unlockCollateral}
/>
)}
{showUpgrade && (
<SetAllowance
collateral={getNativeAsset(context.networkId)}
finished={upgradeFinished && RemoteData.is.success(proxyIsUpToDate)}
loading={RemoteData.is.asking(proxyIsUpToDate)}
onUnlock={upgradeProxy}
/>
)}
<StyledButtonContainer borderTop={true} marginTop={showSetAllowance || isNegativeAmount}>
<Button buttonType={ButtonType.secondaryLine} onClick={() => switchMarketTab(MarketDetailsTab.swap)}>
Cancel
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { useConnectedWeb3Context } from '../../../../hooks/connectedWeb3'
import { ERC20Service } from '../../../../services'
import { getLogger } from '../../../../util/logger'
import { MarketCreationStatus } from '../../../../util/market_creation_status_data'
import { pseudoNativeAssetAddress } from '../../../../util/networks'
import { MarketData } from '../../../../util/types'
import { ModalConnectWallet } from '../../../modal'

Expand Down Expand Up @@ -40,7 +41,7 @@ const MarketWizardCreatorContainer: FC = () => {

setMarketCreationStatus(MarketCreationStatus.creatingAMarket())

if (!cpk.cpk.isSafeApp()) {
if (!cpk.cpk.isSafeApp() && marketData.collateral.address !== pseudoNativeAssetAddress) {
// Approve collateral to the proxy contract
const collateralService = new ERC20Service(provider, account, marketData.collateral.address)
const hasEnoughAlowance = await collateralService.hasEnoughAllowance(account, cpk.address, marketData.funding)
Expand All @@ -49,6 +50,7 @@ const MarketWizardCreatorContainer: FC = () => {
await collateralService.approveUnlimited(cpk.address)
}
}

const { marketMakerAddress, transaction } = await cpk.createMarket({
marketData,
conditionalTokens,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@ import {
useConnectedCPKContext,
useConnectedWeb3Context,
useCpkAllowance,
useCpkProxy,
} from '../../../../../../hooks'
import { useGraphMarketsFromQuestion } from '../../../../../../hooks/useGraphMarketsFromQuestion'
import { BalanceState, fetchAccountBalance } from '../../../../../../store/reducer'
import { MarketCreationStatus } from '../../../../../../util/market_creation_status_data'
import { getNativeAsset, pseudoNativeAssetAddress } from '../../../../../../util/networks'
import { RemoteData } from '../../../../../../util/remote_data'
import { formatBigNumber, formatDate, formatNumber } from '../../../../../../util/tools'
import { Arbitrator, Ternary, Token } from '../../../../../../util/types'
Expand Down Expand Up @@ -224,10 +226,13 @@ const FundingAndFeeStep: React.FC<Props> = (props: Props) => {

const [amount, setAmount] = useState<BigNumber>(funding)
const [amountToDispaly, setAmountToDisplay] = useState<string>('')

const hasEnoughAllowance = RemoteData.mapToTernary(allowance, allowance => allowance.gte(funding))
const hasZeroAllowance = RemoteData.mapToTernary(allowance, allowance => allowance.isZero())

const [upgradeFinished, setUpgradeFinished] = useState(false)
const { proxyIsUpToDate, updateProxy } = useCpkProxy()
const isUpdated = RemoteData.hasData(proxyIsUpToDate) ? proxyIsUpToDate.data : false

useEffect(() => {
dispatch(fetchAccountBalance(account, provider, collateral))
}, [dispatch, account, provider, collateral])
Expand Down Expand Up @@ -273,12 +278,27 @@ const FundingAndFeeStep: React.FC<Props> = (props: Props) => {
!account ||
amountError !== null ||
exceedsMaxFee ||
isNegativeDepositAmount
isNegativeDepositAmount ||
(!isUpdated && collateral.address === pseudoNativeAssetAddress)

const showSetAllowance =
collateral.address !== pseudoNativeAssetAddress &&
!cpk?.cpk.isSafeApp() &&
(allowanceFinished || hasZeroAllowance === Ternary.True || hasEnoughAllowance === Ternary.False)

const showUpgrade =
(!isUpdated && collateral.address === pseudoNativeAssetAddress) ||
(upgradeFinished && collateral.address === pseudoNativeAssetAddress)

const upgradeProxy = async () => {
if (!cpk) {
return
}

await updateProxy()
setUpgradeFinished(true)
}

const unlockCollateral = async () => {
if (!cpk) {
return
Expand Down Expand Up @@ -386,6 +406,7 @@ const FundingAndFeeStep: React.FC<Props> = (props: Props) => {
<div>
<CurrenciesWrapper>
<CurrencySelector
addNativeAsset
balance={formatNumber(collateralBalanceFormatted, 5)}
context={context}
currency={collateral.address}
Expand Down Expand Up @@ -460,6 +481,15 @@ const FundingAndFeeStep: React.FC<Props> = (props: Props) => {
style={{ marginBottom: 20 }}
/>
)}
{showUpgrade && (
<SetAllowance
collateral={getNativeAsset(context.networkId)}
finished={upgradeFinished && RemoteData.is.success(proxyIsUpToDate)}
loading={RemoteData.is.asking(proxyIsUpToDate)}
onUnlock={upgradeProxy}
style={{ marginBottom: 20 }}
/>
)}
<WarningMessage
additionalDescription={''}
description={
Expand Down
Loading

0 comments on commit 359673d

Please sign in to comment.