Skip to content

Commit

Permalink
Rewrite the custom types example to use increment example (stellar#142)
Browse files Browse the repository at this point in the history
* Rewrite the custom types example to use increment example

* remove logging to simplify
  • Loading branch information
leighmcculloch authored Oct 8, 2022
1 parent 2b29013 commit 8f9967a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 35 deletions.
47 changes: 26 additions & 21 deletions custom_types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,39 @@
use soroban_sdk::{contractimpl, contracttype, symbol, Env, Symbol};

#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Name {
None,
FirstLast(FirstLast),
#[derive(Clone, Default, Debug, Eq, PartialEq)]
pub struct State {
pub count: u32,
pub last_incr: u32,
}

#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FirstLast {
pub first: Symbol,
pub last: Symbol,
}
const STATE: Symbol = symbol!("STATE");

pub struct CustomTypesContract;

const NAME: Symbol = symbol!("NAME");
pub struct IncrementContract;

#[contractimpl]
impl CustomTypesContract {
pub fn store(env: Env, name: Name) {
env.data().set(NAME, name);
}
impl IncrementContract {
/// Increment increments an internal counter, and returns the value.
pub fn increment(env: Env, incr: u32) -> u32 {
// Get the current count.
let mut state = Self::get_state(env.clone());

pub fn retrieve(env: Env) -> Name {
// Increment the count.
state.count += incr;
state.last_incr = incr;

// Save the count.
env.data().set(STATE, &state);

// Return the count to the caller.
state.count
}
/// Return the current state.
pub fn get_state(env: Env) -> State {
env.data()
.get(NAME) // Get the value associated with key NAME.
.unwrap_or(Ok(Name::None)) // If no value, use None instead.
.unwrap()
.get(STATE)
.unwrap_or_else(|| Ok(State::default())) // If no value set, assume 0.
.unwrap() // Panic if the value of COUNTER is not a State.
}
}

Expand Down
23 changes: 9 additions & 14 deletions custom_types/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,16 @@ use soroban_sdk::Env;
#[test]
fn test() {
let env = Env::default();
let contract_id = env.register_contract(None, CustomTypesContract);
let client = CustomTypesContractClient::new(&env, &contract_id);

assert_eq!(client.retrieve(), Name::None);

client.store(&Name::FirstLast(FirstLast {
first: symbol!("first"),
last: symbol!("last"),
}));
let contract_id = env.register_contract(None, IncrementContract);
let client = IncrementContractClient::new(&env, &contract_id);

assert_eq!(client.increment(&1), 1);
assert_eq!(client.increment(&10), 11);
assert_eq!(
client.retrieve(),
Name::FirstLast(FirstLast {
first: symbol!("first"),
last: symbol!("last"),
}),
client.get_state(),
State {
count: 11,
last_incr: 10
}
);
}

0 comments on commit 8f9967a

Please sign in to comment.