1

Let's say I have the following struct:

struct Price {
    uint value;
}

Let's say I have the following function:

function isPriceOkay(Price calldata price) public pure returns (bool) {
    return price.value > 10;
}

Is it possible to, from another function, encode a memory/storage to calldata when sending it to another function. Such as in:

function buy() public view returns (bool) {
    Price memory priceData;
    price.value = 10;
    // Maybe do some encoding here?
    return isPriceOkay(priceData); // <-- I wonder if this is possible (in any way)
}

If it is possible, is it possible to do it with nested structs?

2 Answers 2

0

You can instantiate a new Price inline. Is it your concern?

If yes, the example below demonstrates the syntax for that kind of assignment.

However, you'll need to change the function's calldata to memory.

pragma solidity ^0.8.13;

contract Test {

    struct Price {
        uint64 value;
    }
    address private immutable owner;

    constructor() {
        owner = msg.sender;
    }

    modifier auth() {
        require(msg.sender == owner, "You are not authorized to call this function");
        _;
    }

    function mint() external payable auth {
        callInnerFunction(Price({
            value: uint64(msg.value)
        }));

        // do something
    }

    function callInnerFunction(Price memory price) internal {

    }

}
1
  • 1
    Thanks for your answer! My understanding is that when the parameter is calldata, it uses less gas. So my logic was, if I have a function that uses a struct and only reads from it, maybe using it as calldata will require less gas.
    – robeng
    Commented Feb 2 at 16:13
0

No, it is not possible to modify calldata. It is read only from within the same transaction.

To create calldata you could make an external call.

function isPriceOkay(Price calldata price) external pure returns (bool) {
    return price.value > 10;
}

function buy() public view returns (bool) {
    Price memory priceData;
    priceData.value = 10;
    // Maybe do some encoding here?
    return this.isPriceOkay(priceData);
}

You won't be saving anything because you have to pay extra for the external call.

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.