Skip to content

Commit

Permalink
Make store take a list of (key, value) to "store many" (#1097)
Browse files Browse the repository at this point in the history
* add `store_single` and adapt `store` to take a list of tuples

* merge import

* rename to `store_by_key` and make it a store of a one length array

Co-authored-by: Richard Pringle <richard.pringle@avalabs.org>
Signed-off-by: Franfran <51274081+iFrostizz@users.noreply.github.com>

---------

Signed-off-by: Franfran <51274081+iFrostizz@users.noreply.github.com>
Co-authored-by: Richard Pringle <richard.pringle@avalabs.org>
  • Loading branch information
iFrostizz and richardpringle committed Jul 5, 2024
1 parent a16766a commit 93a9e45
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 52 deletions.
37 changes: 14 additions & 23 deletions x/programs/rust/examples/automated-market-maker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,11 @@ pub fn add_liquidity(context: Context<StateKeys>, amount_x: u64, amount_y: u64)

program
.state()
.store(StateKeys::ReserveX, &(reserve_x + amount_x))
.unwrap();
program
.state()
.store(StateKeys::ReserveY, &(reserve_y + amount_y))
.unwrap();
program
.state()
.store(StateKeys::TotalySupply, &(total_supply + minted))
.store([
(StateKeys::ReserveX, &(reserve_x + amount_x)),
(StateKeys::ReserveY, &(reserve_y + amount_y)),
(StateKeys::TotalySupply, &(total_supply + minted)),
])
.unwrap();

minted
Expand All @@ -57,15 +53,11 @@ pub fn remove_liquidity(context: Context<StateKeys>, shares: u64) -> (u64, u64)

program
.state()
.store(StateKeys::ReserveX, &(reserve_x - amount_x))
.unwrap();
program
.state()
.store(StateKeys::ReserveY, &(reserve_y - amount_y))
.unwrap();
program
.state()
.store(StateKeys::TotalySupply, &(total_supply - shares))
.store([
(StateKeys::ReserveX, &(reserve_x - amount_x)),
(StateKeys::ReserveY, &(reserve_y - amount_y)),
(StateKeys::TotalySupply, &(total_supply - shares)),
])
.unwrap();

(amount_x, amount_y)
Expand Down Expand Up @@ -95,11 +87,10 @@ pub fn swap(context: Context<StateKeys>, amount_in: u64, x_to_y: bool) -> u64 {

program
.state()
.store(StateKeys::ReserveX, &reserve_x)
.unwrap();
program
.state()
.store(StateKeys::ReserveY, &reserve_y)
.store([
(StateKeys::ReserveX, &reserve_x),
(StateKeys::ReserveY, &reserve_y),
])
.unwrap();

out
Expand Down
2 changes: 1 addition & 1 deletion x/programs/rust/examples/counter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub fn inc(context: Context<StateKeys>, to: Address, amount: Count) -> bool {
context
.program()
.state()
.store(StateKeys::Counter(to), &counter)
.store_by_key(StateKeys::Counter(to), &counter)
.expect("failed to store counter");

true
Expand Down
18 changes: 8 additions & 10 deletions x/programs/rust/examples/token/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,19 @@ pub fn init(context: Context<StateKeys>) {
// set total supply
program
.state()
.store(StateKeys::TotalSupply, &INITIAL_SUPPLY)
.store_by_key(StateKeys::TotalSupply, &INITIAL_SUPPLY)
.expect("failed to store total supply");

// set token name
program
.state()
.store(StateKeys::Name, b"WasmCoin")
.store_by_key(StateKeys::Name, b"WasmCoin")
.expect("failed to store coin name");

// set token symbol
program
.state()
.store(StateKeys::Symbol, b"WACK")
.store_by_key(StateKeys::Symbol, b"WACK")
.expect("failed to store symbol");
}

Expand Down Expand Up @@ -76,7 +76,7 @@ fn mint_to_internal(

program
.state()
.store(StateKeys::Balance(recipient), &(balance + amount))
.store_by_key(StateKeys::Balance(recipient), &(balance + amount))
.expect("failed to store balance");

context
Expand Down Expand Up @@ -123,12 +123,10 @@ pub fn transfer(
// update balances
program
.state()
.store(StateKeys::Balance(sender), &(sender_balance - amount))
.expect("failed to store balance");

program
.state()
.store(StateKeys::Balance(recipient), &(recipient_balance + amount))
.store([
(StateKeys::Balance(sender), &(sender_balance - amount)),
(StateKeys::Balance(recipient), &(recipient_balance + amount)),
])
.expect("failed to store balance");

true
Expand Down
43 changes: 26 additions & 17 deletions x/programs/rust/wasmlanche-sdk/src/state.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{memory::HostPtr, state::Error as StateError};
use borsh::{from_slice, to_vec, BorshDeserialize, BorshSerialize};
use borsh::{from_slice, BorshDeserialize, BorshSerialize};
use std::{cell::RefCell, collections::HashMap, hash::Hash};

#[derive(Clone, thiserror::Error, Debug)]
Expand Down Expand Up @@ -38,29 +38,38 @@ impl<'a, K: Key> State<'a, K> {
Self { cache }
}

/// Store a key and value to the host storage. If the key already exists,
/// the value will be overwritten.
/// Store a list of tuple of key and value to the host storage.
/// # Errors
/// Returns an [`Error`] if the key or value cannot be
/// serialized or if the host fails to handle the operation.
pub fn store<V>(self, key: K, value: &V) -> Result<(), Error>
where
V: BorshSerialize,
{
let serialized = to_vec(&value)
.map_err(|_| StateError::Deserialization)
.and_then(|bytes| {
if bytes.is_empty() {
Err(StateError::InvalidByteLength(0))
} else {
Ok(bytes)
}
})?;
self.cache.borrow_mut().insert(key, Some(serialized));
pub fn store<'b, V: BorshSerialize + 'b, Pairs: IntoIterator<Item = (K, &'b V)>>(
self,
pairs: Pairs,
) -> Result<(), Error> {
let cache = &mut self.cache.borrow_mut();

pairs
.into_iter()
.map(|(k, v)| borsh::to_vec(&v).map(|bytes| (k, Some(bytes))))
.try_for_each(|result| {
result.map(|(k, v)| {
cache.insert(k, v);
})
})
.map_err(|_| StateError::Serialization)?;

Ok(())
}

/// Store a key and value to the host storage. If the key already exists,
/// the value will be overwritten.
/// # Errors
/// Returns an [`Error`] if the key or value cannot be
/// serialized or if the host fails to handle the operation.
pub fn store_by_key<V: BorshSerialize>(self, key: K, value: &V) -> Result<(), Error> {
self.store([(key, value)])
}

/// Get a value from the host's storage.
///
/// Note: The pointer passed to the host are only valid for the duration of this
Expand Down
2 changes: 1 addition & 1 deletion x/programs/test/programs/state_access/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub fn put(context: Context<StateKeys>, value: i64) {
context
.program()
.state()
.store(StateKeys::State, &value)
.store_by_key(StateKeys::State, &value)
.expect("failed to store state");
}

Expand Down

0 comments on commit 93a9e45

Please sign in to comment.