Function returns a transaction instead of a string array

Function should return string array but returns instead a transaction

:computer: Environment
@openzeppelin/contracts-upgradeable”: “^4.0.0”,
“truffle”: “^5.3.1”

:memo:Details
This function should return a string array:

function getAttributes(uint256 _token_id) public returns (string[] memory) {
    AttributesStruct[] memory _attributes = attribute[_token_id];
    string[] memory result = new string[](_attributes.length);
    for (uint256 i = 0; i < _attributes.length; i++) {
        result[i] = _attributes[i].value;
    }
    return result;
    //return _attributes;
}

As seen in this test it returns a transaction and the test fails:

it.only(“add properties”, async function () {
//key and value should be a string
await this.GhostmarketNFT.setAttributes(11, [{ key: “bar”, value: “1234” }])
const attributes = await this.GhostmarketNFT.getAttributes(11);
console.log(“attributes:”, attributes)
expect(attributes[11].key).to.be(“bar”);
});

console log shows this:

attributes: {
  tx: '0xb70af8c56a62e9c4611fed9210f7560ffb1e419fc4ea7c2cb7f6059e6173a72c',
  receipt: {
    transactionHash: '0xb70af8c56a62e9c4611fed9210f7560ffb1e419fc4ea7c2cb7f6059e6173a72c',
    transactionIndex: 0,
    blockHash: '0x5b4d412aea78f791d2bdf78fc4a1aa3d0a974a44ba55e123c6010e327a0e190f',
    blockNumber: 516,
    from: '0x1a1122c2483e8f988f9a800f3a6ee316db77e4e0',
    to: '0x0a0a80d2962ec0f239855a0b8ef3418c10c9c3ab',
    gasUsed: 32193,
    cumulativeGasUsed: 32193,
    contractAddress: null,
    logs: [],
    status: true,
    logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
    rawLogs: []
  },
  logs: []
}

fail message from test

add properties:
TypeError: Cannot read property ‘key’ of undefined

:1234: Code to reproduce

Hey! When you send a tx calling a contract, you will always get back the transaction object. The return value of the function is not returned.

This changes if you make a call to the contract, rather than sending a tx to it. To do that, you’ll have to flag the function as view, which you can do in this case (since you’re not modifying your contract’s state in the getter). If you do that, you will just call the contract (rather than sign and send a tx to it, which costs gas fees) and get the return value back!

2 Likes