The main issue with your code is that you are trying to return a uint[]
which is an array
, however you defined your variable as a mapping of mappings, and mapping
and array
are different types.
You could get your code to compile like this:
pragma solidity ^0.4.24;
contract test {
mapping (address => uint[]) public transactions;
constructor() public {
transactions[msg.sender].push(123456);
transactions[msg.sender].push(789101);
transactions[msg.sender].push(865436);
}
function getTransactions() public view returns (uint[]) {
return transactions[msg.sender];
}
}
However in general, I would not recommend a single function which returns all the values. While this may be useable in a web front-end, it will not scale as a normal contract function, since eventually you will reach a number of objects in the array where the gas cost to return them all will be too large for the evm.
Instead, I suggest you break it into two functions:
pragma solidity ^0.4.24;
contract test {
mapping (address => uint[]) public transactions;
constructor() public {
transactions[msg.sender].push(123456);
transactions[msg.sender].push(789101);
transactions[msg.sender].push(865436);
}
function getTransactionsLength() public view returns (uint) {
return transactions[msg.sender].length;
}
function getTransactionsValue(uint index) public view returns (uint) {
return transactions[msg.sender][index];
}
}
One is getTransactionsLength()
, and the other is getTransactionsValue()
. Both of these functions return just a single uint, which means you will have predictable output size and gas costs, which means it can be used in other parts of your contract.
Furthermore, you will also create better user experiences by controlling the number of values you are showing. If you need to show all the values, you could first get the length
, and then loop the value call from 0 to length-1
.
But even better, you may only want to show the last 10 transactions in the UI, where then you can loop from length-1 to length-11
. These may seem like complexities at first, but in reality will be simplifications to your dApp is it grows; things you will really come to appreciate from immutable programs :)
The problems is that since solc v0.6.0 userIndex.push(userAddress)
no longer return the length as in previous versions.
You can fix the code with something like this
userIndex.push(userAddress);
userStructs[userAddress].index = userIndex.length - 1;
Best Answer
You're getting that problem because you're trying to search through the indexes of the array using an address which is not valid, you must search using uints. You can however use a pattern to make the index of the address easily retrievable.
Here's a pattern I use to do just this
One thing to note is that this doesn't preserve order in the array, and whatever address you delete will turn into the nu;l address
0x0000000000000000000000000000000000000000