use alloc::vec::Vec;
use soroban_sdk::Env;
use super::error::AccountError;
use super::traits::CougrAccount;
use super::types::GameAction;
pub struct BatchBuilder {
actions: Vec<GameAction>,
}
impl BatchBuilder {
pub fn new() -> Self {
Self {
actions: Vec::new(),
}
}
pub fn add(&mut self, action: GameAction) -> &mut Self {
self.actions.push(action);
self
}
pub fn len(&self) -> usize {
self.actions.len()
}
pub fn is_empty(&self) -> bool {
self.actions.is_empty()
}
pub fn execute<A: CougrAccount>(
self,
env: &Env,
account: &A,
) -> Result<Vec<GameAction>, AccountError> {
if self.actions.is_empty() {
return Err(AccountError::BatchEmpty);
}
for action in &self.actions {
account.authorize(env, action)?;
}
Ok(self.actions)
}
}
impl Default for BatchBuilder {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::accounts::testing::MockAccount;
use soroban_sdk::{symbol_short, Bytes, Env};
#[test]
fn test_batch_builder_new() {
let batch = BatchBuilder::new();
assert!(batch.is_empty());
assert_eq!(batch.len(), 0);
}
#[test]
fn test_batch_builder_add() {
let env = Env::default();
let mut batch = BatchBuilder::new();
batch.add(GameAction {
system_name: symbol_short!("move"),
data: Bytes::new(&env),
});
batch.add(GameAction {
system_name: symbol_short!("attack"),
data: Bytes::new(&env),
});
assert_eq!(batch.len(), 2);
assert!(!batch.is_empty());
}
#[test]
fn test_batch_execute_empty_fails() {
let env = Env::default();
let account = MockAccount::new(&env);
let batch = BatchBuilder::new();
let result = batch.execute(&env, &account);
assert!(matches!(result, Err(AccountError::BatchEmpty)));
}
#[test]
fn test_batch_execute_success() {
let env = Env::default();
let account = MockAccount::new(&env);
let mut batch = BatchBuilder::new();
batch.add(GameAction {
system_name: symbol_short!("move"),
data: Bytes::new(&env),
});
batch.add(GameAction {
system_name: symbol_short!("attack"),
data: Bytes::new(&env),
});
let result = batch.execute(&env, &account);
assert!(result.is_ok());
let actions = result.unwrap();
assert_eq!(actions.len(), 2);
}
}