Compare commits

...

7 Commits

Author SHA1 Message Date
Ian Lapham
a70aa41df2 Routing updates only (#1265)
* start routing fix for multi hops

* switch to input amount comparison on exactOut

* make percent logic more clear

* remove uneeded comaprisons

* move logic to functions for testing

* add multi hop disable switch

* add GA

* fix bug to return multihop no single

* update swap details

* code clean

* routing only
2021-01-12 17:36:57 -05:00
Ian Lapham
587b659816 catch error in bytes32 string parsing (#1253) 2020-12-30 11:50:40 -05:00
Ian Lapham
5388cab779 update vote timestamp estimation (#1242) 2020-12-21 14:49:58 -05:00
Georgios Konstantopoulos
cadd68fb37 feat: allow overriding proposals in the UI (#1239)
* feat: allow overriding proposals in the UI

* Fix code style issues with ESLint

Co-authored-by: Lint Action <lint-action@samuelmeuli.com>
2020-12-18 10:12:22 -05:00
Moody Salem
ab8ce37ceb fix(token lists): update to latest token-lists 2020-12-10 16:18:18 -06:00
Moody Salem
5a9a71ae2d improvement(analytics): try out cloudflare analytics 2020-12-10 10:10:50 -06:00
Noah Zinsmeister
b93fd230bd Specially Designated Nationals and Blocked Persons Ethereum addresses 2020-12-08 16:11:42 -05:00
19 changed files with 323 additions and 72 deletions

View File

@@ -31,7 +31,7 @@
"@uniswap/liquidity-staker": "^1.0.2",
"@uniswap/merkle-distributor": "1.0.1",
"@uniswap/sdk": "3.0.3",
"@uniswap/token-lists": "^1.0.0-beta.18",
"@uniswap/token-lists": "^1.0.0-beta.19",
"@uniswap/v2-core": "1.0.0",
"@uniswap/v2-periphery": "^1.1.0-beta.0",
"@web3-react/core": "^6.0.9",

View File

@@ -39,5 +39,6 @@
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "a141524a42594f028627f6004b23ff75"}'></script>
</body>
</html>

View File

@@ -0,0 +1,12 @@
import React, { ReactNode, useMemo } from 'react'
import { BLOCKED_ADDRESSES } from '../../constants'
import { useActiveWeb3React } from '../../hooks'
export default function Blocklist({ children }: { children: ReactNode }) {
const { account } = useActiveWeb3React()
const blocked: boolean = useMemo(() => Boolean(account && BLOCKED_ADDRESSES.indexOf(account) !== -1), [account])
if (blocked) {
return <div>Blocked address</div>
}
return <>{children}</>
}

View File

@@ -9,7 +9,8 @@ import {
useDarkModeManager,
useExpertModeManager,
useUserTransactionTTL,
useUserSlippageTolerance
useUserSlippageTolerance,
useUserSingleHopOnly
} from '../../state/user/hooks'
import { TYPE } from '../../theme'
import { ButtonError } from '../Button'
@@ -135,6 +136,8 @@ export default function SettingsTab() {
const [expertMode, toggleExpertMode] = useExpertModeManager()
const [singleHopOnly, setSingleHopOnly] = useUserSingleHopOnly()
const [darkMode, toggleDarkMode] = useDarkModeManager()
// show confirmation view before turning on
@@ -230,6 +233,19 @@ export default function SettingsTab() {
}
/>
</RowBetween>
<RowBetween>
<RowFixed>
<TYPE.black fontWeight={400} fontSize={14} color={theme.text2}>
Disable Multihops
</TYPE.black>
<QuestionHelper text="Restricts swaps to direct pairs only." />
</RowFixed>
<Toggle
id="toggle-disable-multihop-button"
isActive={singleHopOnly}
toggle={() => (singleHopOnly ? setSingleHopOnly(false) : setSingleHopOnly(true))}
/>
</RowBetween>
<RowBetween>
<RowFixed>
<TYPE.black fontWeight={400} fontSize={14} color={theme.text2}>

View File

@@ -7,6 +7,8 @@ export const ROUTER_ADDRESS = '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D'
export const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'
export { PRELOADED_PROPOSALS } from './proposals'
// a list of tokens by chain
type ChainTokenList = {
readonly [chainId in ChainId]: Token[]
@@ -21,7 +23,7 @@ export const AMPL = new Token(ChainId.MAINNET, '0xD46bA6D942050d489DBd938a2C909A
export const WBTC = new Token(ChainId.MAINNET, '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599', 8, 'WBTC', 'Wrapped BTC')
// Block time here is slightly higher (~1s) than average in order to avoid ongoing proposals past the displayed time
export const AVERAGE_BLOCK_TIME_IN_SECS = 14
export const AVERAGE_BLOCK_TIME_IN_SECS = 13
export const PROPOSAL_LENGTH_IN_BLOCKS = 40_320
export const PROPOSAL_LENGTH_IN_SECS = AVERAGE_BLOCK_TIME_IN_SECS * PROPOSAL_LENGTH_IN_BLOCKS
@@ -199,3 +201,12 @@ export const BLOCKED_PRICE_IMPACT_NON_EXPERT: Percent = new Percent(JSBI.BigInt(
// used to ensure the user doesn't send so much ETH so they end up with <.01
export const MIN_ETH: JSBI = JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(16)) // .01 ETH
export const BETTER_TRADE_LINK_THRESHOLD = new Percent(JSBI.BigInt(75), JSBI.BigInt(10000))
export const BETTER_TRADE_LESS_HOPS_THRESHOLD = new Percent(JSBI.BigInt(50), JSBI.BigInt(10000))
// SDN OFAC addresses
export const BLOCKED_ADDRESSES: string[] = [
'0x7F367cC41522cE07553e823bf3be79A889DEbe1B',
'0xd882cFc20F52f2599D84b8e8D58C7FB62cfE344b',
'0x901bb9583b24D97e995513C6778dc6888AB6870e',
'0xA7e5d5A720f06526557c513402f2e6B5fA20b008'
]

View File

@@ -0,0 +1,4 @@
import { UNISWAP_GRANTS } from './uniswap_grants'
// Proposals are 0-indexed
export const PRELOADED_PROPOSALS = new Map([[2, UNISWAP_GRANTS]])

View File

@@ -0,0 +1,106 @@
export const UNISWAP_GRANTS = `# Uniswap Grants Program v0.1
*co-authored with [Ken Ng](https://twitter.com/nkennethk?lang=en)*
## Summary:
**This post outlines a framework for funding Uniswap ecosystem development with grants from the[ UNI Community Treasury](https://uniswap.org/blog/uni/).** The program starts small—sponsoring hackathons, [for example](https://gov.uniswap.org/c/proposal-discussion/5)—but could grow in significance over time (with renewals approved by governance) to fund core protocol development. Grants administration is a subjective process that cannot be easily automated, and thus we propose a nimble committee of 6 members —1 lead and 5 reviewers—to deliver an efficient, predictable process to applicants, such that funding can be administered without having to put each application to a vote. We propose the program start with an initial cap of $750K per quarter and a limit of 2 quarters before renewal—a sum that we feel is appropriate for an MVP relative to the size of the treasury that UNI token holders are entrusted with allocating.
**Purpose:**
**The mission of the UGP is to provide valuable resources to help grow the Uniswap ecosystem.** Through public discourse and inbound applications, the community will get first-hand exposure to identify and respond to the most pressing needs of the ecosystem, as well as the ability to support innovative projects expanding the capabilities of Uniswap. By rewarding talent early with developer incentives, bounties, and infrastructure support, UGP acts as a catalyst for growth and helps to maintain Uniswap as a nexus for DeFi on Ethereum.
**Quarterly Budget:**
* Max quarterly budget of up to $750k
* Budget and caps to be assessed every six months
**Grant Allocation Committee:**
* Of 6 committee members: 1 lead and 5 reviewers
* Each committee has a term of 2 quarters (6 months) after which the program needs to be renewed by UNI governance
* Committee functions as a 4 of 5 multi-sig
**Committee Members**
While the goals and priorities of the grant program will be thoroughly discussed and reviewed by the community through public discourse, **the decision to start UGP by operating as a small committee is to ensure that the application and decision process will be efficient and predictable, so applicants have clear objectives and timely decisions.**
Starting with just six members enables the committee to efficiently fund projects with tight feedback loops and rapid iterations. The purpose of this committee would be to test the hypothesis that the Grants Program can successfully provide value for the UNI ecosystem before scaling the program.
**We suggest the grants program is administered by a single lead. Here we propose Kenneth Ng, a co-author of this post**. Ken has helped grow the Ethereum Foundation Grants Program over the last two years in establishing high level priorities and adapting for the ecosystems needs.
**The other 5 committee members should be thought of as “reviewers” — UNI community members who will keep the grants program functional by ensuring Ken is leading effectively and, of course, not absconding with funds.** Part of the reviewers job is to hold the program accountable for success (defined below) and/or return any excess funds to the UNI treasury. Reviewers are not compensated as part of this proposal as we expect their time commitment to be minimal. Compensation for the lead role is discussed below, as we expect this to be a labor intensive role.
**Program Lead:** [Ken Ng](https://twitter.com/nkennethk?lang=en) (HL Creative Corp)
*Ecosystem Support Program at the Ethereum Foundation*
1. Reviewer: [Jesse Walden](https://twitter.com/jessewldn) (o/b/o Unofficial LLC dba [Variant Fund](http://twitter.com/variantfund))
*Founder and Investor at Variant Fund (holds UNI)*
2. Reviewer: [Monet Supply](https://twitter.com/MonetSupply)
*Risk Analyst at MakerDAO*
3. Reviewer: [Robert Leshner](https://twitter.com/rleshner)
*Founder and CEO of Compound Finance*
4. Reviewer: [Kain Warwick](https://twitter.com/kaiynne)
*Founder of Synthetix*
5. Reviewer: [Ashleigh Schap](https://twitter.com/ashleighschap)
*Growth Lead, Uniswap (Company)*
## Methodology
**1.1 Budget**
This proposal recommends a max cap of $750K per quarter, with the ability to reevaluate biannually at each epoch (two fiscal quarters). While the UGP Grants Committee will be the decision makers around individual grants, respective budgets, roadmaps, and milestones, any top-level changes to UGP including epochs and max cap, will require full community quorum (4% approval).
The UGP will be funded by the UNI treasury according to the[ release schedule](https://uniswap.org/blog/uni/) set out by the Uniswap team, whereby 43% of the UNI treasury is released over a four-year timeline. In Year 1 this will total to 172,000,000 UNI (~$344M as of writing).
Taking into consideration the current landscape of ecosystem funding across Ethereum, the community would be hard-pressed to allocate even 5% of Year 1s treasury. For context Gitcoin CLR Round 7 distributed $725k ($450k in matched) across 857 projects and YTD, Moloch has granted just under $200k but in contrast, the EF has committed to somewhere in the 8 figure range.
**1.2 Committee Compensation**
Operating a successful grants program takes considerable time and effort. Take, for instance, the EF Ecosystem Support Program, which has awarded grants since 2018, consists of an internal team at the Foundation as well as an ever increasing roster of community advisors in order to keep expanding and adapting to best serve the needs of the Ethereum ecosystem. While the structure of the allocation committee has six members, we propose that only the lead will be remunerated for their work in establishing the initial processes, vetting applications, and managing the program overall as this role is expected to be time consuming if the program is to be succesful. We propose that the other committee members be unpaid UNI ecosystem stakeholders who have an interest in seeing the protocol ecosystem continue to operate and grow.
**We propose the lead be compensated 25 UNI/hr (approximately $100 USD at time of this writing) capped at 30 hours/week. This compensation, along with the quarterly budget, will be allocated to the UGP multisig from the UNI treasury**. In keeping with the committees commitment to the community, hours and duties will be logged publicly and transparently .
**2.1 Priorities**
Initially, the program aims to start narrow in scope, funding peripheral ecosystem initiatives, such as targeted bounties, hackathon sponsorships, and other low-stakes means of building out the Uniswap developer ecosystem. Over time, if the program proves effective, the grant allocations can grow in scope to include, for example, improved frontends, trading interfaces, and eventually, core protocol development.
![|624x199](upload://vNP0APCOjiwQMurCmYI47cTLklc.png)
With the initial priorities in mind, some effective measures for quick successes might look like:
* Total number of projects funded
* Quarterly increase in applications
* Project engagement post-event/funding
* Overall community engagement/sentiment
**2.2 Timeline**
In keeping with the fast pace of the UNI ecosystem, we organize time in epochs, or two calendar quarters. Each epoch will see two funding rounds, one per quarter, after which the community can review and create proposals to improve or revamp the program as they deem fit.
**![|624x245](upload://n56TSh5X3mt4TSqVVMFhbnZM0eM.png)**
**Rolling Wave 1 & 2 Applications**
* Starting in Q1 2021, UGP will start accepting applications for events looking for support in the form of bounties or prizes that in parallel can be proactively sourced. During these first two waves of funding projects, the allocation committee lead can begin laying out guardrails for continued funding
* Considering the immediate feedback loops for the first epoch, we expect these allocation decisions to be discussed and reviewed by the larger community. Should this not be of value, the community can submit a formal governance proposal to change any piece of UGP that was not effective
**Wave 3 & Beyond**
* Beginning with Wave 3, there should have been enough time with impactful projects funded to be considered for follow-on funding, should it make sense. In the same vein, projects within scope will be expanded to also include those working on integrations and and other key components.
* Beyond the second epoch, as the community helps to review and help adapt UGP to be most effective, the scope will continue to grow in order to accommodate the state of the ecosystem including that of core protocol improvements
## Conclusion:
**If this proposal is successfully approved, UGP will start accepting applications on a rolling basis beginning at the start of 2021.** With the phases and priorities laid out above, UGP will aim to make a significant impact by catalyzing growth and innovation in the UNI ecosystem.
**This program is meant to be the simplest possible MVP of a Uniswap Ecosystem Grants initiative.** While the multi-sig committee comes with trust assumptions about the members, our hope is the community will approve this limited engagement to get the ball rolling in an efficient structure. **After the first epoch (2 fiscal quarters) the burden of proof will be on UGP to show empirical evidence that the program is worth continuing in its existing form and will submit to governance to renew treasury funding.**
If this program proves successful, we hope it will inspire others to follow suit and create their own funding committees for allocating treasury capital—ideally with different specializations.
`

View File

@@ -3,11 +3,9 @@ import {
BigintIsh,
Currency,
CurrencyAmount,
currencyEquals,
ETHER,
JSBI,
Pair,
Percent,
Route,
Token,
TokenAmount,
@@ -157,31 +155,3 @@ export function useV1TradeExchangeAddress(trade: Trade | undefined): string | un
}, [trade])
return useV1ExchangeAddress(tokenAddress)
}
const ZERO_PERCENT = new Percent('0')
const ONE_HUNDRED_PERCENT = new Percent('1')
// returns whether tradeB is better than tradeA by at least a threshold percentage amount
export function isTradeBetter(
tradeA: Trade | undefined,
tradeB: Trade | undefined,
minimumDelta: Percent = ZERO_PERCENT
): boolean | undefined {
if (tradeA && !tradeB) return false
if (tradeB && !tradeA) return true
if (!tradeA || !tradeB) return undefined
if (
tradeA.tradeType !== tradeB.tradeType ||
!currencyEquals(tradeA.inputAmount.currency, tradeB.inputAmount.currency) ||
!currencyEquals(tradeB.outputAmount.currency, tradeB.outputAmount.currency)
) {
throw new Error('Trades are not comparable')
}
if (minimumDelta.equalTo(ZERO_PERCENT)) {
return tradeA.executionPrice.lessThan(tradeB.executionPrice)
} else {
return tradeA.executionPrice.raw.multiply(minimumDelta.add(ONE_HUNDRED_PERCENT)).lessThan(tradeB.executionPrice)
}
}

View File

@@ -8,6 +8,7 @@ import { isAddress } from '../utils'
import { useActiveWeb3React } from './index'
import { useBytes32TokenContract, useTokenContract } from './useContract'
import { arrayify } from 'ethers/lib/utils'
export function useAllTokens(): { [address: string]: Token } {
const { chainId } = useActiveWeb3React()
@@ -40,10 +41,12 @@ export function useIsUserAddedToken(currency: Currency): boolean {
// parse a name or symbol from a token response
const BYTES32_REGEX = /^0x[a-fA-F0-9]{64}$/
function parseStringOrBytes32(str: string | undefined, bytes32: string | undefined, defaultValue: string): string {
return str && str.length > 0
? str
: bytes32 && BYTES32_REGEX.test(bytes32)
: // need to check for proper bytes string and valid terminator
bytes32 && BYTES32_REGEX.test(bytes32) && arrayify(bytes32)[31] === 0
? parseBytes32String(bytes32)
: defaultValue
}

View File

@@ -1,12 +1,14 @@
import { isTradeBetter } from 'utils/trades'
import { Currency, CurrencyAmount, Pair, Token, Trade } from '@uniswap/sdk'
import flatMap from 'lodash.flatmap'
import { useMemo } from 'react'
import { BASES_TO_CHECK_TRADES_AGAINST, CUSTOM_BASES } from '../constants'
import { BASES_TO_CHECK_TRADES_AGAINST, CUSTOM_BASES, BETTER_TRADE_LESS_HOPS_THRESHOLD } from '../constants'
import { PairState, usePairs } from '../data/Reserves'
import { wrappedCurrency } from '../utils/wrappedCurrency'
import { useActiveWeb3React } from './index'
import { useUserSingleHopOnly } from 'state/user/hooks'
function useAllCommonPairs(currencyA?: Currency, currencyB?: Currency): Pair[] {
const { chainId } = useActiveWeb3React()
@@ -78,19 +80,40 @@ function useAllCommonPairs(currencyA?: Currency, currencyB?: Currency): Pair[] {
)
}
const MAX_HOPS = 3
/**
* Returns the best trade for the exact amount of tokens in to the given token out
*/
export function useTradeExactIn(currencyAmountIn?: CurrencyAmount, currencyOut?: Currency): Trade | null {
const allowedPairs = useAllCommonPairs(currencyAmountIn?.currency, currencyOut)
const [singleHopOnly] = useUserSingleHopOnly()
return useMemo(() => {
if (currencyAmountIn && currencyOut && allowedPairs.length > 0) {
return (
Trade.bestTradeExactIn(allowedPairs, currencyAmountIn, currencyOut, { maxHops: 3, maxNumResults: 1 })[0] ?? null
)
if (singleHopOnly) {
return (
Trade.bestTradeExactIn(allowedPairs, currencyAmountIn, currencyOut, { maxHops: 1, maxNumResults: 1 })[0] ??
null
)
}
// search through trades with varying hops, find best trade out of them
let bestTradeSoFar: Trade | null = null
for (let i = 1; i <= MAX_HOPS; i++) {
const currentTrade: Trade | null =
Trade.bestTradeExactIn(allowedPairs, currencyAmountIn, currencyOut, { maxHops: i, maxNumResults: 1 })[0] ??
null
// if current trade is best yet, save it
if (isTradeBetter(bestTradeSoFar, currentTrade, BETTER_TRADE_LESS_HOPS_THRESHOLD)) {
bestTradeSoFar = currentTrade
}
}
return bestTradeSoFar
}
return null
}, [allowedPairs, currencyAmountIn, currencyOut])
}, [allowedPairs, currencyAmountIn, currencyOut, singleHopOnly])
}
/**
@@ -99,13 +122,28 @@ export function useTradeExactIn(currencyAmountIn?: CurrencyAmount, currencyOut?:
export function useTradeExactOut(currencyIn?: Currency, currencyAmountOut?: CurrencyAmount): Trade | null {
const allowedPairs = useAllCommonPairs(currencyIn, currencyAmountOut?.currency)
const [singleHopOnly] = useUserSingleHopOnly()
return useMemo(() => {
if (currencyIn && currencyAmountOut && allowedPairs.length > 0) {
return (
Trade.bestTradeExactOut(allowedPairs, currencyIn, currencyAmountOut, { maxHops: 3, maxNumResults: 1 })[0] ??
null
)
if (singleHopOnly) {
return (
Trade.bestTradeExactOut(allowedPairs, currencyIn, currencyAmountOut, { maxHops: 1, maxNumResults: 1 })[0] ??
null
)
}
// search through trades with varying hops, find best trade out of them
let bestTradeSoFar: Trade | null = null
for (let i = 1; i <= MAX_HOPS; i++) {
const currentTrade =
Trade.bestTradeExactOut(allowedPairs, currencyIn, currencyAmountOut, { maxHops: i, maxNumResults: 1 })[0] ??
null
if (isTradeBetter(bestTradeSoFar, currentTrade, BETTER_TRADE_LESS_HOPS_THRESHOLD)) {
bestTradeSoFar = currentTrade
}
}
return bestTradeSoFar
}
return null
}, [allowedPairs, currencyIn, currencyAmountOut])
}, [currencyIn, currencyAmountOut, allowedPairs, singleHopOnly])
}

View File

@@ -6,6 +6,7 @@ import ReactDOM from 'react-dom'
import ReactGA from 'react-ga'
import { Provider } from 'react-redux'
import { HashRouter } from 'react-router-dom'
import Blocklist from './components/Blocklist'
import { NetworkContextName } from './constants'
import './i18n'
import App from './pages/App'
@@ -58,15 +59,17 @@ ReactDOM.render(
<FixedGlobalStyle />
<Web3ReactProvider getLibrary={getLibrary}>
<Web3ProviderNetwork getLibrary={getLibrary}>
<Provider store={store}>
<Updaters />
<ThemeProvider>
<ThemedGlobalStyle />
<HashRouter>
<App />
</HashRouter>
</ThemeProvider>
</Provider>
<Blocklist>
<Provider store={store}>
<Updaters />
<ThemeProvider>
<ThemedGlobalStyle />
<HashRouter>
<App />
</HashRouter>
</ThemeProvider>
</Provider>
</Blocklist>
</Web3ProviderNetwork>
</Web3ReactProvider>
</StrictMode>,

View File

@@ -21,7 +21,7 @@ import TokenWarningModal from '../../components/TokenWarningModal'
import ProgressSteps from '../../components/ProgressSteps'
import { BETTER_TRADE_LINK_THRESHOLD, INITIAL_ALLOWED_SLIPPAGE } from '../../constants'
import { getTradeVersion, isTradeBetter } from '../../data/V1'
import { getTradeVersion } from '../../data/V1'
import { useActiveWeb3React } from '../../hooks'
import { useCurrency } from '../../hooks/Tokens'
import { ApprovalState, useApproveCallbackFromTrade } from '../../hooks/useApproveCallback'
@@ -37,13 +37,14 @@ import {
useSwapActionHandlers,
useSwapState
} from '../../state/swap/hooks'
import { useExpertModeManager, useUserSlippageTolerance } from '../../state/user/hooks'
import { useExpertModeManager, useUserSlippageTolerance, useUserSingleHopOnly } from '../../state/user/hooks'
import { LinkStyledButton, TYPE } from '../../theme'
import { maxAmountSpend } from '../../utils/maxAmountSpend'
import { computeTradePriceBreakdown, warningSeverity } from '../../utils/prices'
import AppBody from '../AppBody'
import { ClickableText } from '../Pool/styleds'
import Loader from '../../components/Loader'
import { isTradeBetter } from 'utils/trades'
export default function Swap() {
const loadedUrlParams = useDefaultsFromURLSearch()
@@ -183,6 +184,8 @@ export default function Swap() {
const { priceImpactWithoutFee } = computeTradePriceBreakdown(trade)
const [singleHopOnly] = useUserSingleHopOnly()
const handleSwap = useCallback(() => {
if (priceImpactWithoutFee && !confirmPriceImpactWithoutFee(priceImpactWithoutFee)) {
return
@@ -209,6 +212,11 @@ export default function Swap() {
getTradeVersion(trade)
].join('/')
})
ReactGA.event({
category: 'Routing',
action: singleHopOnly ? 'Swap with multihop disabled' : 'Swap with multihop enabled'
})
})
.catch(error => {
setSwapState({
@@ -219,7 +227,17 @@ export default function Swap() {
txHash: undefined
})
})
}, [tradeToConfirm, account, priceImpactWithoutFee, recipient, recipientAddress, showConfirm, swapCallback, trade])
}, [
priceImpactWithoutFee,
swapCallback,
tradeToConfirm,
showConfirm,
recipient,
recipientAddress,
account,
trade,
singleHopOnly
])
// errors
const [showInverted, setShowInverted] = useState<boolean>(false)
@@ -384,6 +402,7 @@ export default function Swap() {
) : noRoute && userHasSpecifiedInputOutput ? (
<GreyCard style={{ textAlign: 'center' }}>
<TYPE.main mb="4px">Insufficient liquidity for this trade.</TYPE.main>
{singleHopOnly && <TYPE.main mb="4px">Try enabling multi-hop trades.</TYPE.main>}
</GreyCard>
) : showApproveFlow ? (
<RowBetween>

View File

@@ -10,19 +10,20 @@ import { ArrowLeft } from 'react-feather'
import { ButtonPrimary } from '../../components/Button'
import { ProposalStatus } from './styled'
import { useProposalData, useUserVotesAsOfBlock, ProposalData, useUserDelegatee } from '../../state/governance/hooks'
import { useTimestampFromBlock } from '../../hooks/useTimestampFromBlock'
import { DateTime } from 'luxon'
import ReactMarkdown from 'react-markdown'
import VoteModal from '../../components/vote/VoteModal'
import { TokenAmount, JSBI } from '@uniswap/sdk'
import { useActiveWeb3React } from '../../hooks'
import { PROPOSAL_LENGTH_IN_SECS, COMMON_CONTRACT_NAMES, UNI, ZERO_ADDRESS } from '../../constants'
import { AVERAGE_BLOCK_TIME_IN_SECS, COMMON_CONTRACT_NAMES, UNI, ZERO_ADDRESS } from '../../constants'
import { isAddress, getEtherscanLink } from '../../utils'
import { ApplicationModal } from '../../state/application/actions'
import { useModalOpen, useToggleDelegateModal, useToggleVoteModal } from '../../state/application/hooks'
import { useModalOpen, useToggleDelegateModal, useToggleVoteModal, useBlockNumber } from '../../state/application/hooks'
import DelegateModal from '../../components/vote/DelegateModal'
import { GreyCard } from '../../components/Card'
import { useTokenBalance } from '../../state/wallet/hooks'
import useCurrentBlockTimestamp from 'hooks/useCurrentBlockTimestamp'
import { BigNumber } from 'ethers'
const PageWrapper = styled(AutoColumn)`
width: 100%;
@@ -124,10 +125,16 @@ export default function VotePage({
const toggelDelegateModal = useToggleDelegateModal()
// get and format date from data
const startTimestamp: number | undefined = useTimestampFromBlock(proposalData?.startBlock)
const endDate: DateTime | undefined = startTimestamp
? DateTime.fromSeconds(startTimestamp).plus({ seconds: PROPOSAL_LENGTH_IN_SECS })
: undefined
const currentTimestamp = useCurrentBlockTimestamp()
const currentBlock = useBlockNumber()
const endDate: DateTime | undefined =
proposalData && currentTimestamp && currentBlock
? DateTime.fromSeconds(
currentTimestamp
.add(BigNumber.from(AVERAGE_BLOCK_TIME_IN_SECS).mul(BigNumber.from(proposalData.endBlock - currentBlock)))
.toNumber()
)
: undefined
const now: DateTime = DateTime.local()
// get total votes and format percentages for UI

View File

@@ -1,4 +1,4 @@
import { UNI } from './../../constants/index'
import { UNI, PRELOADED_PROPOSALS } from './../../constants/index'
import { TokenAmount } from '@uniswap/sdk'
import { isAddress } from 'ethers/lib/utils'
import { useGovernanceContract, useUniContract } from '../../hooks/useContract'
@@ -121,10 +121,11 @@ export function useAllProposalData() {
return Boolean(p.result) && Boolean(allProposalStates[i]?.result) && Boolean(formattedEvents[i])
})
.map((p, i) => {
const description = PRELOADED_PROPOSALS.get(allProposals.length - i - 1) || formattedEvents[i].description
const formattedProposal: ProposalData = {
id: allProposals[i]?.result?.id.toString(),
title: formattedEvents[i].description?.split(/# |\n/g)[1] || 'Untitled',
description: formattedEvents[i].description || 'No description.',
title: description?.split(/# |\n/g)[1] || 'Untitled',
description: description || 'No description.',
proposer: allProposals[i]?.result?.proposer,
status: enumerateProposalState(allProposalStates[i]?.result?.[0]) ?? 'Undetermined',
forCount: parseFloat(ethers.utils.formatUnits(allProposals[i]?.result?.forVotes.toString(), 18)),

View File

@@ -16,6 +16,7 @@ export interface SerializedPair {
export const updateMatchesDarkMode = createAction<{ matchesDarkMode: boolean }>('user/updateMatchesDarkMode')
export const updateUserDarkMode = createAction<{ userDarkMode: boolean }>('user/updateUserDarkMode')
export const updateUserExpertMode = createAction<{ userExpertMode: boolean }>('user/updateUserExpertMode')
export const updateUserSingleHopOnly = createAction<{ userSingleHopOnly: boolean }>('user/updateUserSingleHopOnly')
export const updateUserSlippageTolerance = createAction<{ userSlippageTolerance: number }>(
'user/updateUserSlippageTolerance'
)

View File

@@ -1,5 +1,6 @@
import { ChainId, Pair, Token } from '@uniswap/sdk'
import flatMap from 'lodash.flatmap'
import ReactGA from 'react-ga'
import { useCallback, useMemo } from 'react'
import { shallowEqual, useDispatch, useSelector } from 'react-redux'
import { BASES_TO_TRACK_LIQUIDITY_FOR, PINNED_PAIRS } from '../../constants'
@@ -17,7 +18,8 @@ import {
updateUserDeadline,
updateUserExpertMode,
updateUserSlippageTolerance,
toggleURLWarning
toggleURLWarning,
updateUserSingleHopOnly
} from './actions'
function serializeToken(token: Token): SerializedToken {
@@ -81,6 +83,27 @@ export function useExpertModeManager(): [boolean, () => void] {
return [expertMode, toggleSetExpertMode]
}
export function useUserSingleHopOnly(): [boolean, (newSingleHopOnly: boolean) => void] {
const dispatch = useDispatch<AppDispatch>()
const singleHopOnly = useSelector<AppState, AppState['user']['userSingleHopOnly']>(
state => state.user.userSingleHopOnly
)
const setSingleHopOnly = useCallback(
(newSingleHopOnly: boolean) => {
ReactGA.event({
category: 'Routing',
action: newSingleHopOnly ? 'enable single hop' : 'disable single hop'
})
dispatch(updateUserSingleHopOnly({ userSingleHopOnly: newSingleHopOnly }))
},
[dispatch]
)
return [singleHopOnly, setSingleHopOnly]
}
export function useUserSlippageTolerance(): [number, (slippage: number) => void] {
const dispatch = useDispatch<AppDispatch>()
const userSlippageTolerance = useSelector<AppState, AppState['user']['userSlippageTolerance']>(state => {

View File

@@ -13,7 +13,8 @@ import {
updateUserExpertMode,
updateUserSlippageTolerance,
updateUserDeadline,
toggleURLWarning
toggleURLWarning,
updateUserSingleHopOnly
} from './actions'
const currentTimestamp = () => new Date().getTime()
@@ -27,6 +28,8 @@ export interface UserState {
userExpertMode: boolean
userSingleHopOnly: boolean // only allow swaps on direct pairs
// user defined slippage tolerance in bips, used in all txns
userSlippageTolerance: number
@@ -58,6 +61,7 @@ export const initialState: UserState = {
userDarkMode: null,
matchesDarkMode: false,
userExpertMode: false,
userSingleHopOnly: false,
userSlippageTolerance: INITIAL_ALLOWED_SLIPPAGE,
userDeadline: DEFAULT_DEADLINE_FROM_NOW,
tokens: {},
@@ -103,6 +107,9 @@ export default createReducer(initialState, builder =>
state.userDeadline = action.payload.userDeadline
state.timestamp = currentTimestamp()
})
.addCase(updateUserSingleHopOnly, (state, action) => {
state.userSingleHopOnly = action.payload.userSingleHopOnly
})
.addCase(addSerializedToken, (state, { payload: { serializedToken } }) => {
state.tokens[serializedToken.chainId] = state.tokens[serializedToken.chainId] || {}
state.tokens[serializedToken.chainId][serializedToken.address] = serializedToken

29
src/utils/trades.ts Normal file
View File

@@ -0,0 +1,29 @@
import { Trade, currencyEquals, Percent } from '@uniswap/sdk'
const ZERO_PERCENT = new Percent('0')
const ONE_HUNDRED_PERCENT = new Percent('1')
// returns whether tradeB is better than tradeA by at least a threshold percentage amount
export function isTradeBetter(
tradeA: Trade | undefined | null,
tradeB: Trade | undefined | null,
minimumDelta: Percent = ZERO_PERCENT
): boolean | undefined {
if (tradeA && !tradeB) return false
if (tradeB && !tradeA) return true
if (!tradeA || !tradeB) return undefined
if (
tradeA.tradeType !== tradeB.tradeType ||
!currencyEquals(tradeA.inputAmount.currency, tradeB.inputAmount.currency) ||
!currencyEquals(tradeB.outputAmount.currency, tradeB.outputAmount.currency)
) {
throw new Error('Trades are not comparable')
}
if (minimumDelta.equalTo(ZERO_PERCENT)) {
return tradeA.executionPrice.lessThan(tradeB.executionPrice)
} else {
return tradeA.executionPrice.raw.multiply(minimumDelta.add(ONE_HUNDRED_PERCENT)).lessThan(tradeB.executionPrice)
}
}

View File

@@ -2726,10 +2726,10 @@
tiny-warning "^1.0.3"
toformat "^2.0.0"
"@uniswap/token-lists@^1.0.0-beta.18":
version "1.0.0-beta.18"
resolved "https://registry.yarnpkg.com/@uniswap/token-lists/-/token-lists-1.0.0-beta.18.tgz#b6c70b67fa9ee142e6df088e40490ec3a545e7ba"
integrity sha512-RuDY36JUc2+Id2Dlpnt+coFfUEf9WkfvR0a3LKvwVgzAfcrd5KvjZg+PhAr4bczFU1aq7rs3/QLgwpsnFYaiPw==
"@uniswap/token-lists@^1.0.0-beta.19":
version "1.0.0-beta.19"
resolved "https://registry.yarnpkg.com/@uniswap/token-lists/-/token-lists-1.0.0-beta.19.tgz#5256db144fba721a6233f43b92ffb388cbd58327"
integrity sha512-19V3KM7DAe40blWW1ApiaSYwqbq0JTKMO3yChGBrXzQBl+BoQZRTNZ4waCyoZ5QM45Q0Mxd6bCn6jXcH9G1kjg==
"@uniswap/v2-core@1.0.0":
version "1.0.0"