adrianhajdin / project_crowdfunding

With a stunning design, connected to the blockchain, metamask pairing, interaction with smart contracts, sending Ethereum through the blockchain network, and writing solidity code.
https://jsmastery.pro
709 stars 382 forks source link

contract call failed TypeError: Cannot read properties of undefined (reading 'call') at Object.mutationFn (useTransactions-a28ed134.browser.esm.js:2926:21) at Object.fn (mutation.ts:179:31) at run (retryer.ts:147:31) at createRetryer (retryer.ts:204:5) at executeMutation (mutation.ts:174:22) at Mutation.execute (mutation.ts:216:26) at async publishCampaign (index.jsx:18:20) at async CreateCampaign.jsx:33:9 #63

Open gyan-sy opened 1 year ago

Mosqu1to3zZ commented 1 year ago

Post your code!

gyan-sy commented 1 year ago

Post your code! index.jsx file

import React, { useContext, createContext } from 'react';

import { useAddress, useContract, useMetamask, useContractWrite } from '@thirdweb-dev/react'; import { ethers } from 'ethers'; import { EditionMetadataWithOwnerOutputSchema } from '@thirdweb-dev/sdk';

const StateContext = createContext();

export const StateContextProvider = ({ children }) => { const { contract } = useContract('0xf59A1f8251864e1c5a6bD64020e3569be27e6AA9'); const { mutateAsync: createCampaign } = useContractWrite(contract, 'createCampaign');

const address = useAddress(); const connect = useMetamask();

const publishCampaign = async (form) => { try { const data = await createCampaign({ args: [ address, // owner form.title, // title form.description, // description form.target, new Date(form.deadline).getTime(), // deadline, form.image, ], });

  console.log("contract call success", data)
} catch (error) {
  console.log("contract call failure", error)
}

}

const getCampaigns = async () => { const campaigns = await contract.call('getCampaigns');

const parsedCampaings = campaigns.map((campaign, i) => ({
  owner: campaign.owner,
  title: campaign.title,
  description: campaign.description,
  target: ethers.utils.formatEther(campaign.target.toString()),
  deadline: campaign.deadline.toNumber(),
  amountCollected: ethers.utils.formatEther(campaign.amountCollected.toString()),
  image: campaign.image,
  pId: i
}));

return parsedCampaings;

}

const getUserCampaigns = async () => { const allCampaigns = await getCampaigns();

const filteredCampaigns = allCampaigns.filter((campaign) => campaign.owner === address);

return filteredCampaigns;

}

const donate = async (pId, amount) => { const data = await contract.call('donateToCampaign', [pId], { value: ethers.utils.parseEther(amount)});

return data;

}

const getDonations = async (pId) => { const donations = await contract.call('getDonators', [pId]); const numberOfDonations = donations[0].length;

const parsedDonations = [];

for(let i = 0; i < numberOfDonations; i++) {
  parsedDonations.push({
    donator: donations[0][i],
    donation: ethers.utils.formatEther(donations[1][i].toString())
  })
}

return parsedDonations;

}

return ( <StateContext.Provider value={{ address, contract, connect, createCampaign: publishCampaign, getCampaigns, getUserCampaigns, donate, getDonations }}

{children} </StateContext.Provider> ) }

export const useStateContext = () => useContext(StateContext);

Mosqu1to3zZ commented 1 year ago

const data = await createCampaign( [ address, // owner form.title, // title form.description, // description form.target, new Date(form.deadline).getTime(), // deadline, form.image, ]);

iamashruu commented 1 year ago

// update your code with this. For me it's working const address = useAddress(); const connect = useMetamask(); if (address == 'undefined') { connect(); }

gyan-sy commented 1 year ago

Still its showing same error

aadarsh-nagrath commented 1 year ago

Yes @gyan-sy I am facing the same problem in this. I have tried Changing to Sepolia But this is the exact error irritating me. Have you got any solution ?

harshbaid-13 commented 12 months ago

@aadarsh-nagrath have you got any solution?

aadarsh-nagrath commented 12 months ago

@aadarsh-nagrath have you got any solution?

Yeah, I did solved all errors and shifted it to Polygon U can check it here -> https://github.com/aadarsh-nagrath/Web3.0_App.git

Client and web3 directory will be useful to you; there is doc ... but I guess you already know how to setup a project.

AliyaAkhtar commented 11 months ago

@aadarsh-nagrath Isn't there any other way of resolving this error. Is it necessary to shift to the polygon. Can't this error be resolved with Goerli

aadarsh-nagrath commented 11 months ago

@aadarsh-nagrath Isn't there any other way of resolving this error. Is it necessary to shift to the polygon. Can't this error be resolved with Goerli

It can be; mine works for all networks. Error needs to be solved. The network can be any regardless.

AliyaAkhtar commented 11 months ago

@aadarsh-nagrath Can you tell me what how you have resolved the error. Following is my index.jsx code.

import React, { useContext, createContext } from 'react';

import { useAddress, useContract, useMetamask, useContractWrite } from '@thirdweb-dev/react'; import { ethers } from 'ethers'; import { EditionMetadataWithOwnerOutputSchema } from '@thirdweb-dev/sdk';

const StateContext = createContext();

export const StateContextProvider = ({ children }) => { const { contract } = useContract('0x4bE731B4CF15F13F2fCc8f2652D78f9C9b248214'); const { mutateAsync: createCampaign } = useContractWrite(contract, 'createCampaign');

const address = useAddress();
const connect = useMetamask();

const publishCampaign = async (form) => {
    try {
        const data = await createCampaign({
            args: [
                address, // owner
                form.title, // title
                form.description, // description
                form.target,
                new Date(form.deadline).getTime(), // deadline,
                form.image,
            ],
        });

        console.log("contract call success", data)
    } catch (error) {
        console.log("contract call failure", error)
    }
}

const getCampaigns = async () => {
    const campaigns = await contract.call('getCampaigns');

    //console.log(campaigns);

    const parsedCampaings = campaigns.map((campaign, i) => ({
        owner: campaign.owner,
        title: campaign.title,
        description: campaign.description,
        target: ethers.utils.formatEther(campaign.target.toString()),
        deadline: campaign.deadline.toNumber(),
        amountCollected: ethers.utils.formatEther(campaign.amountCollected.toString()),
        image: campaign.image,
        pId: i
    }));

    //console.log(parsedCampaings);

    return parsedCampaings;
}

const getUserCampaigns = async () => {
    const allCampaigns = await getCampaigns();

    const filteredCampaigns = allCampaigns.filter((campaign) => campaign.owner === address);

    return filteredCampaigns;
}

const donate = async (pId, amount) => {
    const data = await contract.call('donateToCampaign', [pId], { value: ethers.utils.parseEther(amount) });

    return data;
}

const getDonations = async (pId) => {
    const donations = await contract.call('getDonators', [pId]);
    const numberOfDonations = donations[0].length;

    const parsedDonations = [];

    for (let i = 0; i < numberOfDonations; i++) {
        parsedDonations.push({
            donator: donations[0][i],
            donation: ethers.utils.formatEther(donations[1][i].toString())
        })
    }

    return parsedDonations;
}

return (
    <StateContext.Provider
        value={{
            address,
            contract,
            connect,
            createCampaign: publishCampaign,
            getCampaigns,
            getUserCampaigns,
            donate,
            getDonations
        }}
    >
        {children}
    </StateContext.Provider>
)

}

export const useStateContext = () => useContext(StateContext);

Following is my CreatCampaign code

import React, { useState } from 'react' import { useNavigate } from 'react-router-dom'; import { ethers } from 'ethers';

import { useStateContext } from '../context'; import { money } from '../assets'; import { CustomButton, FormField, Loader } from '../components'; import { checkIfImage } from '../utils';

const CreateCampaign = () => { const navigate = useNavigate(); const [isLoading, setIsLoading] = useState(false); const { createCampaign } = useStateContext(); const [form, setForm] = useState({ name: '', title: '', description: '', target: '', deadline: '', image: '' });

const handleFormFieldChange = (fieldName, e) => {
    setForm({ ...form, [fieldName]: e.target.value })
}

const handleSubmit = async (e) => {
    e.preventDefault();

    console.log(form);

    checkIfImage(form.image, async (exists) => {
        if (exists) {
            setIsLoading(true)
            await createCampaign({ ...form, target: ethers.utils.parseUnits(form.target, 18) })
            setIsLoading(false);
            navigate('/');
        } else {
            alert('Provide valid image URL')
            setForm({ ...form, image: '' });
        }
    })
}

return (
    <div className="bg-[#1c1c24] flex justify-center items-center flex-col rounded-[10px] sm:p-10 p-4">
        {isLoading && <Loader />}
        <div className="flex justify-center items-center p-[16px] sm:min-w-[380px] bg-[#3a3a43] rounded-[10px]">
            <h1 className="font-epilogue font-bold sm:text-[25px] text-[18px] leading-[38px] text-white">Start a Campaign</h1>
        </div>

        <form onSubmit={handleSubmit} className="w-full mt-[65px] flex flex-col gap-[30px]">
            <div className="flex flex-wrap gap-[40px]">
                <FormField
                    labelName="Your Name *"
                    placeholder="John Doe"
                    inputType="text"
                    value={form.name}
                    handleChange={(e) => handleFormFieldChange('name', e)}
                />
                <FormField
                    labelName="Campaign Title *"
                    placeholder="Write a title"
                    inputType="text"
                    value={form.title}
                    handleChange={(e) => handleFormFieldChange('title', e)}
                />
            </div>

            <FormField
                labelName="Story *"
                placeholder="Write your story"
                isTextArea
                value={form.description}
                handleChange={(e) => handleFormFieldChange('description', e)}
            />

            <div className="w-full flex justify-start items-center p-4 bg-[#8c6dfd] h-[120px] rounded-[10px]">
                <img src={money} alt="money" className="w-[40px] h-[40px] object-contain" />
                <h4 className="font-epilogue font-bold text-[25px] text-white ml-[20px]">You will get 100% of the raised amount</h4>
            </div>

            <div className="flex flex-wrap gap-[40px]">
                <FormField
                    labelName="Goal *"
                    placeholder="ETH 0.50"
                    inputType="text"
                    value={form.target}
                    handleChange={(e) => handleFormFieldChange('target', e)}
                />
                <FormField
                    labelName="End Date *"
                    placeholder="End Date"
                    inputType="date"
                    value={form.deadline}
                    handleChange={(e) => handleFormFieldChange('deadline', e)}
                />
            </div>

            <FormField
                labelName="Campaign image *"
                placeholder="Place image URL of your campaign"
                inputType="url"
                value={form.image}
                handleChange={(e) => handleFormFieldChange('image', e)}
            />

            <div className="flex justify-center items-center mt-[40px]">
                <CustomButton
                    btnType="submit"
                    title="Submit new campaign"
                    styles="bg-[#1dc071]"
                />
            </div>
        </form>
    </div>
)

}

export default CreateCampaign

I checked your code as well but didnot find any thing that is nto mentioned in my code. To me yours an d mine code looks to be same. Please help me out with this.