1
import React, { useEffect, useState } from 'react';
import { ethers } from 'ethers';

import { contractABI, contractAddress } from '../utils/constants';

export const TransactionContext = React.createContext<any>({});

const { ethereum } = window as any;

const getEthereumContract = (): ethers.Contract => {
    console.log(contractAddress)
    console.log(contractABI)

    const provider = new ethers.BrowserProvider(ethereum);
    const signer = provider.getSigner();

    const contract = new ethers.Contract(contractAddress, contractABI, signer);
    console.log(provider, signer, contract)

    return contract;
}

export const TransactionProvider = ({ children }: any) => {

    const [currentAccount, setcurrentAccount] = useState(null);
    const [formData, setFormData] = useState<any>({ addressTo: '', amount: '', keyword: '', message: '' });
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [transactionCount, setTransactionCount] =
        useState<number>(
            parseInt(
                localStorage.getItem('transactionCount') ? localStorage.getItem('transactionCount') as string : '0'
            )
        );

    const checkIfWalletIsConnected = async () => {
        if (!ethereum) {
            return alert('Make sure you have metamask installed!');
        }
        const accounts = await ethereum.request({ method: 'eth_accounts' });

        if (accounts.length) {
            setcurrentAccount(accounts[0]);
        }

    }

    const handleChange = (e: any, name: string) => {
        setFormData((prev: any) => ({ ...prev, [name]: e.target.value }))
        console.log(formData)
    }


    const connectWallet = async () => {
        try {
            if (!ethereum) return alert("Please install metamask")
            const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
            await setcurrentAccount(accounts)
            console.log(currentAccount)
        } catch (error) {
            console.error(error)
            throw new Error("No account found")
        }
    }

    const sendTransaction = async (): Promise<void> => {
        try {
            if (!ethereum) return alert("Please install metamask")
            const {
                addressTo,
                amount,
                keyword,
                message
            } = formData;
            const transactionContract = getEthereumContract()
            const parsedAmount: bigint = ethers.parseEther(amount)
            console.log(currentAccount)
            console.log("--------------")
            console.log(addressTo)

            await ethereum.request({
                method: 'eth_sendTransaction',
                params: [{
                    from: currentAccount,
                    to: addressTo,
                    value: parsedAmount.toString(16),
                    gas: (21000).toString(16),
                }]
            });

            const transactionHash: any = await transactionContract.addToBlockchain(addressTo, parsedAmount, message, keyword);

            setIsLoading(true);
            console.log(`Loading ${transactionHash.hash}`)
            await transactionHash.wait()
            setIsLoading(false);
            console.log(`Done ${transactionHash.hash}`)

            const transactionCount = await transactionContract.getTransactionCount();
            setTransactionCount(transactionCount.toNumber());
            console.log(transactionCount.toNumber())

        } catch (e) {
            console.error(e)
        }
    }

    useEffect(() => {
        checkIfWalletIsConnected();
    })

    return (
        <TransactionContext.Provider value={{
            connectWallet: connectWallet,
            currentAccount: currentAccount,
            formData: formData,
            setFormData: setFormData,
            handleChange: handleChange,
            sendTransaction: sendTransaction,
            isLoading: isLoading,
        }}>
            {children}
        </TransactionContext.Provider>
    )
}

Here I am getting console error, I have double-checked my contract abi's and contract address they are right, but still I am not able to interact with the contract.

Here is the error:

TransactionContext.tsx:103 Error: contract runner does not support sending transactions (operation="sendTransaction", code=UNSUPPORTED_OPERATION, version=6.6.2)
    at makeError (errors.ts:677:21)
    at assert (errors.ts:694:25)
    at send (contract.ts:288:9)
    at Proxy.addToBlockchain (contract.ts:330:22)
    at sendTransaction (TransactionContext.tsx:90:68)
sendTransaction @ TransactionContext.tsx:103
await in sendTransaction (async)
handleSubmit @ Welcome.tsx:53
onClick @ Welcome.tsx:156
callCallback2 @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26140
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
Show 15 more frames
2
  • Did "const signer = await provider.getSigner();" solve your problem? I am getting the same error and not sure where the root cause coming from.
    – Téwa
    Commented Jul 6, 2023 at 23:56
  • I think there are some changes in ethers version 6 method, because when I was passing signer to the contract it was forbidding to take the object, I searched about the method but I was not able to found the answer, then after a lot of searching I deleted ethers version 6 and used old method of ethers version 5.
    – Yana Gupta
    Commented Jul 7, 2023 at 4:36

1 Answer 1

0

Put an await in your signer.

const signer = await provider.getSigner();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.