rustnearprotocolnear-sdk-rs

How can I insert a key-value pair in an unordered map that is present in the innermost struct in rust programming language?


This is my data model:

pub struct RaffleDetails {
    prize: Balance,
    start: Timestamp,
    end: Timestamp,
    participants: UnorderedMap<AccountId, Balance>,
}


pub struct RaffleDapp {
    raffles: UnorderedMap<AccountId, RaffleDetails>,
}

How can I insert a key-value pair in the 'participants' variable?

I tried self.raffles.get(&raffle_account_id).unwrap().participants.insert(&env::predecessor_account_id(), &confidence); but it's not persistent.

References: UnorderedMap NEAR Rust SDK


Solution

  • You need to make sure you are updating the RaffleDetails instance that is in the map, not a copy/clone of it.

    I'm not familiar with UnorderedMap, but it seems to me the get() method returns a copy of the value that is in the map, so you are only updating the copied value. I don't know if UnorderedMap allows you to mutate a value in it directly (skimming through the docs, I don't see such a method). What you can do though is re-insert the modified RaffleDetails into the raffles map (so as to replace the old one with the modified one).

    I'm talking about something like this (I haven't tested compiling it):

    let o = self.raffles.get(&raffle_account_id);
    if let copied_rd = Some(o) {
        copied_rd.participants.insert(&env::predecessor_account_id(), &confidence);
        self.raffles.insert(&raffle_account_id, &copied_rd);
    }