Skip to content
Merged
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
8 changes: 8 additions & 0 deletions .cargo/mutants.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,11 @@
# Tests, examples and build scripts aren't product code; the crate's own tests
# run for every change in its src.
examine_globs = ["crates/*/src/**/*.rs"]

# Mutants no test can tell apart from the real code.
exclude_re = [
# crates/timba-protocol/src/events.rs: the first invocation puts the same extra empty frames
# under every later frame, so cutting the stack at `depth + 1` or `depth` instead of
# `depth - 1` keeps the same top frame. Only the top frame decides what is trusted.
"replace - with [+/] in get_trusted_program_data$",
]
2 changes: 1 addition & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ resolver = "2"

[workspace.package]
# Matches package.json, so a crate and npm release share one protocol version.
version = "0.18.3"
version = "0.18.4"
edition = "2021"
rust-version = "1.85"
license = "AGPL-3.0-only"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ The crate is not on crates.io. Depend on a release tag, adding `features = ["evm

```toml
[dependencies]
timba-protocol = { git = "https://github.com/timbagame/protocol", tag = "v0.18.3" }
timba-protocol = { git = "https://github.com/timbagame/protocol", tag = "v0.18.4" }
```

Its version always matches `package.json`, and it needs Rust 1.85 or newer. Two differences from TypeScript: amounts are `u128` (larger values fail with the `range` code), and the `http` module validates JSON values (`schema::parse` returns the same output zod would) but has no typed REST client.
Expand Down
4 changes: 2 additions & 2 deletions crates/timba-protocol/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ publish.workspace = true

[features]
# EVM contract v0.1.0 (alloy bindings, typed data, events and HTTP validation).
evm = ["dep:alloy-primitives", "dep:alloy-sol-types", "dep:anyhow"]
evm = ["dep:alloy-primitives", "dep:alloy-sol-types", "dep:anyhow", "dep:hex"]

[dependencies]
alloy-primitives = { workspace = true, optional = true }
Expand All @@ -19,7 +19,7 @@ anyhow = { workspace = true, optional = true }
base64.workspace = true
bs58.workspace = true
curve25519-dalek.workspace = true
hex.workspace = true
hex = { workspace = true, optional = true }
regex.workspace = true
serde.workspace = true
serde_json.workspace = true
Expand Down
7 changes: 6 additions & 1 deletion crates/timba-protocol/src/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ impl Address {

/// Mirrors `@solana/kit` `isAddress`: 32-44 base58 characters decoding to 32 bytes.
pub fn parse(value: &str) -> Result<Self, AddressError> {
if value.len() < 32 || value.len() > 44 {
// The length check also keeps long text away from the quadratic base58 decode.
if !(32..=44).contains(&value.len()) {
return Err(AddressError::Invalid(value.to_string()));
}
let decoded = bs58::decode(value).into_vec().map_err(|_| AddressError::Invalid(value.to_string()))?;
Expand Down Expand Up @@ -268,6 +269,10 @@ mod tests {
// find_program_address reserves one seed slot for the bump.
let seeds: Vec<&[u8]> = vec![b"s"; MAX_SEEDS];
assert_eq!(Address::find_program_address(&seeds, &program), Err(AddressError::InvalidSeeds));
// The limits themselves are allowed: only an on-curve result can fail.
assert_ne!(Address::create_program_address(&seeds, &program), Err(AddressError::InvalidSeeds));
let longest = [0u8; MAX_SEED_LENGTH];
assert_ne!(Address::create_program_address(&[&longest], &program), Err(AddressError::InvalidSeeds));
assert_eq!(Address::find_program_address(&[&long], &program), Err(AddressError::InvalidSeeds));

let (pda, bump) = Address::find_program_address(&[b"game"], &program).unwrap();
Expand Down
6 changes: 5 additions & 1 deletion crates/timba-protocol/src/amounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ pub fn format_token_amount(value: u128, decimals: u32) -> Result<String, TokenAm
}
let d = decimals as usize;
let digits = value.to_string();
let padded = if digits.len() < d + 1 { format!("{}{}", "0".repeat(d + 1 - digits.len()), digits) } else { digits };
// At least one whole digit: 5 with 2 decimals is "005", so "0.05".
let padded = format!("{digits:0>width$}", width = d + 1);
let (whole, fraction) = padded.split_at(padded.len() - d);
let fraction = fraction.trim_end_matches('0');
Ok(if fraction.is_empty() { whole.to_string() } else { format!("{whole}.{fraction}") })
Expand Down Expand Up @@ -97,6 +98,9 @@ mod tests {
assert_eq!(format_token_amount(0, 6).unwrap(), "0");
assert_eq!(format_token_amount(1, 6).unwrap(), "0.000001");
assert_eq!(format_token_amount(1_500_000, 6).unwrap(), "1.5");
assert_eq!(format_token_amount(5, 1).unwrap(), "0.5");
assert_eq!(format_token_amount(123, 3).unwrap(), "0.123");
assert_eq!(format_token_amount(1234, 3).unwrap(), "1.234");
assert_eq!(format_token_amount(42, 0).unwrap(), "42");
assert!(format_token_amount(1, 256).is_err());
assert_eq!(tokens_to_amount(1_500_000, 6), 1.5);
Expand Down
17 changes: 16 additions & 1 deletion crates/timba-protocol/src/contracts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ fn expect_discriminator(reader: &mut Reader<'_>, expected: &[u8; 8], what: &str)
impl GameAccount {
/// Mirrors protocol `decodeGame`.
pub fn decode(data: &[u8]) -> Result<Self, DecodeError> {
if data.len() < 8 || data[..8] != discriminators::GAME_ACCOUNT {
if !data.starts_with(&discriminators::GAME_ACCOUNT) {
return Err(DecodeError::new("Account is not a Timba game"));
}
let mut r = Reader::new(data);
Expand Down Expand Up @@ -715,6 +715,21 @@ mod tests {
mismatch.tickets_count = 3;
assert!(GameAccount::decode(&mismatch.encode()).is_err());
assert!(GameAccount::decode(&bytes[..bytes.len() - 1]).is_err());
for short in [&bytes[..0], &bytes[..7]] {
assert_eq!(GameAccount::decode(short).unwrap_err().to_string(), "Account is not a Timba game");
}
// Accounts are allocated for the most players, so free space follows the participants.
let mut spare = bytes.clone();
spare.extend([0; 64]);
assert_eq!(GameAccount::decode(&spare).unwrap(), game);
// A count past the data fails before any participant is read.
let count_at = bytes.len() - 2 * 32 - 4;
let mut long_count = bytes.clone();
long_count[count_at..count_at + 4].copy_from_slice(&3u32.to_le_bytes());
assert_eq!(
GameAccount::decode(&long_count).unwrap_err().to_string(),
"Codec [decode] participant vector exceeds account data"
);
}

#[test]
Expand Down
7 changes: 7 additions & 0 deletions crates/timba-protocol/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,13 @@ mod tests {
assert_eq!(get_trusted_program_data(&logs, program), vec![vec![5u8; 12]]);
}

#[test]
fn a_known_discriminator_without_fields_is_malformed() {
assert!(decode_program_event(&discriminators::GAME_COMPLETED).is_err());
assert_eq!(decode_program_event(&[0; 8]).unwrap(), None);
assert_eq!(decode_program_event(&discriminators::GAME_COMPLETED[..7]).unwrap(), None);
}

#[test]
fn trusted_program_data_keeps_the_frame_after_a_stray_completion() {
let program = "32Jr4JnXWvqq9GqPQynkooHsszaucUUvZfNLh2hdX2L5";
Expand Down
13 changes: 13 additions & 0 deletions crates/timba-protocol/src/plans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,19 @@ mod tests {
}
}

#[test]
fn refunds_never_wrap_sol() {
let adapter = ContractAdapter::new(ContractVersion::V0_3_0, PROGRAM_ID);
let player = Address::parse("9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM").unwrap();
for (token_mint, token_amount) in [(NATIVE_MINT, None), (NATIVE_MINT, Some(5)), (Address([2; 32]), Some(5))] {
let input =
GameInstructionInput { game: Address([9; 32]), player, token_mint, token_amount, authority: None };
let plan = adapter.build_refund_plan(&input).unwrap();
// The token account setup, then the refund.
assert_eq!(plan.instructions.len(), 2, "{token_mint:?}");
}
}

#[test]
fn create_game_requires_a_32_byte_oracle_commitment() {
let creator = Address::parse("9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM").unwrap();
Expand Down
4 changes: 4 additions & 0 deletions crates/timba-protocol/src/validators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ mod tests {
assert!(!is_strict_base64("AAA"));
assert!(!is_strict_base64("AA==AAAA"));
assert!(!is_base64_transaction(""));
assert!(is_base64_transaction("AQID"));
assert!(is_base64_transaction(&"A".repeat(16_384)));
assert!(!is_base64_transaction(&"A".repeat(16_388)));
assert!(!is_base64_transaction("AQI"));
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion dist/amounts/index.d.ts.map

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

16 changes: 9 additions & 7 deletions dist/amounts/index.js

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

2 changes: 1 addition & 1 deletion dist/amounts/index.js.map

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

Loading