Skip to content
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

Resolving proxy contracts transparently for ABI's #95

Merged
merged 5 commits into from
Mar 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ NEXT_PUBLIC_DELEGATION_ANNOUNCEMENTS_START_BLOCK=10541166 # per chain
# Plugin addresses
NEXT_PUBLIC_TOKEN_VOTING_PLUGIN_ADDRESS=0x1276a2f2F8Ea2172FAD053562C2fa05966111A42
NEXT_PUBLIC_DELEGATION_CONTRACT_ADDRESS=0xb3b899F190Af7f5FEE002f6f823743Ba80b2FfA1
NEXT_PUBLIC_DUAL_GOVERNANCE_PLUGIN_ADDRESS=0xa6796635D194442b4FAC81904E60E380cFE3eDAE # Goerli
NEXT_PUBLIC_DUAL_GOVERNANCE_PLUGIN_ADDRESS=0xa6796635D194442b4FAC81904E60E380cFE3eDAE

# Network and services
NEXT_PUBLIC_CHAIN_NAME=goerli
NEXT_PUBLIC_WEB3_URL_PREFIX=https://eth-goerli.g.alchemy.com/v2/
NEXT_PUBLIC_CHAIN_NAME=sepolia
NEXT_PUBLIC_WEB3_URL_PREFIX=https://eth-sepolia.g.alchemy.com/v2/

NEXT_PUBLIC_ALCHEMY_API_KEY="ALCHEMY KEY"
NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID="YOUR WALLET CONNECT PROJECT ID"
Expand All @@ -19,7 +19,7 @@ NEXT_PUBLIC_IPFS_API_KEY="..."
NEXT_PUBLIC_ETHERSCAN_API_KEY="OPTIONAL: ETHERSCAN API"

