useCallback for listeners

This commit is contained in:
apoorvlathey
2024-10-30 19:25:32 +04:00
parent 895f6d37b2
commit e6303ffc64
3 changed files with 187 additions and 155 deletions

View File

@@ -24,7 +24,7 @@ function BrowserExtensionTab() {
</chakra.a> </chakra.a>
</Text> </Text>
</Box> </Box>
<HStack mt="2" w="full" fontSize={"lg"}> {/* <HStack mt="2" w="full" fontSize={"lg"}>
<Text>Read more:</Text> <Text>Read more:</Text>
<Link <Link
color="cyan.200" color="cyan.200"
@@ -34,7 +34,7 @@ function BrowserExtensionTab() {
> >
Launch Tweet Launch Tweet
</Link> </Link>
</HStack> </HStack> */}
<Image mt="2" src="/extension.png" /> <Image mt="2" src="/extension.png" />
</Center> </Center>
); );

View File

@@ -1,6 +1,6 @@
"use client"; "use client";
import { useState, useEffect } from "react"; import { useState, useEffect, useCallback } from "react";
import { Container, useToast, Center, Spacer, Flex } from "@chakra-ui/react"; import { Container, useToast, Center, Spacer, Flex } from "@chakra-ui/react";
import { SingleValue } from "chakra-react-select"; import { SingleValue } from "chakra-react-select";
@@ -171,13 +171,6 @@ function Body() {
// eslint-disable-next-line // eslint-disable-next-line
}, [provider]); }, [provider]);
useEffect(() => {
if (web3wallet) {
subscribeToEvents();
}
// eslint-disable-next-line
}, [web3wallet]);
useEffect(() => { useEffect(() => {
localStorage.setItem("tenderlyForkId", tenderlyForkId); localStorage.setItem("tenderlyForkId", tenderlyForkId);
}, [tenderlyForkId]); }, [tenderlyForkId]);
@@ -236,7 +229,17 @@ function Body() {
}, },
], ],
}) })
.then((res) => console.log(res.data)); .then((res) => {
console.log(res.data);
toast({
title: "Txn Simulated on Tenderly",
description: `Hash: ${res.data.result}`,
status: "success",
position: "bottom-right",
duration: null,
isClosable: true,
});
});
} }
} }
// eslint-disable-next-line // eslint-disable-next-line
@@ -380,11 +383,8 @@ function Body() {
setAppUrl(_inputAppUrl); setAppUrl(_inputAppUrl);
}; };
const subscribeToEvents = async () => { const onSessionProposal = useCallback(
console.log("ACTION", "subscribeToEvents"); async (proposal) => {
if (web3wallet) {
web3wallet.on("session_proposal", async (proposal) => {
if (loading) { if (loading) {
setLoading(false); setLoading(false);
} }
@@ -400,15 +400,11 @@ function Body() {
: undefined; : undefined;
let chains: string[] | undefined = let chains: string[] | undefined =
requiredNamespace === undefined requiredNamespace === undefined ? undefined : requiredNamespace.chains;
? undefined
: requiredNamespace.chains;
if (optionalNamespace && optionalNamespace.chains) { if (optionalNamespace && optionalNamespace.chains) {
if (chains) { if (chains) {
// merge chains from requiredNamespace & optionalNamespace, while avoiding duplicates // merge chains from requiredNamespace & optionalNamespace, while avoiding duplicates
chains = Array.from( chains = Array.from(new Set(chains.concat(optionalNamespace.chains)));
new Set(chains.concat(optionalNamespace.chains))
);
} else { } else {
chains = optionalNamespace.chains; chains = optionalNamespace.chains;
} }
@@ -424,8 +420,7 @@ function Body() {
chains: chains, chains: chains,
methods: methods:
requiredNamespace === undefined ? [] : requiredNamespace.methods, requiredNamespace === undefined ? [] : requiredNamespace.methods,
events: events: requiredNamespace === undefined ? [] : requiredNamespace.events,
requiredNamespace === undefined ? [] : requiredNamespace.events,
}; };
if (requiredNamespace && requiredNamespace.chains) { if (requiredNamespace && requiredNamespace.chains) {
@@ -436,7 +431,7 @@ function Body() {
}); });
} }
const session = await web3wallet.approveSession({ const session = await web3wallet?.approveSession({
id: proposal.id, id: proposal.id,
namespaces: { namespaces: {
[namespaceKey]: namespace, [namespaceKey]: namespace,
@@ -444,56 +439,21 @@ function Body() {
}); });
setWeb3WalletSession(session); setWeb3WalletSession(session);
setIsConnected(true); setIsConnected(true);
});
try {
await web3wallet.core.pairing.pair({ uri });
} catch (e) {
console.error(e);
}
web3wallet.on("session_request", async (event) => {
const { topic, params, id } = event;
const { request } = params;
console.log("EVENT", "session_request", event);
if (request.method === "eth_sendTransaction") {
await handleSendTransaction(id, request.params, topic);
} else {
await web3wallet.respondSessionRequest({
topic,
response: {
jsonrpc: "2.0",
id: id,
error: {
code: 0,
message: "Method not supported by Impersonator",
}, },
}, [web3wallet]
}); );
}
});
web3wallet.on("session_delete", () => { const handleSendTransaction = useCallback(
console.log("EVENT", "session_delete"); async (id: number, params: any[], topic?: string) => {
reset();
});
}
};
const handleSendTransaction = async (
id: number,
params: any[],
topic?: string
) => {
setSendTxnData((data) => { setSendTxnData((data) => {
const newTxn = { const newTxn = {
id: id, id: id,
from: params[0].from, from: params[0].from,
to: params[0].to, to: params[0].to,
data: params[0].data, data: params[0].data,
value: params[0].value ? parseInt(params[0].value, 16).toString() : "0", value: params[0].value
? parseInt(params[0].value, 16).toString()
: "0",
}; };
if (data.some((d) => d.id === newTxn.id)) { if (data.some((d) => d.id === newTxn.id)) {
@@ -531,7 +491,10 @@ function Body() {
response: { response: {
jsonrpc: "2.0", jsonrpc: "2.0",
id: id, id: id,
error: { code: 0, message: "Method not supported by Impersonator" }, error: {
code: 0,
message: "Method not supported by Impersonator",
},
}, },
}); });
} }
@@ -551,13 +514,81 @@ function Body() {
response: { response: {
jsonrpc: "2.0", jsonrpc: "2.0",
id: id, id: id,
error: { code: 0, message: "Method not supported by Impersonator" }, error: {
code: 0,
message: "Method not supported by Impersonator",
},
}, },
}); });
} }
} }
},
[tenderlyForkId, web3wallet]
);
const onSessionRequest = useCallback(
async (event) => {
const { topic, params, id } = event;
const { request } = params;
console.log("EVENT", "session_request", event);
if (request.method === "eth_sendTransaction") {
await handleSendTransaction(id, request.params, topic);
} else {
await web3wallet?.respondSessionRequest({
topic,
response: {
jsonrpc: "2.0",
id: id,
error: {
code: 0,
message: "Method not supported by Impersonator",
},
},
});
}
},
[web3wallet, handleSendTransaction]
);
const onSessionDelete = () => {
console.log("EVENT", "session_delete");
reset();
}; };
const subscribeToEvents = useCallback(async () => {
console.log("ACTION", "subscribeToEvents");
if (web3wallet) {
web3wallet.on("session_proposal", onSessionProposal);
try {
await web3wallet.core.pairing.pair({ uri });
} catch (e) {
console.error(e);
}
web3wallet.on("session_request", onSessionRequest);
web3wallet.on("session_delete", onSessionDelete);
}
}, [handleSendTransaction, web3wallet]);
useEffect(() => {
if (web3wallet) {
subscribeToEvents();
}
return () => {
// Clean up event listeners
if (web3wallet) {
web3wallet.removeListener("session_proposal", onSessionProposal);
web3wallet.removeListener("session_request", onSessionRequest);
web3wallet.removeListener("session_delete", onSessionDelete);
}
};
}, [web3wallet, subscribeToEvents]);
const updateSession = async ({ const updateSession = async ({
newChainId, newChainId,
newAddress, newAddress,

View File

@@ -17,6 +17,7 @@ const theme = extendTheme({
global: { global: {
body: { body: {
bg: "brand.black", bg: "brand.black",
color: "white",
}, },
}, },
}, },