Skip to content

Instantly share code, notes, and snippets.

@ghostffcode
Last active June 30, 2023 14:42
Show Gist options
  • Save ghostffcode/30194186f5fa40490644fbe484653a64 to your computer and use it in GitHub Desktop.
Save ghostffcode/30194186f5fa40490644fbe484653a64 to your computer and use it in GitHub Desktop.
Hooks for interacting with user safes
import { useEffect, useState } from "react";
import { isAddress } from "viem";
import { useNetwork } from "wagmi";
interface Props {
address?: string;
chainId?: number;
}
const useMySafes = ({ address = "", chainId }: Props) => {
const { chain } = useNetwork();
const [safes, setSafes] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
useEffect(() => {
const loadSafesForOwner = async () => {
setIsLoading(true);
try {
const activeChainId = chainId || chain?.id || 1;
const res = await fetch(`https://safe-client.safe.global/v1/chains/${activeChainId}/owners/${address}/safes`);
const data = await res.json();
setIsError(false);
setSafes(data);
} catch (error) {
setIsError(true);
setSafes([]);
}
setIsLoading(false);
};
if (isAddress(address)) {
loadSafesForOwner();
}
}, [address, chain?.id, chainId]);
return { data: safes, isLoading, isError };
};
export default useMySafes;
import { isAddress } from "viem";
import { useContractReads } from "wagmi";
const safeABI = [
{
inputs: [],
name: "getThreshold",
outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "getOwners",
outputs: [{ internalType: "address[]", name: "", type: "address[]" }],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "nonce",
outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
stateMutability: "view",
type: "function",
},
];
interface Props {
address?: string;
}
const useSafe = ({ address }: Props) => {
const { data, isError, isLoading } = useContractReads({
contracts: safeABI.map(i => ({
address,
abi: safeABI,
functionName: i.name,
})),
enabled: isAddress(address as string),
select: (_data: any[]) => ({ threshold: _data[0], owners: _data[1], nonce: _data[2] }),
});
return { data, isError, isLoading };
};
export default useSafe;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment