Search code examples
ethereumblockchainsoliditysmartcontractsremix

The transaction has been reverted to the initial state. The called function should be payable if you send value


the Error being specified is

revert
    The transaction has been reverted to the initial state.
Note: The called function should be payable if you send value and the value you send should be less than your current balance.
Debug the transaction to get more information.
//SPDX-License-Identifier:MIT
pragma solidity 0.8.8;
contract Giftcard{
    event UniqueCardId(uint indexed Id,address indexed owner);
    //Enter The Giftcard amount
    //Pay the gift card by making multiple transations
    //require(giftcard owner should approve the withdrawl )
    address[]  Giftcardowners;
    mapping(address => uint) amountUploaded;
    function Addamount() external payable{
        require(msg.value >= 1 ether,"Gift card amount to small");
        amountUploaded[msg.sender] = msg.value;
        Giftcardowners.push(msg.sender);
        emit UniqueCardId(Giftcardowners.length-1,msg.sender);
    }
    function GetGiftcard(uint _cardId) payable external {
        require(Giftcardowners.length > _cardId,"Id doesnot exits");
        address owner = Giftcardowners[_cardId-1];
        uint amount = amountUploaded[owner];
        require(amount >= 1 ether,"transfered is less than 1 ether");
       // (bool successs,)  = payable(msg.sender).call{value:amount}("");
        //require(successs,"transaction reverted");
        payable(msg.sender).transfer(1 ether);
    }
    function getBalance() external view  returns(uint balance){
        return address(this).balance;
    }
}

Firstly I called the Addamount function by paying more than 1 ether to the smart contract now after that when the GetGiftcard function is called the transaction is reverted. I am unable to find a solution

unable to understand the concept


Solution

  • Error is here

    address owner = Giftcardowners[_cardId-1];
    

    should be

    address owner = Giftcardowners[_cardId];
    

    When you call addAmount, this line executes

      Giftcardowners.push(msg.sender);
    

    in the Giftcardowners array you have only 1 item

    Giftcardowners=[0x7EF2e0048f5bAeDe046f6BF797943daF4ED8CB47]
    

    when you call the GetGiftcard, you need to pass _cardId=0, you are actually assigning the index of the array as the id. when you pass 0, index will be -1 here

    address owner = Giftcardowners[_cardId-1];
    

    You cannot pass 1 to get 1-1=0, because you have this condition

    require(Giftcardowners.length > _cardId,"Id doesnot exits");