# PRIVATE (scripts)
DEPLOYMENT_TARGET_CHAIN_ID=goerli
DEPLOYMENT_TARGET_CHAIN_ID=sepolia
DEPLOYMENT_WALLET_PRIVATE_KEY="0x..."
DEPLOYMENT_ALCHEMY_API_KEY="..."
DEPLOYMENT_WEB3_ENDPOINT="https://..."
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/app-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jobs:
NEXT_PUBLIC_TOKEN_VOTING_PLUGIN_ADDRESS: "0x1234567890123456789012345678901234567890"
NEXT_PUBLIC_DELEGATION_CONTRACT_ADDRESS: "0x1234567890123456789012345678901234567890"
NEXT_PUBLIC_DUAL_GOVERNANCE_PLUGIN_ADDRESS: "0x1234567890123456789012345678901234567890"
NEXT_PUBLIC_CHAIN_NAME: goerli
NEXT_PUBLIC_CHAIN_NAME: sepolia
NEXT_PUBLIC_WEB3_URL_PREFIX: https://rpc/
NEXT_PUBLIC_ALCHEMY_API_KEY: x
NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID: x
Expand Down
43 changes: 29 additions & 14 deletions components/input/function-selector.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react";
import { Hex, encodeFunctionData } from "viem";
import { Button, InputText } from "@aragon/ods";
import { AlertInline, Button, InputText } from "@aragon/ods";
import { AbiFunction } from "abitype";
import { Else, If, Then } from "@/components/if";
import { decodeCamelCase } from "@/utils/case";
Expand Down Expand Up @@ -75,9 +75,7 @@ export const FunctionSelector = ({
};

const functionAbiList = (abi || []).filter(
(item) =>
item.type === "function" &&
!["pure", "view"].includes(item.stateMutability)
(item) => item.type === "function"
);

return (
Expand All @@ -91,7 +89,14 @@ export const FunctionSelector = ({
onClick={() => setSelectedAbiItem(fn)}
className={`w-full text-left font-sm hover:bg-neutral-100 py-2 px-3 rounded-xl hover:cursor-pointer ${fn.name === selectedAbiItem?.name && "bg-neutral-100 font-semibold"}`}
>
{decodeCamelCase(fn.name)}
<If condition={!["pure", "view"].includes(fn.stateMutability)}>
<Then>{decodeCamelCase(fn.name)}</Then>
<Else>
<span>{decodeCamelCase(fn.name)}</span>
<br />
<span className="text-xs text-neutral-300">(read only)</span>
</Else>
</If>
</li>
))}
</ul>
Expand All @@ -102,21 +107,31 @@ export const FunctionSelector = ({
<Then>
<div className="">
<div className="flex flex-row justify-between items-center mx-4 mb-3 pb-4 border-b border-neutral-200">
<p className="text-lg font-semibold text-neutral-800">
<p className="text-md font-semibold text-neutral-800 mr-3">
<code>{decodeCamelCase(selectedAbiItem?.name)}</code>
</p>
<div className="ml-4 min-w-10">
<Button className="" size="sm" onClick={onAddAction}>
<div className="">
<Button
className="!min-w-[110px]"
size="sm"
onClick={onAddAction}
>
Add action
</Button>
</div>
</div>
{/* Make titles smaller */}
<style>{`
label div p.leading-tight {
font-size: 1rem;
}
`}</style>
<If
condition={["pure", "view"].includes(
selectedAbiItem?.stateMutability || ""
)}
>
<div className="mx-4">
<AlertInline
message="This function is marked as read only. An action with it would have no impact"
variant="warning"
/>
</div>
</If>
{selectedAbiItem?.inputs.map((paramAbi, i) => (
<div key={i} className="mx-4 my-3">
<InputParameter
Expand Down
2 changes: 1 addition & 1 deletion components/input/input-parameter-array.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const InputParameterArray = ({
{abi.name ? decodeCamelCase(abi.name) : "Parameter " + (idx + 1)}
</p>
{value.map((item, i) => (
<div className="flex">
<div key={i} className="flex">
<InputText
className={i > 0 ? "mt-3" : ""}
addon={(i + 1).toString()}
Expand Down
2 changes: 1 addition & 1 deletion components/input/input-parameter-tuple-array.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export const InputParameterTupleArray = ({
<If not={someMissingName}>
<Then>
{values.map((_, i) => (
<div className="mt-6">
<div key={i} className="mt-6">
<div className="flex justify-between">
<p className="text-base font-normal leading-tight text-neutral-800 md:text-lg mb-3">
{abi.name
Expand Down
2 changes: 1 addition & 1 deletion constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const PUB_DELEGATION_ANNOUNCEMENTS_START_BLOCK = BigInt(

// Target chain
export const PUB_CHAIN_NAME = (process.env.NEXT_PUBLIC_CHAIN_NAME ??
"goerli") as ChainName;
"sepolia") as ChainName;
export const PUB_CHAIN = getChain(PUB_CHAIN_NAME);

// Network and services
Expand Down
89 changes: 72 additions & 17 deletions hooks/useAbi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,56 @@ import { useQuery } from "@tanstack/react-query";
import { isAddress } from "@/utils/evm";
import { PUB_CHAIN, PUB_ETHERSCAN_API_KEY } from "@/constants";
import { useAlerts } from "@/context/Alerts";
import { getImplementation, isProxyContract } from "@/utils/proxies";
import { ChainName } from "@/utils/chains";

const CHAIN_NAME = PUB_CHAIN.name.toLowerCase() as ChainName;

export const useAbi = (contractAddress: Address) => {
const { addAlert } = useAlerts();
const publicClient = usePublicClient({ chainId: PUB_CHAIN.id });

const { data: implementationAddress, isLoading: isLoadingImpl } =
useQuery<Address | null>({
queryKey: ["proxy-check", contractAddress, !!publicClient],
queryFn: () => {
if (!contractAddress || !publicClient) return null;

return isProxyContract(publicClient, contractAddress)
.then((isProxy) => {
if (!isProxy) return null;
return getImplementation(publicClient, contractAddress);
})
.catch(() => null);
},
retry: 4,
refetchOnMount: false,
refetchOnReconnect: false,
retryOnMount: true,
staleTime: Infinity,
});

const resolvedAddress = isAddress(implementationAddress)
? implementationAddress
: contractAddress;

const {
data: abi,
isLoading,
error,
} = useQuery<AbiFunction[], Error>({
queryKey: [contractAddress || "", !!publicClient],
queryKey: ["abi", resolvedAddress || "", !!publicClient],
queryFn: () => {
if (!contractAddress || !isAddress(contractAddress) || !publicClient) {
if (!resolvedAddress || !isAddress(resolvedAddress) || !publicClient) {
return Promise.resolve([]);
}

const abiLoader = new whatsabi.loaders.EtherscanABILoader({
apiKey: PUB_ETHERSCAN_API_KEY,
});

const abiLoader = getEtherscanAbiLoader();
return whatsabi
.autoload(contractAddress!, {
.autoload(resolvedAddress, {
provider: publicClient,
abiLoader,
followProxies: true,
followProxies: false,
enableExperimentalMetadata: true,
})
.then(({ abi }) => {
Expand All @@ -42,18 +67,17 @@ export const useAbi = (contractAddress: Address) => {
name: (item as any).name ?? "(function)",
inputs: item.inputs ?? [],
outputs: item.outputs ?? [],
stateMutability: item.stateMutability ?? "payable",
stateMutability: item.stateMutability || "payable",
type: item.type,
});
}
functionItems.sort((a, b) => {
if (
["pure", "view"].includes(a.stateMutability) &&
["pure", "view"].includes(b.stateMutability)
) {
return 0;
} else if (["pure", "view"].includes(a.stateMutability)) return 1;
else if (["pure", "view"].includes(b.stateMutability)) return -1;
const a_RO = ["pure", "view"].includes(a.stateMutability);
const b_RO = ["pure", "view"].includes(b.stateMutability);

if (a_RO === b_RO) return 0;
else if (a_RO) return 1;
else if (b_RO) return -1;
return 0;
});
return functionItems;
Expand All @@ -76,7 +100,38 @@ export const useAbi = (contractAddress: Address) => {

return {
abi: abi ?? [],
isLoading,
isLoading: isLoading || isLoadingImpl,
error,
};
};

function getEtherscanAbiLoader() {
switch (CHAIN_NAME) {
case "mainnet":
return new whatsabi.loaders.EtherscanABILoader({
apiKey: PUB_ETHERSCAN_API_KEY,
});
case "polygon":
return new whatsabi.loaders.EtherscanABILoader({
apiKey: PUB_ETHERSCAN_API_KEY,
baseURL: "https://api.polygonscan.com/api",
});
case "arbitrum":
return new whatsabi.loaders.EtherscanABILoader({
apiKey: PUB_ETHERSCAN_API_KEY,
baseURL: "https://api.arbiscan.io/api",
});
case "sepolia":
return new whatsabi.loaders.EtherscanABILoader({
apiKey: PUB_ETHERSCAN_API_KEY,
baseURL: "https://api-sepolia.etherscan.io/api",
});
case "mumbai":
return new whatsabi.loaders.EtherscanABILoader({
apiKey: PUB_ETHERSCAN_API_KEY,
baseURL: "https://api-mumbai.polygonscan.com/api",
});
default:
throw new Error("Unknown chain");
}
}
2 changes: 1 addition & 1 deletion hooks/useMetadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useQuery } from "@tanstack/react-query";

export function useMetadata<T = JsonValue>(ipfsUri?: string) {
const { data, isLoading, isSuccess, error } = useQuery<T, Error>({
queryKey: [ipfsUri || ""],
queryKey: ["ipfs", ipfsUri || ""],
queryFn: () => {
if (!ipfsUri) return Promise.resolve("");

Expand Down
12 changes: 12 additions & 0 deletions pages/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@ ol {
color: var(--ods-color-neutral-600);
}

/* Inline alerts */
div.inline-flex.items-center.gap-x-2.rounded p {
font-size: 14px !important;
font-weight: 400;
opacity: 0.8;
}

/* Smaller titles */
label div p.leading-tight {
font-size: 1rem;
}

/* Dark mode snippet */
/*
@media (prefers-color-scheme: dark) {
Expand Down
2 changes: 1 addition & 1 deletion utils/case.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export function decodeCamelCase(input?: string): string {
if (!input || typeof input !== "string") return "";

if (input.startsWith("_")) input = input.replace(/^_+/, "");
input = input.replace(/_+/g, " ").trim();
return (
input
.replace(/([a-z])([A-Z])/g, "$1 $2")
Expand Down
23 changes: 19 additions & 4 deletions utils/chains.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
import { polygon, mainnet, sepolia, goerli, Chain } from "@wagmi/core/chains";
import {
polygon,
mainnet,
sepolia,
arbitrum,
polygonMumbai,
Chain,
} from "@wagmi/core/chains";

const chainNames = ["mainnet", "polygon", "sepolia", "goerli"] as const;
const chainNames = [
"mainnet",
"polygon",
"sepolia",
"mumbai",
"arbitrum",
] as const;
export type ChainName = (typeof chainNames)[number];

export function getChain(chainName: ChainName): Chain {
Expand All @@ -9,10 +22,12 @@ export function getChain(chainName: ChainName): Chain {
return mainnet;
case "polygon":
return polygon;
case "arbitrum":
return arbitrum;
case "sepolia":
return sepolia;
case "goerli":
return goerli;
case "mumbai":
return polygonMumbai;
default:
throw new Error("Unknown chain");
}
Expand Down
Loading
Loading