0

I have some code that attempts to copy an array to mapping:

// Mapping of user addresses to their payment configuration
mapping(address => PaymentConfiguration[]) internal configurations;

// Event to signal that a user's payment configuration has been updated
event ConfigurationUpdated(address user, PaymentConfiguration[] paymentConfigurations);

function updateConfiguration(PaymentConfiguration[] calldata paymentConfigurations) onlyOwner public {
    //TODO: we should probably add validations to assure that payment configuration total percentage doesn't exceed the denominator
    configurations[_msgSender()] = paymentConfigurations;
    emit ConfigurationUpdated(_msgSender(), paymentConfigurations);
}

I believe this issue is caused by the fact that you can't copy an array of structs to memory. Is there a simple way I can replicate this behavior

1 Answer 1

1

Array in storage would have a length field to keep track of the total length of the array. If you're adding entry to storage array, you need to use .push, which will also update the length.

// append only
for (uint i; i < paymentConfigurations.length; ) {
  configurations[_msgSender()].push(paymentConfigurations[i])

  unchecked {
    ++i;
  }
}

You would need to add some logic if you're replacing the old array with the new one: basically if i < length, you overwrite, and if i> length, you push.


If you don't want to keep track of the total length, (if you don't need to iterate through them), it's better to make it a mapping:

// msg.sender => index => config
mapping(address => mapping(uint => PaymentConfiguration)) internal configurations;

So that it would be cheaper to update the storage this way

for (uint i; i < paymentConfigurations.length; ) {

  configurations[_msgSender()][i] = paymentConfigurations[i];

  unchecked {
    ++i;
  }
}
1
  • hmm, this is very similar to what chatGPT told me. I just ended up wrapping the type with another class instead
    – Ritzy Dev
    Jan 2, 2023 at 5:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.