Skip to content

Commit

Permalink
Merge pull request #15 from dynamic-labs/fix/safe-switch-network
Browse files Browse the repository at this point in the history
fix: check and change network for safe
  • Loading branch information
matthew1809 authored Jul 9, 2024
2 parents b832691 + 2a03708 commit 32bee92
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 24 deletions.
2 changes: 1 addition & 1 deletion .lintstagedrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const buildHardhatEslintCommand = (filenames) =>
module.exports = {
"packages/nextjs/**/*.{ts,tsx}": [
buildNextEslintCommand,
checkTypesNextCommand,
// checkTypesNextCommand,
],
"packages/hardhat/**/*.{ts,tsx}": [buildHardhatEslintCommand],
};
4 changes: 2 additions & 2 deletions packages/nextjs/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { Address } from "~~/components/scaffold-eth";
import { sendTransaction, signMessage } from "~~/lib/dynamic";

const Home: NextPage = () => {
const { primaryWallet } = useDynamicContext();
const { primaryWallet, networkConfigurations } = useDynamicContext();
const [messageSignature, setMessageSignature] = useState<string>("");
const [transactionSignature, setTransactionSignature] = useState<string>("");
const connectedAddress = primaryWallet?.address;
Expand All @@ -33,7 +33,7 @@ const Home: NextPage = () => {
if (!isTestnet) {
alert("You might want to switch to testnet to send transactions");
}
const hash = await sendTransaction(connectedAddress, "0.0001", primaryWallet);
const hash = await sendTransaction(connectedAddress, "0.0001", primaryWallet, networkConfigurations);
setTransactionSignature(hash);

setTimeout(() => {
Expand Down
56 changes: 39 additions & 17 deletions packages/nextjs/app/safe/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use client";

import { useState } from "react";
import { ExternalLinkIcon, useDynamicContext } from "@dynamic-labs/sdk-react-core";
import { useEffect, useState } from "react";
import { ExternalLinkIcon, getNetwork, useDynamicContext, useSwitchNetwork } from "@dynamic-labs/sdk-react-core";
import { createWalletClientFromWallet } from "@dynamic-labs/viem-utils";
import { formatUnits } from "viem";
import { baseSepolia } from "viem/chains";
Expand All @@ -26,6 +26,7 @@ import {
const SafePage = () => {
const { address, chain, isConnected } = useAccount();
const { primaryWallet, isAuthenticated } = useDynamicContext();
const switchNetwork = useSwitchNetwork();

const [safeDeployed, setSafeDeployed] = useState(false);
const [safeAddress, setSafeAddress] = useState<string | null>("");
Expand All @@ -40,6 +41,7 @@ const SafePage = () => {
const [crossChainRecipientAddress, setCrossChainRecipientAddress] = useState<string>("");
const [transferTokenAddress, setTransferTokenAddress] = useState<string>("");
const [recipientAddress, setRecipientAddress] = useState<string>("");
const [network, setNetwork] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
const { data: safeBalance, refetch: refetchSafeBalance } = useBalance({
address: (safeAddress || ("" as `0x${string}`)) as `0x${string}`,
Expand All @@ -53,12 +55,23 @@ const SafePage = () => {
args: [safeAddress],
});

const fetchNetwork = async () => {
if (!primaryWallet) return;
const network = Number(await getNetwork(primaryWallet.connector));
setNetwork(network);
};

useEffect(() => {
fetchNetwork();
}, [primaryWallet]);

const handleDeploySafe = async () => {
setLoading(true);
setError(null);
try {
const userAddress = address as `0x${string}`;
if (!primaryWallet || !chain) return;

const walletClient = await createWalletClientFromWallet(primaryWallet);
const { account } = await getPimlicoSmartAccountClient(userAddress, chain, walletClient);
setSafeAddress(account.address);
Expand Down Expand Up @@ -362,21 +375,30 @@ const SafePage = () => {
</div>
) : (
<>
<button
className="btn btn-success"
onClick={handleDeploySafe}
disabled={loading || !isConnected || !isAuthenticated}
>
{loading ? (
<>
<span className="loading loading-spinner"></span>Deploying...
</>
) : isConnected && isAuthenticated ? (
"Deploy Safe Account"
) : (
"Connect Wallet first"
)}
</button>
{isConnected && isAuthenticated && network !== baseSepolia.id ? (
<button
className="btn btn-success"
onClick={() => switchNetwork({ wallet: primaryWallet, network: baseSepolia.id })}
>
Switch to Base Sepolia
</button>
) : (
<button
className="btn btn-success"
onClick={handleDeploySafe}
disabled={loading || !isConnected || !isAuthenticated}
>
{loading ? (
<>
<span className="loading loading-spinner"></span>Deploying...
</>
) : isConnected && isAuthenticated ? (
"Deploy Safe Account"
) : (
"Connect Wallet first"
)}
</button>
)}
{error && <p className="text-red-500 mt-4">{error}</p>}
</>
)}
Expand Down
13 changes: 9 additions & 4 deletions packages/nextjs/lib/dynamic.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
import { Wallet } from "@dynamic-labs/sdk-react-core";
import { NetworkConfigurationMap } from "@dynamic-labs/types";
import { getOrMapViemChain } from "@dynamic-labs/viem-utils";
import { Account, Chain, Hex, Transport, WalletClient, parseEther } from "viem";
import { customEvmNetworks } from "~~/lib/networks";

export const signMessage = async (message: string, wallet: any): Promise<string> => {
const connector = wallet?.connector;

return await connector.signMessage(message);
};

export const sendTransaction = async (address: any, amount: string, wallet: Wallet): Promise<string> => {
export const sendTransaction = async (
address: any,
amount: string,
wallet: Wallet,
networkConfigurations: NetworkConfigurationMap,
): Promise<string> => {
const walletClient = wallet.connector.getWalletClient<WalletClient<Transport, Chain, Account>>();

const chainID = await wallet.connector.getNetwork();
const currentNetwork = customEvmNetworks.find(network => network.chainId === chainID);
const currentNetwork = networkConfigurations.evm?.find(network => network.chainId === chainID);

if (!currentNetwork) {
throw new Error("No chain ID found");
throw new Error("Network not found");
}

const chain = getOrMapViemChain(currentNetwork);
Expand Down

0 comments on commit 32bee92

Please sign in to comment.