7

I'm trying to call another contract, and return the data - however it's unable to return the correct data (just a string set on the other contract)

pragma solidity ^0.8.0;

contract MyContract {
  address public constant OTHER_CONTRACT = 0x8016619281F888d011c84d2E2a5348d9417c775B;

  event Response(bool success, bytes data);

    function testCall() public returns (bytes memory) {
        (bool success,  bytes memory data) = OTHER_CONTRACT.call{gas: 50000}(abi.encodeWithSignature("greet()"));

        emit Response(success, data);

        return data;
    }
}

I'm testing this on Rinkeby, and I'm wondering if I'm doing something incorrectly here.

This is the contract I'm calling

pragma solidity ^0.8.0;

import "hardhat/console.sol";

contract Greeter {
    string private greeting;

    constructor(string memory _greeting) {
        console.log("Deploying a Greeter with greeting:", _greeting);
        greeting = _greeting;
    }

    function greet() public view returns (string memory) {
        return greeting;
    }

    function setGreeting(string memory _greeting) public {
        console.log("Changing greeting from '%s' to '%s'", greeting, _greeting);
        greeting = _greeting;
    }
}

1 Answer 1

6

It is easier to declare an interface and use it like below.

//Interface name is not important, however functions in it are important
interface GreeterInterface{
  function greet() external view returns (string memory);
  function setGreeting(string memory _greeting) external;
}

contract MyContract {
  address public constant OTHER_CONTRACT = 0x8016619281F888d011c84d2E2a5348d9417c775B;
  GreeterInterface GreeterContract = GreeterInterface(OTHER_CONTRACT);
  
  function testCall() public returns (string memory) {
    //This is example and not related to your contract
    string memory greet = GreeterContract.greet();
    return greet;
  }
}
2
  • Say I want to call the ownerOf function for another contract that inherits for ERC721 - would I just create an interface like ERC721Interface and have ownerOf defined in that interface? Sep 7, 2021 at 22:58
  • Yes! But interface has a little difference with functions. First, you can't call a private or internal function, they just can be call within the contract they are deployed to. Second, you do not use words override and virtual in the interface (It is already virtual). Third, public and internal functions will be changed into external. Sep 7, 2021 at 23:32

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.