0

As you can see here, I have changed HashMap to Mapping.

Then I got a lot of errors like this, does it mean that there is no entry in Mapping? version is bellow ink_storage = { version = "3.3", default-features = false }

error[E0599]: no method named `entry` found for struct `Mapping` in the current scope

method not found in Mapping<ink_env::AccountId, u128> enter image description here

======================

This is within the Withdraw function in AMM. In my case, the bellow code is before I change.

Token1balance = Mapping,Amount of Token1 each user have

amountToken1,2 = withdrawal amount of Token1,2 from pool

        self.token1Balance 
            .entry(caller)
            .and_modify(|val| *val += amountToken1);
        self.token2Balance
            .entry(caller)
            .and_modify(|val| *val += amountToken2);
        Ok((amountToken1, amountToken2))

Does the above code update the token1Balance, which is the amount of tokens held by each user, and add the amoutToken1 that was withdrawn from the pool?

1 Answer 1

2

Correct, you need to read the state variable with .get, modify it and then write the updated result back to contract state with .insert.

Check the details here

So updating an entry from a mapping between a key and a struct would roughly look like:

let old_balance1 = self.token1Balance.get(&caller).unwrap();
self.token1Balance.insert(&caller, &(old_balance1 + amountToken1));
4
  • Thank you very much. How would I describe if I want to update a mapping by adding a specific value to a value that is already in the mapping?
    – Steve
    Oct 10, 2022 at 11:15
  • Updated my answer above with an example.
    – Achim
    Oct 10, 2022 at 12:28
  • Thank you very much. But I don't think I understand it properly. I have updated my question as well.
    – Steve
    Oct 10, 2022 at 14:18
  • I was assuming you mapping's value is a struct. In the referenced case its simpler, I updated my example above. Read the mapping's value to get the old value and then write the new one which depend's on the old value.
    – Achim
    Oct 10, 2022 at 14:54

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.