Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modified game and player account creation endpoints for frontend integration #21

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
3 changes: 2 additions & 1 deletion .github/workflows/run-integration-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ name: Run Aze integration Tests on PR
on:
pull_request:
branches:
- main
- main
- develop

jobs:
test:
Expand Down
1 change: 1 addition & 0 deletions lib/src/constants/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub const DEFAULT_AUTH_SCRIPT: &str =

pub const CLIENT_CONFIG_FILE_NAME: &str = "miden-client.toml";
pub const BUY_IN_AMOUNT: u64 = 1000;
pub const SMALL_BUY_IN_AMOUNT: u8 = 100;
pub const TRANSFER_AMOUNT: u64 = 59;
pub const SMALL_BLIND_AMOUNT: u8 = 5;
pub const PLAYER_INITIAL_BALANCE: u8 = 30;
Expand Down
152 changes: 124 additions & 28 deletions lib/src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,37 +1,45 @@
use miden_objects::{
accounts::{ Account, AccountCode, AccountId, AccountStorage, SlotItem },
assembly::{ ModuleAst, ProgramAst },
assets::{ Asset, AssetVault, FungibleAsset },
accounts::{Account, AccountCode, AccountId, AccountStorage, SlotItem},
assembly::{ModuleAst, ProgramAst},
assets::{Asset, AssetVault, FungibleAsset, TokenSymbol},
crypto::{
dsa::rpo_falcon512::SecretKey,
rand::{FeltRng, RpoRandomCoin},
utils::Serializable,
rand::FeltRng,
rand::RpoRandomCoin,
},
notes::{ Note, NoteId, NoteScript },
notes::{Note, NoteId, NoteScript, NoteType},
transaction::{
ChainMmr,
ExecutedTransaction,
InputNote,
InputNotes,
ProvenTransaction,
TransactionInputs,
ChainMmr, ExecutedTransaction, InputNote, InputNotes, ProvenTransaction, TransactionInputs,
},
BlockHeader,
Felt,
Word,
BlockHeader, Felt, Word,
};

use crate::{
client::{AzeAccountTemplate, AzeClient, AzeGameMethods},
constants::{
BUY_IN_AMOUNT, CURRENT_TURN_INDEX_SLOT, HIGHEST_BET, NO_OF_PLAYERS, PLAYER_INITIAL_BALANCE,
SMALL_BLIND_AMOUNT, SMALL_BUY_IN_AMOUNT,
},
notes::{consume_notes, mint_note},
storage::GameStorageSlotData,
};
use ::rand::Rng;
use figment::{
providers::{Format, Toml},
Figment,
};
use std::{ env::temp_dir, fs, time::Duration };
use miden_client::{
client::{ rpc::NodeRpcClient, Client },
client::{
accounts::{AccountStorageMode, AccountTemplate},
rpc::NodeRpcClient,
Client,
},
config::ClientConfig,
errors::{ ClientError, NoteIdPrefixFetchError },
store::{ sqlite_store::SqliteStore, InputNoteRecord, NoteFilter as ClientNoteFilter, Store },
errors::{ClientError, NoteIdPrefixFetchError},
store::{sqlite_store::SqliteStore, InputNoteRecord, NoteFilter as ClientNoteFilter, Store},
};
use std::path::Path;
use figment::{ providers::{ Format, Toml }, Figment };
use ::rand::Rng;
use crate::client::AzeClient;
use std::{env::temp_dir, fs, time::Duration};

// use uuid::Uuid;

