-
Notifications
You must be signed in to change notification settings - Fork 39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Follow Proxies #41
Merged
Merged
Follow Proxies #41
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
aa94c78
Add infura property to config
hasparus eac5c48
Detect transparent proxy pattern
hasparus 1663229
Unit test detectProxy
hasparus 099ea37
Test for implementation ABI in gatherABIs
hasparus 7e0ce0e
Add missing ethers peerDependencies
hasparus 767f969
Add changeset
hasparus 30bb2dc
Remove redundant comment
hasparus 65acd85
Allow specifying multiple RPC URLs and opting out of proxy following
hasparus 9fe200d
Describe noFollowProxies in README
hasparus File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
--- | ||
'@dethcrypto/eth-sdk': minor | ||
--- | ||
|
||
Given an address to a proxy, eth-sdk now generates ethers Contract for implementation contract | ||
|
||
As we need to call the chain to get the implementation contract address, two new config options are introduced. You can | ||
specify Ethereum JSON-RPC endpoints in `config.rpc` and opt out from proxy following with `config.noFollowProxies`. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
106 changes: 106 additions & 0 deletions
106
packages/eth-sdk/src/abi-management/detectProxy.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
import { Interface } from '@ethersproject/abi' | ||
import { TransactionRequest } from '@ethersproject/abstract-provider' | ||
import { expect, mockFn } from 'earljs' | ||
import { constants } from 'ethers' | ||
|
||
import { randomAddress } from '../../test/test-utils' | ||
import { Abi } from '../types' | ||
import { detectProxy, EIP1967_IMPLEMENTATION_STORAGE_SLOT } from './detectProxy' | ||
import type { RpcProvider } from './getRpcProvider' | ||
|
||
describe(detectProxy.name, () => { | ||
const abiWithImplementationGetter: Abi = [ | ||
{ name: 'implementation', type: 'function', outputs: [{ type: 'address' }], stateMutability: 'view' }, | ||
] | ||
const proxyAddr = randomAddress('0x123') | ||
const implAddr = randomAddress('0x456') | ||
const implementationCall: TransactionRequest = { | ||
to: proxyAddr, | ||
data: new Interface(abiWithImplementationGetter).encodeFunctionData('implementation', []), | ||
} | ||
|
||
it('detects .implementation getter', async () => { | ||
const rpcProvider = { | ||
call: mockFn<RpcProvider['call']>().resolvesToOnce(implAddr), | ||
getCode: mockFn<RpcProvider['getCode']>().resolvesToOnce('0xfff'), | ||
getStorageAt: mockFn<RpcProvider['getStorageAt']>(), | ||
} | ||
|
||
const actual = await detectProxy(proxyAddr, abiWithImplementationGetter, rpcProvider) | ||
|
||
expect(actual).toEqual({ | ||
implAddress: implAddr, | ||
isProxy: true, | ||
}) | ||
expect(rpcProvider.call).toHaveBeenCalledWith([implementationCall]) | ||
expect(rpcProvider.getCode).toHaveBeenCalledWith([implAddr]) | ||
}) | ||
|
||
it('returns { isProxy: false } when .implementation returns nothing', async () => { | ||
const rpcProvider = { | ||
call: mockFn<RpcProvider['call']>().resolvesToOnce(constants.AddressZero), | ||
getCode: mockFn<RpcProvider['getCode']>().resolvesToOnce('0xfff'), | ||
getStorageAt: mockFn<RpcProvider['getStorageAt']>(), | ||
} | ||
|
||
const actual = await detectProxy(proxyAddr, abiWithImplementationGetter, rpcProvider) | ||
|
||
expect(rpcProvider.getCode.calls.length).toEqual(0) | ||
expect(rpcProvider.getStorageAt.calls.length).toEqual(0) | ||
expect(actual).toEqual({ isProxy: false }) | ||
}) | ||
|
||
it('returns { isProxy: false } when address from .implementation has no contract code', async () => { | ||
const rpcProvider = { | ||
call: mockFn<RpcProvider['call']>().resolvesToOnce(implAddr), | ||
getCode: mockFn<RpcProvider['getCode']>().given(implAddr).resolvesToOnce(constants.AddressZero), | ||
getStorageAt: mockFn<RpcProvider['getStorageAt']>(), | ||
} | ||
|
||
const actual = await detectProxy(proxyAddr, abiWithImplementationGetter, rpcProvider) | ||
|
||
expect(rpcProvider.getStorageAt.calls.length).toEqual(0) | ||
expect(actual).toEqual({ isProxy: false }) | ||
}) | ||
|
||
it('reads storage under EIP1967 implementation storage slot', async () => { | ||
const rpcProvider = { | ||
call: mockFn<RpcProvider['call']>(), | ||
getCode: mockFn<RpcProvider['getCode']>().resolvesToOnce('0xfff'), | ||
getStorageAt: mockFn<RpcProvider['getStorageAt']>() | ||
.given(proxyAddr, EIP1967_IMPLEMENTATION_STORAGE_SLOT) | ||
.resolvesToOnce(implAddr), | ||
} | ||
const abi: Abi = [] | ||
|
||
const actual = await detectProxy(proxyAddr, abi, rpcProvider) | ||
|
||
expect(actual).toEqual({ implAddress: implAddr, isProxy: true }) | ||
expect(rpcProvider.getStorageAt).toHaveBeenCalledWith([proxyAddr, EIP1967_IMPLEMENTATION_STORAGE_SLOT]) | ||
}) | ||
|
||
it('detects and calls custom implementation getters', async () => { | ||
const abi: Abi = [ | ||
{ name: 'currentImplementation', type: 'function', outputs: [{ type: 'address' }], stateMutability: 'view' }, | ||
{ | ||
name: 'pendingCurrentImplementation', | ||
type: 'function', | ||
outputs: [{ type: 'address' }], | ||
stateMutability: 'view', | ||
}, | ||
] | ||
const rpcProvider = { | ||
call: mockFn<RpcProvider['call']>() | ||
.given({ to: proxyAddr, data: new Interface(abi).encodeFunctionData('currentImplementation', []) }) | ||
.resolvesToOnce(implAddr), | ||
getCode: mockFn<RpcProvider['getCode']>().resolvesToOnce('0xfff'), | ||
getStorageAt: mockFn<RpcProvider['getStorageAt']>().resolvesToOnce('0x0'), | ||
} | ||
|
||
const actual = await detectProxy(proxyAddr, abi, rpcProvider) | ||
expect(actual).toEqual({ | ||
implAddress: implAddr, | ||
isProxy: true, | ||
}) | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
import { Interface } from '@ethersproject/abi' | ||
import { BigNumber } from '@ethersproject/bignumber' | ||
|
||
import { Address, parseAddress } from '../config' | ||
import { Abi, JsonFragment } from '../types' | ||
import { RpcProvider } from './getRpcProvider' | ||
|
||
export async function detectProxy(address: Address, abi: Abi, provider: RpcProvider): Promise<DetectProxyResult> { | ||
const stored = await lookForImplementationAddr(address, abi, provider) | ||
|
||
const asNumber = BigNumber.from(stored || 0) | ||
if (!asNumber.isZero()) { | ||
const implAddress = asNumber.toHexString() | ||
const code = await provider.getCode(implAddress) | ||
const isContract = !BigNumber.from(code).isZero() | ||
|
||
if (isContract) { | ||
return { implAddress: parseAddress(implAddress), isProxy: true } | ||
} | ||
} | ||
|
||
return { isProxy: false } | ||
} | ||
|
||
export type DetectProxyResult = { implAddress: Address; isProxy: true } | { isProxy: false } | ||
|
||
async function lookForImplementationAddr(address: Address, abi: Abi, provider: RpcProvider): Promise<BigNumber | null> { | ||
const call = async (name: string) => | ||
BigNumber.from( | ||
await provider.call({ | ||
to: address, | ||
data: new Interface(abi).encodeFunctionData(name, []), | ||
}), | ||
) | ||
|
||
// If there is an `.implementation` getter, we try to call it. | ||
const implementationGetter = abi.find((fragment) => fragment.name === 'implementation') | ||
if (implementationGetter && isPossibleImplementationGetter(implementationGetter)) { | ||
return call('implementation') | ||
} | ||
|
||
// We check storage slot specified by EIP-1967 to hold implementation address. | ||
// see https://eips.ethereum.org/EIPS/eip-1967 | ||
const stored = BigNumber.from(await provider.getStorageAt(address, EIP1967_IMPLEMENTATION_STORAGE_SLOT)) | ||
if (!stored.isZero()) return stored | ||
|
||
// Otherwise, we try shortest getter ending with "Implementation" | ||
const possibleImplementationGetters = abi.filter(isPossibleImplementationGetter) | ||
if (possibleImplementationGetters.length) { | ||
const [frag] = possibleImplementationGetters.sort((a, b) => a.name.length - b.name.length) | ||
return call(frag.name) | ||
} | ||
|
||
return null | ||
} | ||
|
||
/** @internal */ | ||
export const EIP1967_IMPLEMENTATION_STORAGE_SLOT = '0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc' | ||
|
||
const isPossibleImplementationGetter = (frag: JsonFragment): frag is JsonFragment & { name: string } => { | ||
if ( | ||
frag.type === 'function' && | ||
frag.name && | ||
frag.name.match(/[iI]mplementation$/) && | ||
(frag.stateMutability === 'view' || frag.stateMutability === 'pure') | ||
) { | ||
const output = frag.outputs?.[0] | ||
return output?.type === 'address' | ||
} | ||
return false | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
38 changes: 38 additions & 0 deletions
38
packages/eth-sdk/src/abi-management/getRpcProvider.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import { expect } from 'earljs' | ||
import { providers } from 'ethers' | ||
|
||
import { EthSdkConfig } from '../config' | ||
import { createEthSdkConfig } from '../config' | ||
import { getRpcProvider } from './getRpcProvider' | ||
import { UserProvidedNetworkSymbol } from './networks' | ||
|
||
describe(getRpcProvider.name, () => { | ||
const config = createEthSdkConfig({ contracts: {} }) | ||
|
||
it('defaults to a built-in URL', () => { | ||
const provider = getRpcProvider(config, 'mainnet') as providers.JsonRpcProvider | ||
|
||
expect(provider.connection.url).toEqual('https://mainnet.infura.io/v3/0993a4f4500c4fff88649d28b331898c') | ||
}) | ||
|
||
it('uses the RPC url from config', () => { | ||
const cfg: EthSdkConfig = { | ||
...config, | ||
rpc: { kovan: 'https://kovan.test', polygonMumbai: 'https://polygonMumbai.test' }, | ||
} | ||
|
||
let provider = getRpcProvider(cfg, 'kovan') as providers.JsonRpcProvider | ||
|
||
expect(provider.connection.url).toEqual('https://kovan.test') | ||
|
||
provider = getRpcProvider(cfg, 'polygonMumbai') as providers.JsonRpcProvider | ||
|
||
expect(provider.connection.url).toEqual('https://polygonMumbai.test') | ||
}) | ||
|
||
it('returns null when there is no RPC URL for given network', () => { | ||
const provider = getRpcProvider(config, 'user-provided' as UserProvidedNetworkSymbol) | ||
|
||
expect(provider).toEqual(null) | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
import { ethers } from 'ethers' | ||
|
||
import { EthSdkConfig, RpcURLs } from '../config' | ||
import { NetworkSymbol } from './networks' | ||
|
||
const INFURA_PROJECT_URL = '0993a4f4500c4fff88649d28b331898c' | ||
|
||
const rpcProviders: RpcURLs = { | ||
mainnet: `https://mainnet.infura.io/v3/${INFURA_PROJECT_URL}`, | ||
kovan: `https://kovan.infura.io/v3/${INFURA_PROJECT_URL}`, | ||
rinkeby: `https://rinkeby.infura.io/v3/${INFURA_PROJECT_URL}`, | ||
ropsten: `https://ropsten.infura.io/v3/${INFURA_PROJECT_URL}`, | ||
goerli: `https://goerli.infura.io/v3/${INFURA_PROJECT_URL}`, | ||
} | ||
|
||
export function getRpcProvider(config: EthSdkConfig, network: NetworkSymbol): RpcProvider | null { | ||
const rpcUrl = config.rpc[network] || rpcProviders[network] | ||
|
||
return rpcUrl ? new ethers.providers.JsonRpcProvider(rpcUrl) : null | ||
} | ||
|
||
export type RpcProvider = Pick<ethers.providers.Provider, 'getCode' | 'getStorageAt' | 'call'> | ||
|
||
export type GetRpcProvider = typeof getRpcProvider |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is a Markdown All in One extension for VSCode which updates the TOC automatically.