0

I have a struct that has an array of addresses. When the address array is empty and I try to get index 0 I would expect it to return address(0), but instead it reverts. Any way around this?

struct KeyedMapAddressToBool {
  mapping(address => bool) data;
  mapping(address => uint) indices;
  address[] addresses;
}

function set(KeyedMapAddressToBool storage map, address key, bool value) public {
  map.data[key] = value;
  // THIS REVERTS
  address a = map.addresses[0];
}

EDIT:

I updated my struct to contain an exists mapping, but am wondering if there is another way. This works:

struct KeyedMapAddressToBool {
  mapping(address => bool) data;
  mapping(address => uint) indices;
  address[] addresses;
  mapping(address => bool) exists;
}

function set(KeyedMapAddressToBool storage map, address key, bool value) public {
  map.data[key] = value;
  if (map.exists[key] == false) {
    map.indices[key] = map.addresses.length;
    map.addresses.push(key);
    map.exists[key] = true;
  }
}
QYuQianchen
  • 543
  • 2
  • 8
pizzarob
  • 435
  • 1
  • 5
  • 15

1 Answers1

3

When a dynamic array has .length == 0 you can't access the first row to read or write because it doesn't exist. You can append to it with the push() method or increase with .length++.

map.addresses[0] would only run successfully if length is at least 1.

You may find some ideas to help organize contract state over here: Are there well-solved and simple storage patterns for Solidity?

Hope it helps.

Rob Hitchens
  • 55,151
  • 11
  • 89
  • 145