Skip to content

Commit

Permalink
Refactor InitAccount
Browse files Browse the repository at this point in the history
  • Loading branch information
DogLooksGood committed Feb 25, 2024
1 parent 61d938e commit fd04f51
Show file tree
Hide file tree
Showing 44 changed files with 872 additions and 585 deletions.
67 changes: 23 additions & 44 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ members = [
"env",
"client",
"test",
"examples/draw-card",
"examples/simple-settle",
"examples/minimal",
"examples/raffle",
# "examples/draw-card",
# "examples/simple-settle",
# "examples/minimal",
# "examples/raffle",
# "examples/blackjack",
# "examples/roshambo",
# "examples/chat",
Expand Down Expand Up @@ -72,6 +72,7 @@ reqwest = "0.11.16"
openssl = { version = "^0.10" }
prettytable-rs = "^0.10"
sha1 = { version = "0.10.5", default-features = false, features = ["oid"] }
sha256 = "1.5.0"
aes = "0.8.2"
ctr = "0.9.2"
chrono = "0.4.24"
Expand Down
55 changes: 29 additions & 26 deletions api/src/effect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::{
engine::GameHandler,
error::{Error, HandleError, Result},
event::BridgeEvent,
prelude::InitAccount,
random::RandomSpec,
types::{DecisionId, GamePlayer, RandomId, Settle, Transfer},
};
Expand Down Expand Up @@ -42,12 +43,10 @@ pub struct ActionTimeout {
}

#[derive(BorshSerialize, BorshDeserialize, Debug, PartialEq, Eq, Clone)]
pub struct LaunchSubGame {
pub struct SubGame {
pub id: usize,
pub bundle_addr: String,
pub players: Vec<GamePlayer>,
pub init_data: Vec<u8>,
pub checkpoint: Vec<u8>,
pub init_account: InitAccount,
}

#[derive(BorshSerialize, BorshDeserialize, Debug, PartialEq, Eq, Clone)]
Expand All @@ -62,20 +61,25 @@ pub struct SubGameLeave {
pub player_ids: Vec<u64>,
}

impl LaunchSubGame {
impl SubGame {
pub fn try_new<S: BorshSerialize>(
id: usize,
bundle_addr: String,
max_players: u16,
players: Vec<GamePlayer>,
init_data: S,
checkpoint: S,
) -> Result<Self> {
Ok(Self {
id,
bundle_addr,
players,
init_data: init_data.try_to_vec()?,
checkpoint: checkpoint.try_to_vec()?,
init_account: InitAccount {
max_players,
entry_type: crate::types::EntryType::Disabled,
players,
data: init_data.try_to_vec()?,
checkpoint: checkpoint.try_to_vec()?,
},
})
}
}
Expand Down Expand Up @@ -211,7 +215,7 @@ pub struct Effect {
pub error: Option<HandleError>,
pub allow_exit: bool,
pub transfers: Vec<Transfer>,
pub launch_sub_games: Vec<LaunchSubGame>,
pub launch_sub_games: Vec<SubGame>,
pub bridge_events: Vec<EmitBridgeEvent>,
}

Expand Down Expand Up @@ -314,8 +318,13 @@ impl Effect {
self.allow_exit = allow_exit
}

pub fn checkpoint(&mut self) {
self.is_checkpoint = true;
/// Set checkpoint can trigger settlements.
pub fn checkpoint<S: BorshSerialize>(&mut self, checkpoint_state: S) {
if let Ok(checkpoint) = checkpoint_state.try_to_vec() {
self.checkpoint = Some(checkpoint);
} else {
self.error = Some(HandleError::SerializationError)
}
}

/// Submit settlements.
Expand All @@ -333,16 +342,21 @@ impl Effect {
&mut self,
id: usize,
bundle_addr: String,
max_players: u16,
players: Vec<GamePlayer>,
init_data: D,
checkpoint: C,
) -> Result<()> {
self.launch_sub_games.push(LaunchSubGame {
self.launch_sub_games.push(SubGame {
id,
bundle_addr,
players,
init_data: init_data.try_to_vec()?,
checkpoint: checkpoint.try_to_vec()?,
init_account: InitAccount {
max_players,
entry_type: crate::types::EntryType::Disabled,
players,
data: init_data.try_to_vec()?,
checkpoint: checkpoint.try_to_vec()?,
},
});
Ok(())
}
Expand All @@ -368,17 +382,6 @@ impl Effect {
}
}

/// Set checkpoint.
///
/// This is an internal function, DO NOT use in game handler.
pub fn __set_checkpoint<S: BorshSerialize>(&mut self, checkpoint_state: S) {
if let Ok(state) = checkpoint_state.try_to_vec() {
self.checkpoint = Some(state);
} else {
self.error = Some(HandleError::SerializationError);
}
}

pub fn __set_checkpoint_raw(&mut self, raw: Vec<u8>) {
self.checkpoint = Some(raw);
}
Expand Down
32 changes: 8 additions & 24 deletions api/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,14 @@ use crate::{
types::EntryType,
};

/// A subset of on-chain account, used for game handler
/// initialization. The `access_version` may refer to an old state
/// when the game is started by transactor.
#[derive(Debug, Clone, BorshSerialize, BorshDeserialize)]
/// A set of arguments for game handler initialization.
#[derive(Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct InitAccount {
pub addr: String,
pub max_players: u16,
pub entry_type: EntryType,
pub players: Vec<GamePlayer>,
pub data: Vec<u8>,
pub access_version: u64,
pub settle_version: u64,
pub max_players: u16,
pub checkpoint: Vec<u8>,
pub entry_type: EntryType,
}

impl InitAccount {
Expand All @@ -42,7 +37,6 @@ impl InitAccount {
/// This function will panic when a duplicated position is
/// specified.
pub fn add_player(&mut self, id: u64, position: usize, balance: u64) {
self.access_version += 1;
if self.players.iter().any(|p| p.position as usize == position) {
panic!("Failed to add player, duplicated position");
}
Expand All @@ -57,30 +51,20 @@ impl InitAccount {
impl Default for InitAccount {
fn default() -> Self {
Self {
addr: "".into(),
max_players: 0,
entry_type: EntryType::Disabled,
players: Vec::new(),
data: Vec::new(),
access_version: 0,
settle_version: 0,
max_players: 10,
checkpoint: Vec::new(),
entry_type: EntryType::Cash {
min_deposit: 100,
max_deposit: 200,
},
}
}
}

pub trait GameHandler: Sized + BorshSerialize + BorshDeserialize {
type Checkpoint: BorshSerialize + BorshDeserialize;

/// Initialize handler state with on-chain game account data.
/// Initialize handler state with on-chain game account data. The
/// initial state must be determined by the `init_account`.
fn init_state(effect: &mut Effect, init_account: InitAccount) -> HandleResult<Self>;

/// Handle event.
fn handle_event(&mut self, effect: &mut Effect, event: Event) -> HandleResult<()>;

/// Create checkpoint from current state.
fn into_checkpoint(self) -> HandleResult<Self::Checkpoint>;
}
3 changes: 3 additions & 0 deletions api/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@ pub enum Error {

#[error("Cannot bump settle version")]
CantBumpSettleVersion,

#[error("Game uninitialized")]
GameUninitialized,
}

#[cfg(feature = "serde")]
Expand Down
2 changes: 2 additions & 0 deletions api/src/types/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,8 @@ pub enum EntryType {
/// A player can join the game by showing a gate NFT
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
Gating { collection: String },
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
Disabled,
}

impl Default for EntryType {
Expand Down
1 change: 1 addition & 0 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,7 @@ async fn main() {

println!("Interact with chain: {:?}", chain);
println!("RPC Endpoint: {:?}", rpc);
println!("Specified keyfile: {:?}", keyfile);

match matches.subcommand() {
Some(("publish", sub_matches)) => {
Expand Down
Loading

0 comments on commit fd04f51

Please sign in to comment.