0

I'm attempting to write a contract which a variety of classes can inherit that give the inherited class access to various state variables of the child when called by name.

I.e. if parent has a function "food()" which returns 'hamburger', the inherited function is able to access the value of food by calling getAttribute("food()");

I tried to do it like this, but the success variable returns false consistently.

The child contract is as follows inherits from a contract called reader.

pragma solidity >=0.7.0 <0.9.0;
import "./reader.sol";

contract mymain is reader {
    constructor() {
       myAddress=address(this);
    }
    function getName() public pure returns(string memory) {
        return "foo";
    }
    function getFood() public pure returns(string memory) {
        return "hamburger";
    }
}

contract reader { 
    address myAddress;
    function getAttribute(string memory functionName) public view returns(string memory) {
        bytes memory payload = abi.encodePacked(functionName); 
        bool success;
        bytes memory b;
        (success, b)=myAddress.staticcall(payload);
        if (!success) return "failed";
        return(string(b));
    }
}

When I deploy mymain and call mymain.getAttribute("getFood()"); I expect it to return hamburger but it returns failed. I am unfamiliar with the right way to encode the function selector, but obviously doing something wrong.

1
  • I was able to get this work (sort of) by changing abi.encodePacked to abi.encodeWithSignature but I"m not sure why. the bytes array when converted back to a string was padded at the beginning and end with a garbage characters (mostly codePoint 0, but one or two random other unrpintables like 17). If anybody knows why that is it would be helpful.
    – GGizmos
    Commented Apr 7, 2022 at 5:03

1 Answer 1

0

It should be:

bytes memory payload = abi.encodeWithSignature(functionName); 

Instead of:

bytes memory payload = abi.encodePacked(functionName); 

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.