I am currently learning Solidity language and I've noticed that when I'm trying to get the value of a Struct inside my JS code, Solidity returns every variable without arrays. I have to create custom getter to access all the data inside my struct.
I've made a very simple example of a contract with a Struct initialized inside the constructor.
I'm accessing the variable with my custom getter and generated one inside JS code.
Test.sol
pragma solidity ^0.8.4;
contract Test {
struct Data {
string foo;
address[] bar;
address ctrt;
}
Data public d;
constructor() {
d.foo = "HELLO WORLD";
d.bar.push(msg.sender);
d.ctrt = address(this);
}
function getD() public view returns (Data memory) {
return d;
}
}
Test.js
const {ethers} = require('hardhat');
describe('Test', function () {
it('should test something', async function() {
const factory = await ethers.getContractFactory('Test')
const test = await factory.deploy();
console.log("Result from var:");
console.log(await test.d());
console.log("Result from getter:");
console.log(await test.getD());
})
});
Result in console:
Result from var:
[
'HELLO WORLD',
'0x5FbDB2315678afecb367f032d93F642f64180aa3',
foo: 'HELLO WORLD',
ctrt: '0x5FbDB2315678afecb367f032d93F642f64180aa3'
]
Result from getter:
[
'HELLO WORLD',
[ '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266' ],
'0x5FbDB2315678afecb367f032d93F642f64180aa3',
foo: 'HELLO WORLD',
bar: [ '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266' ],
ctrt: '0x5FbDB2315678afecb367f032d93F642f64180aa3'
]
What is the point to explicitly say that a variable is public if some part of the data is not visible?