forked from Uniswap/sybil-interface
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhooks.ts
507 lines (444 loc) · 14.9 KB
/
hooks.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
import { TransactionResponse } from '@ethersproject/providers'
import { TokenAmount, Token, Percent } from '@uniswap/sdk'
import { updateActiveProtocol, updateFilterActive, updateTopDelegates, updateVerifiedDelegates } from './actions'
import { AppDispatch, AppState } from './../index'
import { useDispatch, useSelector } from 'react-redux'
import { GovernanceInfo } from './reducer'
import { useState, useEffect, useCallback } from 'react'
import { useGovernanceContract, useGovTokenContract } from '../../hooks/useContract'
import { useSingleCallResult, useSingleContractMultipleData, NEVER_RELOAD } from '../multicall/hooks'
import { useActiveWeb3React } from '../../hooks'
import { useTransactionAdder } from '../transactions/hooks'
import { isAddress, calculateGasMargin } from '../../utils'
import { useSubgraphClient } from '../application/hooks'
import { fetchProposals, fetchGlobalData, enumerateProposalState } from '../../data/governance'
import { ALL_VOTERS, DELEGATE_INFO } from '../../apollo/queries'
import { deserializeToken } from '../user/hooks'
import { useIsEOA } from '../../hooks/useIsEOA'
export interface GlobaData {
id: string
totalTokenHolders: number
totalDelegates: number
delegatedVotes: number
delegatedVotesRaw: number
}
export interface DelegateData {
id: string
delegatedVotes: number
delegatedVotesRaw: number
votePercent: Percent
votes: {
id: string
support: boolean
votes: number
}[]
EOA: boolean | undefined //
handle: string | undefined // twitter handle
imageURL?: string | undefined
}
export function useActiveProtocol(): [GovernanceInfo | undefined, (activeProtocol: GovernanceInfo) => void] {
const dispatch = useDispatch<AppDispatch>()
const activeProtocol = useSelector<AppState, AppState['governance']['activeProtocol']>(state => {
return state.governance.activeProtocol
})
const setActiveProtocol = useCallback(
(activeProtocol: GovernanceInfo) => {
dispatch(updateActiveProtocol({ activeProtocol }))
},
[dispatch]
)
return [activeProtocol, setActiveProtocol]
}
export function useFilterActive(): [boolean, (filterActive: boolean) => void] {
const dispatch = useDispatch<AppDispatch>()
const filterActive = useSelector<AppState, AppState['governance']['filterActive']>(state => {
return state.governance.filterActive
})
const setFilterActive = useCallback(
(filterActive: boolean) => {
dispatch(updateFilterActive({ filterActive }))
},
[dispatch]
)
return [filterActive, setFilterActive]
}
export function useGovernanceToken(): Token | undefined {
const { chainId } = useActiveWeb3React()
const [activeProtocol] = useActiveProtocol()
return chainId && activeProtocol ? deserializeToken(activeProtocol.token) : undefined
}
// @todo add typed query response
export function useGlobalData(): GlobaData | undefined {
const { library } = useActiveWeb3React()
const client = useSubgraphClient()
const [globalData, setGlobalData] = useState<GlobaData | undefined>()
useEffect(() => {
fetchGlobalData(client).then((data: GlobaData | null) => {
if (data) {
setGlobalData(data)
}
})
}, [library, client])
return globalData
}
export function useTopDelegates(): [DelegateData[] | undefined, (topDelegates: DelegateData[] | undefined) => void] {
const [activeProtocol] = useActiveProtocol()
const dispatch = useDispatch<AppDispatch>()
const delegates = useSelector<AppState, AppState['governance']['topDelegates']>(state => {
return state.governance.topDelegates
})
const setTopDelegates = useCallback(
(topDelegates: DelegateData[] | undefined) => {
activeProtocol && dispatch(updateTopDelegates({ protocolID: activeProtocol?.id, topDelegates }))
},
[activeProtocol, dispatch]
)
return [activeProtocol ? delegates?.[activeProtocol.id] : undefined, setTopDelegates]
}
export function useVerifiedDelegates(): [
DelegateData[] | undefined,
(verifiedDelegates: DelegateData[] | undefined) => void
] {
const [activeProtocol] = useActiveProtocol()
const dispatch = useDispatch<AppDispatch>()
const delegates = useSelector<AppState, AppState['governance']['verifiedDelegates']>(state => {
return state.governance.verifiedDelegates
})
const setVerifiedDelegates = useCallback(
(verifiedDelegates: DelegateData[] | undefined) => {
activeProtocol && dispatch(updateVerifiedDelegates({ protocolID: activeProtocol?.id, verifiedDelegates }))
},
[activeProtocol, dispatch]
)
return [activeProtocol ? delegates?.[activeProtocol.id] : undefined, setVerifiedDelegates]
}
interface ProposalDetail {
target: string
functionSig: string
callData: string
}
export interface ProposalData {
id: string
title: string
description: string
proposer: string
status: string
forCount: number | undefined
againstCount: number | undefined
startBlock: number
endBlock: number
details: ProposalDetail[]
forVotes: {
support: boolean
votes: string
voter: {
id: string
}
}[]
againstVotes: {
support: boolean
votes: string
voter: {
id: string
}
}[]
}
// get count of all proposals made
export function useProposalCount(): number | undefined {
const gov = useGovernanceContract()
const res = useSingleCallResult(gov, 'proposalCount')
if (res.result && !res.loading) {
return parseInt(res.result[0])
}
return undefined
}
/**
* @TODO can this be used to speed up the loading?
*/
export function useAllProposalStates(): number[] | undefined {
const govContract = useGovernanceContract()
const [statuses, setStatuses] = useState<number[] | undefined>()
// get total amount
const proposalCount = useProposalCount()
const ids = proposalCount ? Array.from({ length: proposalCount }, (v, k) => [k + 1]) : [['']]
const statusRes = useSingleContractMultipleData(proposalCount ? govContract : undefined, 'state', ids, NEVER_RELOAD)
useEffect(() => {
if (!statuses) {
const formattedRes = statusRes?.map(res => {
if (!res.loading && res.valid) {
return res.result?.[0]
}
})
if (formattedRes[0]) {
setStatuses(formattedRes)
}
}
}, [statuses, statusRes])
return statuses
}
export function useProposalStatus(id: string): string | undefined {
const allStatuses = useAllProposalStates()
return allStatuses ? enumerateProposalState(allStatuses[parseInt(id) - 1]) : undefined
}
export function useAllProposals(): { [id: string]: ProposalData } | undefined {
const [proposals, setProposals] = useState<{ [id: string]: ProposalData } | undefined>()
// get subgraph client for active protocol
const govClient = useSubgraphClient()
const govToken = useGovernanceToken()
// reset proposals on protocol change
const [activeProtocol] = useActiveProtocol()
useEffect(() => {
setProposals(undefined)
}, [activeProtocol])
// get number of proposals
const amount = useProposalCount()
// need to manually fetch counts and states as not in subgraph
const govContract = useGovernanceContract()
const ids = amount ? Array.from({ length: amount }, (v, k) => [k + 1]) : [['']]
const counts = useSingleContractMultipleData(amount ? govContract : undefined, 'proposals', ids)
const states = useAllProposalStates()
// subgraphs only store ids in lowercase, format
useEffect(() => {
async function fetchData() {
try {
if (govToken) {
fetchProposals(govClient, govToken.address).then((data: ProposalData[] | null) => {
if (data) {
const proposalMap = data.reduce<{ [id: string]: ProposalData }>((accum, proposal: ProposalData) => {
accum[proposal.id] = proposal
return accum
}, {})
setProposals(proposalMap)
}
})
}
} catch (e) {
console.log(e)
}
}
if (!proposals && govToken) {
fetchData()
}
}, [govClient, govToken, proposals, states])
useEffect(() => {
if (counts && proposals && govToken) {
Object.values(proposals).map((p, i) => {
p.forCount = counts?.[i]?.result?.forVotes
? parseFloat(new TokenAmount(govToken, counts?.[i]?.result?.forVotes).toExact())
: undefined
p.againstCount = counts?.[i]?.result?.againstVotes
? parseFloat(new TokenAmount(govToken, counts?.[i]?.result?.againstVotes).toExact())
: undefined
return true
})
}
}, [counts, govToken, proposals])
return proposals
}
export function useProposalData(id: string): ProposalData | undefined {
const allProposalData = useAllProposals()
return allProposalData?.[id]
}
// get the users delegatee if it exists
export function useUserDelegatee(): string {
const { account } = useActiveWeb3React()
const uniContract = useGovTokenContract()
const { result } = useSingleCallResult(uniContract, 'delegates', [account ?? undefined])
return result?.[0] ?? undefined
}
// gets the users current votes
export function useUserVotes(): TokenAmount | undefined {
const { account } = useActiveWeb3React()
const govTokenContract = useGovTokenContract()
const govToken = useGovernanceToken()
// check for available votes
const votes = useSingleCallResult(govTokenContract, 'getCurrentVotes', [account ?? undefined])?.result?.[0]
return votes && govToken ? new TokenAmount(govToken, votes) : undefined
}
// fetch available votes as of block (usually proposal start block)
export function useUserVotesAsOfBlock(block: number | undefined): TokenAmount | undefined {
const { account } = useActiveWeb3React()
const govTokenContract = useGovTokenContract()
const govToken = useGovernanceToken()
// check for available votes
const votes = useSingleCallResult(govTokenContract, 'getPriorVotes', [account ?? undefined, block ?? undefined])
?.result?.[0]
return votes && govToken ? new TokenAmount(govToken, votes) : undefined
}
export function useDelegateCallback(): (delegatee: string | undefined) => undefined | Promise<string> {
const { account, chainId, library } = useActiveWeb3React()
const addTransaction = useTransactionAdder()
const govTokenContract = useGovTokenContract()
return useCallback(
(delegatee: string | undefined) => {
if (!library || !chainId || !account || !isAddress(delegatee ?? '')) return undefined
const args = [delegatee]
if (!govTokenContract) throw new Error('No UNI Contract!')
return govTokenContract.estimateGas.delegate(...args, {}).then(estimatedGasLimit => {
return govTokenContract
.delegate(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Delegated votes`
})
return response.hash
})
})
},
[account, addTransaction, chainId, library, govTokenContract]
)
}
export function useVoteCallback(): {
voteCallback: (proposalId: string | undefined, support: boolean) => undefined | Promise<string>
} {
const { account } = useActiveWeb3React()
const govContract = useGovernanceContract()
const addTransaction = useTransactionAdder()
const voteCallback = useCallback(
(proposalId: string | undefined, support: boolean) => {
if (!account || !govContract || !proposalId) return
const args = [proposalId, support]
return govContract.estimateGas.castVote(...args, {}).then(estimatedGasLimit => {
return govContract
.castVote(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Voted ${support ? 'for ' : 'against'} proposal ${proposalId}`
})
return response.hash
})
})
},
[account, addTransaction, govContract]
)
return { voteCallback }
}
export function useAllVotersForProposal(
proposalID: string,
support: boolean
):
| {
votes: string
voter: {
id: string
}
}[]
| undefined {
const subgraphClient = useSubgraphClient()
const [voters, setVoters] = useState<
| {
votes: string
voter: {
id: string
}
}[]
| undefined
>()
useEffect(() => {
setVoters(undefined)
}, [proposalID, subgraphClient])
useEffect(() => {
async function fetchData() {
subgraphClient
?.query({
query: ALL_VOTERS,
variables: {
proposalID,
support
}
})
.then(
(res: {
data: {
votes: {
votes: string
voter: {
id: string
}
}[]
}
}) => {
setVoters(res.data.votes)
}
)
}
if (!voters) {
fetchData()
}
})
return voters
}
export interface DelegateInfo {
// amount of votes delegated to them
delegatedVotes: number
// amount of delegates they represent
tokenHoldersRepresentedAmount: number
// proposals theyve voted on
votes: {
proposal: number
votes: number
support: boolean
}[]
EOA: boolean | null // null means loading
}
interface DelegateInfoRes {
data:
| {
delegates: {
delegatedVotes: string
tokenHoldersRepresentedAmount: number
votes: {
proposal: {
id: string
}
support: boolean
votes: string
}[]
}[]
}
| undefined
}
export function useDelegateInfo(address: string | undefined): DelegateInfo | undefined {
const client = useSubgraphClient()
const [data, setData] = useState<DelegateInfo | undefined>()
const isEOA = useIsEOA(address)
useEffect(() => {
async function fetchData() {
client
?.query({
query: DELEGATE_INFO,
variables: {
address: address?.toLocaleLowerCase()
}
})
.then((res: DelegateInfoRes) => {
if (res?.data) {
const resData = res.data.delegates[0]
const votes = resData
? resData.votes
// sort in order created
.sort((a, b) => (parseInt(a.proposal.id) > parseInt(b.proposal.id) ? 1 : -1))
.map((v: { proposal: { id: string }; support: boolean; votes: string }) => ({
proposal: parseInt(v.proposal.id),
votes: parseFloat(v.votes),
support: v.support
}))
: []
setData({
delegatedVotes: parseFloat(resData?.delegatedVotes ?? '0'),
tokenHoldersRepresentedAmount: resData?.tokenHoldersRepresentedAmount ?? 0,
votes,
EOA: isEOA
})
}
})
.catch(e => {
console.log(e)
})
}
if (!data && address) {
fetchData()
}
}, [address, client, data, isEOA])
return data
}