Skip to content

Commit

Permalink
fix web3.js v4.x issue with contract interaction
Browse files Browse the repository at this point in the history
  • Loading branch information
chaitanyapotti committed Nov 2, 2023
1 parent bad3780 commit 467b0c7
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 4 deletions.
4 changes: 4 additions & 0 deletions demo/react-app/src/components/Main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const Main = () => {
switchChain,
getTokenBalance,
signAndSendTokenTransaction,
randomContractInteraction,
} = useWeb3Auth();

const loggedInView = (
Expand Down Expand Up @@ -55,6 +56,9 @@ const Main = () => {
<button onClick={signAndSendTokenTransaction} className={styles.card}>
Sign and Send Token Transaction
</button>
<button onClick={randomContractInteraction} className={styles.card}>
Contract Interaction
</button>
<button onClick={logout} className={styles.card}>
Log Out
</button>
Expand Down
12 changes: 12 additions & 0 deletions demo/react-app/src/config/abi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,3 +220,15 @@ export const erc20Abi = [
type: "event",
},
] as const;

export const randomContractAbi = [
{ inputs: [{ internalType: "string", name: "initMessage", type: "string" }], stateMutability: "nonpayable", type: "constructor" },
{ inputs: [], name: "message", outputs: [{ internalType: "string", name: "", type: "string" }], stateMutability: "view", type: "function" },
{
inputs: [{ internalType: "string", name: "newMessage", type: "string" }],
name: "update",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
] as const;
26 changes: 24 additions & 2 deletions demo/react-app/src/services/ethProvider.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { IProvider } from "@web3auth/base";
import Web3 from "web3";
import { IWalletProvider } from "./walletProvider";
import { erc20Abi } from "../config/abi";
import { erc20Abi, randomContractAbi } from "../config/abi";
const tokenAddress = "0x655F2166b0709cd575202630952D71E2bB0d61Af";

const ethProvider = (provider: IProvider, uiConsole: (...args: unknown[]) => void): IWalletProvider => {
Expand Down Expand Up @@ -85,6 +85,19 @@ const ethProvider = (provider: IProvider, uiConsole: (...args: unknown[]) => voi
}
};

const randomContractInteraction = async () => {
try {
const web3 = new Web3(provider as any);
const accounts = await web3.eth.getAccounts();
const contract = new web3.eth.Contract(randomContractAbi, "0x04cA407965D60C2B39d892a1DFB1d1d9C30d0334", { dataInputFill: "data" });
const txRes = await contract.methods.update(`Hello world ${Math.random().toString(36).substring(1, 5)}`).send({ from: accounts[0] });
uiConsole("txRes", txRes);
} catch (error) {
console.log("error", error);
uiConsole("error", error);
}
};

const signTransaction = async () => {
try {
const web3 = new Web3(provider as any);
Expand All @@ -101,7 +114,16 @@ const ethProvider = (provider: IProvider, uiConsole: (...args: unknown[]) => voi
uiConsole("error", error);
}
};
return { getAccounts, getBalance, signMessage, signAndSendTransaction, signTransaction, getTokenBalance, signAndSendTokenTransaction };
return {
getAccounts,
getBalance,
signMessage,
signAndSendTransaction,
signTransaction,
getTokenBalance,
signAndSendTokenTransaction,
randomContractInteraction,
};
};

export default ethProvider;
1 change: 1 addition & 0 deletions demo/react-app/src/services/walletProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export interface IWalletProvider {
signMessage: () => Promise<void>;
getTokenBalance?: () => Promise<void>;
signAndSendTokenTransaction?: () => Promise<void>;
randomContractInteraction?: () => Promise<void>;
}

export const getWalletProvider = (chain: string, provider: IProvider, uiConsole: any): IWalletProvider => {
Expand Down
14 changes: 13 additions & 1 deletion demo/react-app/src/services/web3auth.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ADAPTER_EVENTS, CHAIN_NAMESPACES, IProvider } from "@web3auth/base";
import { Web3Auth } from "@web3auth/modal";
import { OpenloginAdapter } from "@web3auth/openlogin-adapter";
import { TorusWalletConnectorPlugin } from "@web3auth/torus-wallet-connector-plugin";
// import { TorusWalletConnectorPlugin } from "@web3auth/torus-wallet-connector-plugin";
import { createContext, FunctionComponent, ReactNode, useCallback, useContext, useEffect, useState } from "react";
import { CHAIN_CONFIG, CHAIN_CONFIG_TYPE } from "../config/chainConfig";
import { WEB3AUTH_NETWORK_TYPE } from "../config/web3AuthNetwork";
Expand All @@ -25,6 +25,7 @@ export interface IWeb3AuthContext {
switchChain: () => Promise<void>;
getTokenBalance: () => Promise<void>;
signAndSendTokenTransaction: () => Promise<void>;
randomContractInteraction: () => Promise<void>;
}

export const Web3AuthContext = createContext<IWeb3AuthContext>({
Expand All @@ -45,6 +46,7 @@ export const Web3AuthContext = createContext<IWeb3AuthContext>({
switchChain: async () => {},
getTokenBalance: async () => {},
signAndSendTokenTransaction: async () => {},
randomContractInteraction: async () => {},
});

export function useWeb3Auth(): IWeb3AuthContext {
Expand Down Expand Up @@ -297,6 +299,15 @@ export const Web3AuthProvider: FunctionComponent<IWeb3AuthState> = ({ children,
await provider.signAndSendTokenTransaction?.();
};

const randomContractInteraction = async () => {
if (!provider) {
console.log("provider not initialized yet");
uiConsole("provider not initialized yet");
return;
}
await provider.randomContractInteraction?.();
};

const uiConsole = (...args: unknown[]): void => {
const el = document.querySelector("#console>p");
if (el) {
Expand All @@ -322,6 +333,7 @@ export const Web3AuthProvider: FunctionComponent<IWeb3AuthState> = ({ children,
switchChain,
signAndSendTokenTransaction,
getTokenBalance,
randomContractInteraction,
};
return <Web3AuthContext.Provider value={contextProvider}>{children}</Web3AuthContext.Provider>;
};
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export function getProviderHandlers({
message: "Provider is not initialized",
code: 4902,
});
if (txParams.input && !txParams.data) txParams.data = txParams.input;
const signedTx = await signTx(txParams, privKey, txFormatter);
const txHash = await providerEngineProxy.request<[string], string>({
method: "eth_sendRawTransaction",
Expand All @@ -63,6 +64,7 @@ export function getProviderHandlers({
message: "Provider is not initialized",
code: 4902,
});
if (txParams.input && !txParams.data) txParams.data = txParams.input;
const signedTx = await signTx(txParams, privKey, txFormatter);
return `0x${signedTx.toString("hex")}`;
},
Expand Down
2 changes: 1 addition & 1 deletion packages/providers/ethereum-provider/src/rpc/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export interface ExtendedTxData extends TxData {
from: string;
}

export type TransactionParams = ExtendedFeeMarketEIP1559Transaction & ExtendedAccessListEIP2930TxData & ExtendedTxData;
export type TransactionParams = ExtendedFeeMarketEIP1559Transaction & ExtendedAccessListEIP2930TxData & ExtendedTxData & { input?: string };

export interface MessageParams<T> {
from: string;
Expand Down

0 comments on commit 467b0c7

Please sign in to comment.