|
| 1 | +import { formatUnits } from '@ethersproject/units'; |
| 2 | +import { getAddress, isAddress } from '@ethersproject/address'; |
| 3 | +import { multicall } from '../../utils'; |
| 4 | + |
| 5 | +export const author = 'snapshot-labs'; |
| 6 | +export const version = '0.1.0'; |
| 7 | + |
| 8 | +const abi = [ |
| 9 | + 'function delegates(address account) view returns (address)', |
| 10 | + 'function balanceOf(address account) view returns (uint256)' |
| 11 | +]; |
| 12 | + |
| 13 | +export async function strategy( |
| 14 | + space, |
| 15 | + network, |
| 16 | + provider, |
| 17 | + addresses, |
| 18 | + options, |
| 19 | + snapshot |
| 20 | +) { |
| 21 | + const blockTag = typeof snapshot === 'number' ? snapshot : 'latest'; |
| 22 | + |
| 23 | + // Combine both delegates and balanceOf calls in a single multicall |
| 24 | + const calls = addresses.flatMap((address: any) => [ |
| 25 | + [options.address, 'delegates', [address.toLowerCase()]], |
| 26 | + [options.address, 'balanceOf', [address.toLowerCase()]] |
| 27 | + ]); |
| 28 | + |
| 29 | + const response = await multicall(network, provider, abi, calls, { blockTag }); |
| 30 | + |
| 31 | + return Object.fromEntries( |
| 32 | + addresses.map((address, i) => { |
| 33 | + const delegatesIndex = i * 2; |
| 34 | + const balanceOfIndex = i * 2 + 1; |
| 35 | + |
| 36 | + const delegateTo = response[delegatesIndex]?.toString().toLowerCase(); |
| 37 | + const balance = parseFloat( |
| 38 | + formatUnits(response[balanceOfIndex].toString(), options.decimals || 18) |
| 39 | + ); |
| 40 | + |
| 41 | + // If user has delegated their voting power (to anyone, including themselves), their voting power is 0 |
| 42 | + // Otherwise, they get their balance as voting power |
| 43 | + const hasDelegated = hasDelegateAddress(delegateTo); |
| 44 | + const totalVotingPower = hasDelegated ? 0 : balance; |
| 45 | + |
| 46 | + return [getAddress(address), totalVotingPower]; |
| 47 | + }) |
| 48 | + ); |
| 49 | +} |
| 50 | + |
| 51 | +function hasDelegateAddress(delegateAddress: string | undefined): boolean { |
| 52 | + return ( |
| 53 | + !!delegateAddress && |
| 54 | + isAddress(delegateAddress) && |
| 55 | + delegateAddress !== '0x0000000000000000000000000000000000000000' |
| 56 | + ); |
| 57 | +} |
0 commit comments