Expand All @@ -57,7 +65,12 @@ pub fn create_aze_store_path() -> std::path::PathBuf {
pub fn load_config(config_file: &Path) -> Result<ClientConfig, String> {
Figment::from(Toml::file(config_file))
.extract()
.map_err(|err| format!("Failed to load {} config file: {err}", config_file.display()))
.map_err(|err| {
format!(
"Failed to load {} config file: {err}",
config_file.display()
)
})
}

pub fn get_random_coin() -> RpoRandomCoin {
Expand All @@ -71,15 +84,98 @@ pub fn get_random_coin() -> RpoRandomCoin {
// TODO hide this methods under debug feature
pub async fn log_account_status(client: &AzeClient, account_id: AccountId) {
let (regular_account, _seed) = client.get_account(account_id).unwrap();
println!("Account asset count --> {:?}", regular_account.vault().assets().count());
println!("Account storage root --> {:?}", regular_account.storage().root());
println!("Account slot 100 --> {:?}", regular_account.storage().get_item(100));
println!("Account slot 101 --> {:?}", regular_account.storage().get_item(101));
println!(
"Account asset count --> {:?}",
regular_account.vault().assets().count()
);
println!(
"Account storage root --> {:?}",
regular_account.storage().root()
);
println!(
"Account slot 100 --> {:?}",
regular_account.storage().get_item(100)
);
println!(
"Account slot 101 --> {:?}",
regular_account.storage().get_item(101)
);
}

pub async fn log_slots(client: &AzeClient, account_id: AccountId) {
let (regular_account, _seed) = client.get_account(account_id).unwrap();
for i in 1..100 {
println!("Account slot {:?} --> {:?}", i, regular_account.storage().get_item(i));
println!(
"Account slot {:?} --> {:?}",
i,
regular_account.storage().get_item(i)
);
}
}

pub async fn setup_accounts(
mut client: &mut AzeClient,
) -> (FungibleAsset, AccountId, AccountId, GameStorageSlotData) {
let slot_data = GameStorageSlotData::new(
SMALL_BLIND_AMOUNT,
SMALL_BUY_IN_AMOUNT,
NO_OF_PLAYERS,
CURRENT_TURN_INDEX_SLOT,
HIGHEST_BET,
PLAYER_INITIAL_BALANCE,
);

let (game_account, _) = client
.new_game_account(
AzeAccountTemplate::GameAccount {
mutable_code: false,
storage_mode: AccountStorageMode::Local, // for now
},
Some(slot_data.clone()),
)
.unwrap();
let game_account_id = game_account.id();
log_slots(&client, game_account_id).await;

let (player_account, _) = client
.new_game_account(
AzeAccountTemplate::PlayerAccount {
mutable_code: false,
storage_mode: AccountStorageMode::Local, // for now
},
None,
)
.unwrap();
let player_account_id = player_account.id();

let (faucet_account, _) = client
.new_account(AccountTemplate::FungibleFaucet {
token_symbol: TokenSymbol::new("MATIC").unwrap(),
decimals: 8,
max_supply: 1_000_000_000,
storage_mode: AccountStorageMode::Local,
})
.unwrap();
let faucet_account_id = faucet_account.id();

let note = mint_note(
&mut client,
player_account_id,
faucet_account_id,
NoteType::Public,
)
.await;
println!("Minted note");
consume_notes(&mut client, player_account_id, &[note]).await;

let fungible_asset = FungibleAsset::new(faucet_account_id, BUY_IN_AMOUNT).unwrap();
let sender_account_id = player_account_id;
let target_account_id = game_account_id;

return (
fungible_asset,
sender_account_id,
target_account_id,
slot_data,
);
}
34 changes: 11 additions & 23 deletions node/src/api/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,15 @@ use aze_lib::storage::GameStorageSlotData;

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please don't raise pr from develop. We will only raise pr from develop once the feature is quite well tested.

use aze_types::accounts::{
AccountCreationError,
AccountCreationRequest,
AccountCreationResponse,
PlayerAccountCreationRequest,
PlayerAccountCreationResponse,
};
use aze_lib::utils::log_account_status;
use miden_lib::AuthScheme;
use miden_objects::{
accounts:: AccountId,
assets::TokenSymbol,
assets::{ Asset, FungibleAsset },
crypto::dsa::rpo_falcon512::{ PublicKey, SecretKey },
Expand All @@ -31,28 +34,17 @@ use miden_client::client::{
transactions::transaction_request::TransactionTemplate,
};

use actix_web::{ get, web::Json };
use actix_web::{ get, post, web::Json };

// TODO: pass account id of the players as request object in this game
#[get("/v1/game/create-account")]
pub async fn create_aze_game_account() -> Result<
#[post("/v1/game/create-account")]
pub async fn create_aze_game_account(request_object: Json<AccountCreationRequest>) -> Result<
Json<AccountCreationResponse>,
AccountCreationError
> {
let mut client: AzeClient = create_aze_client();
let slot_data = GameStorageSlotData::new(0, 0, 0, 0, 0, 0);

// TODO: creating player just for testing purposes
let (player_account, _) = client
.new_game_account(
AzeAccountTemplate::PlayerAccount {
mutable_code: false,
storage_mode: AccountStorageMode::Local, // for now
},
None
)
.unwrap();

let (faucet_account, _) = client
.new_account(AccountTemplate::FungibleFaucet {
token_symbol: TokenSymbol::new("MATIC").unwrap(),
Expand All @@ -66,7 +58,7 @@ pub async fn create_aze_game_account() -> Result<
let fungible_asset = FungibleAsset::new(faucet_account_id, BUY_IN_AMOUNT).unwrap();

// TODO: get the player account ids from the request object
let player_account_ids = vec![player_account.id()];
let player_account_ids = request_object.game_player_ids.clone();

let (game_account, _) = client
.new_game_account(
Expand Down Expand Up @@ -102,11 +94,9 @@ pub async fn create_aze_game_account() -> Result<

println!("Start sending cards to players");
for (i, _) in player_account_ids.iter().enumerate() {
let target_account_id = player_account_ids[i];
let target_account_id = AccountId::try_from(player_account_ids[i]).unwrap();
println!("Target account id {:?}", target_account_id);

log_account_status(&client, target_account_id).await;

let input_cards = [cards[i], cards[i + 1]];
let sendcard_txn_data = SendCardTransactionData::new(
Asset::Fungible(fungible_asset),
Expand All @@ -128,15 +118,14 @@ pub async fn create_aze_game_account() -> Result<
execute_tx_and_sync(&mut client, tx_request).await;

println!("Executed and synced with node");
log_account_status(&client, target_account_id).await;
}

// TODO: define appropriate response types
Ok(Json(AccountCreationResponse { is_created: true }))
Ok(Json(AccountCreationResponse { game_id: game_account_id.into() }))
}

#[get("/v1/player/create-account")]
pub async fn create_aze_player_account() -> Result<
#[post("/v1/player/create-account")]
pub async fn create_aze_player_account(request_object: Json<PlayerAccountCreationRequest>) -> Result<
Json<PlayerAccountCreationResponse>,
AccountCreationError
> {
Expand All @@ -160,7 +149,6 @@ pub async fn create_aze_player_account() -> Result<

Ok(
Json(PlayerAccountCreationResponse {
is_created: true,
account_id: game_account.id().into(),
})
)
Expand Down
Loading
Loading