I have an issue with my code, I want to create a function to be able to Mint a token, and add a struct to represent all attributes of this token.
The issue is, I have lot's of args on my function (8) and I have to compute new local variables (2) in the function (like tokenId)..
I know that the maximum stack for local variables are 16 or 17 but in my case I have less then that (If i understand well, I have 10).. So it not should be an issue ? (See: Error while compiling: Stack too deep)
I also learn about Diamond Cut paterns who consist to create sub struct, but in my case it'll only create more local variable to create sub-struct. (See Blog Post)
I also ear it's not a good practice to put Struct as function argument, so it's possible to have a function who create a struct with that much arguments or it's just impossible with current version of Solidity (0.8.12) ??
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
struct TokenData {
uint tokenId;
uint16 familyId;
uint familySupplyIdx;
uint8 typeId;
uint16 evoId;
uint32 colorId;
uint16[] traitIds;
uint16[4] specsIds;
uint32 itemId;
uint valueA;
uint valueB;
uint16[] buffIds;
address lockedBy;
}
function mint(uint16 _familyId, uint8 _typeId, uint16 _evoId, uint32 _colorId, uint16[] memory _traitIds, uint16[4] memory _specsIds, uint _valueA, uint _valueB) public onlyAllowed onlyWithTag('Mint') onlyValidFamily(_familyId) {
uint _familySupplyIdx = supply[_familyId]; // get Current Supply for selected family
uint _tokenId = _getTokenId(_familyId, _familySupplyIdx);
// Add to Storage data
TokenData memory tdata = TokenData(
_tokenId,
_familyId, // <- Following error point here
_familySupplyIdx,
_typeId,
_evoId,
_colorId,
_traitIds,
_specsIds,
0,
_valueA,
_valueB,
new uint16[](0),
address(0x0)
);
tokensDatas[_tokenId] = tdata;
// Finally Mint it
_safeMint(msg.sender, _tokenId);
// Once minted, update supply
_incrementSupply(_familyId);
}
But I got this error:
CompilerError: Stack too deep, try removing local variables.
--> contracts/TokenData.sol:120:7:
|
120 | _familyId,
| ^^^^^^^^^
In addition, I don't understand why the stack error is referring to an existing local variables. The code isn't creating a new local variable here, so why do this cause an error ??
uint[] memory _args, and them create the struct by casting every args:new TokenData( uint16(_args[0]), uint8(_args[1]), .... And it's working.. Do you solution is better (More readable, avoid casting) or mine is better (Avoid custom struct) ? – Arthur Dec 02 '22 at 18:43Alternatively, you could consider using a different data structure, such as an array or a map, to store your data. This can make your code more flexible and easier to work with.
Ultimately, the best solution will depend on the specific requirements of your program and the context in which it is being used.
– VX3 Dec 02 '22 at 21:30