0

I'm getting a console error in hardhat test case this is my solidity code

/**
 * donateToCampaign - Allows a user to donate to a specific campaign.
 *
 * @param _id the ID of the campaign to donate to.
 */
function donateToCampaign(uint256 _id) public payable noReentrancy {
    uint256 amount = msg.value;

    Campaign storage campaign = campaigns[_id];

    require(
        campaign.status != CampaignStatus.Close,
        "This campaign is not open to fund."
    );

    require(
        campaign.deadline > block.timestamp &&
            isCampaignOpen(campaign.status),
        "The campaign is not open or has reached its goal."
    );

    require(
        campaign.amountCollected + amount <= campaign.target,
        "Donation exceeds campaign target."
    );

    campaign.amountCollected += amount;
    campaign.donators.push(payable(msg.sender));
    campaign.donations.push(amount);

    if (campaign.amountCollected == campaign.target) {
        campaign.status = CampaignStatus.Successful;
        emit CampaginSuccessfullyFunded(campaign);
    }

    payable(address(this)).transfer(amount);
}

and the test case in hardhat using chai

 it("should allow a user to donate to a campaign", async () => {
const target = ethers.utils.parseEther("1");
await contract.connect(aliceAccount).createCampaign(
  "Test Campaign",
  "Test Description",
  target,
  "testimage.jpg"
);
let cc = await contract.campaigns(0);
const tx = await contract
  .connect(bobAccount)
  .donateToCampaign(0, { value: ethers.utils.parseEther("0.5") });
const campaign = await contract.campaigns(0);
expect(campaign.amountCollected).to.equal(ethers.utils.parseEther("0.5"));

});

3 Answers 3

1

You do not need to transfer the value if the value is sent in a payable method No need: payable(address(this)).transfer(amount)

If you really want to use this then you have to define a fallback function to receive ether.

Eg.

........
receive() payable external {}
........

Fallback function is necessary to receive any amount of ether. Otherwise you can not send ether to the smart contract using wallet like metamask.

1

I believe the error comes from the last line of your function.

payable(address(this)).transfer(amount); // Also why tf are you doing that?

Here, your contract is trying to call its own fallback ( or receive) function, if it doesnt exist, the whole call would revert with this error message.

Also, unrelated, but why are you using a nonReentrant modifier inside a function that doesn't make any external calls?

0

Update the smart contract address after deployment in your tests. It seems like the contract address is hardcoded.

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.