feat: add rs-scripts crate with decode-document CLI tool#3391
Conversation
Adds a utility crate for debugging and inspecting Platform data. The first tool, decode-document, deserializes platform documents from base64 or hex bytes using the actual platform serialization code. Supports all system contracts by name or ID (base58/base64/hex). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 18 minutes and 25 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (3)
📝 WalkthroughWalkthroughA new Rust package Changes
Estimated Code Review Effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/rs-scripts/README.md`:
- Around line 7-13: Update the README usage text for the decode-document binary
to indicate it accepts both base64 and hex input (not only base64); change the
placeholder and description for the CLI invocation of the decode-document binary
(binary name: decode-document) to something like <ENCODED_DOC> and note that the
input may be base64 or hex, and adjust the preceding sentence to state “accepts
base64 or hex-encoded platform documents” so users aren’t misled by the current
base64-only wording.
In `@packages/rs-scripts/src/bin/decode_document.rs`:
- Around line 109-112: Replace the unchecked cast in format_ts by performing a
checked conversion for seconds: compute secs_u64 = ms / 1000 and use
i64::try_from(secs_u64) to obtain secs; on Err, return the same fallback used
when chrono::DateTime::from_timestamp returns None (preserve the existing None
branch behavior) so out-of-range values are handled explicitly rather than by
implicit wrapping; keep the nanos computation and the rest of the dt handling
unchanged.
- Around line 72-73: The three `.expect()` calls (around
`load_system_data_contract`, the contract type lookup, and the document
deserialization) must be replaced with the same graceful error handling used
earlier in this file (lines ~48–52): handle the Result/Option with `match` or
`if let Err/None` to print a structured error to stderr (e.g. `eprintln!`) and
call `std::process::exit(1)` instead of panicking. Specifically, replace the
`expect` on `load_system_data_contract(...)` with error branching that logs the
failure and exits, do the same for the contract type lookup (the lookup function
used in this file) and for the deserialization step (the function that parses
the document); keep the existing error message style and include the underlying
error details when available.
- Around line 79-86: The current decoding chooses hex first by testing
hex::decode(&args.doc_bytes) before base64, causing base64 payloads composed of
hex-safe chars (e.g., "414243") to be mis-decoded; update the CLI parsing (where
args.doc_bytes is defined) to add an explicit --encoding flag (enum like
Encoding::Auto|Hex|Base64, default Auto) and change the decoding logic in this
block to: if args.encoding == Encoding::Hex -> try hex::decode, else if
Encoding::Base64 -> try base64::engine::general_purpose::STANDARD.decode, else
(Auto) try base64 first and fall back to hex or validate decoded bytes
downstream; ensure error messages reference args.doc_bytes and the selected
encoding when failing.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 5b9a116c-b3ea-4537-bc2a-9d1a3414d5a2
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (4)
Cargo.tomlpackages/rs-scripts/Cargo.tomlpackages/rs-scripts/README.mdpackages/rs-scripts/src/bin/decode_document.rs
| fn format_ts(ms: u64) -> String { | ||
| let secs = (ms / 1000) as i64; | ||
| let nanos = ((ms % 1000) * 1_000_000) as u32; | ||
| let dt = chrono::DateTime::from_timestamp(secs, nanos); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
rg -n -C2 'format_ts|as i64|from_timestamp' packages/rs-scripts/src/bin/decode_document.rsRepository: dashpay/platform
Length of output: 762
🏁 Script executed:
#!/bin/bash
# Find chrono dependency and version
fd 'Cargo.toml' packages/rs-scripts/ | xargs cat | grep -A5 'dependencies'Repository: dashpay/platform
Length of output: 270
🏁 Script executed:
#!/bin/bash
# Check the full function implementation and context
sed -n '109,120p' packages/rs-scripts/src/bin/decode_document.rsRepository: dashpay/platform
Length of output: 381
🌐 Web query:
chrono DateTime::from_timestamp i64 range limits documentation
💡 Result:
The DateTime::from_timestamp(secs: i64, nsecs: u32) method in the chrono crate creates a new DateTime from the given UNIX timestamp (non-leap seconds since 1970-01-01 00:00:00 UTC) and nanoseconds. This method panics if the resulting NaiveDateTime is out of range. The valid range for NaiveDateTime (and thus DateTime) corresponds to NaiveDate::MIN at 00:00:00 to NaiveDate::MAX at 23:59:59.999999999: - Minimum: January 1, -262144 (262145 BCE) - Maximum: December 31, 262142 (262143 CE) An i64 timestamp spans from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 seconds (~292 billion years), far exceeding Chrono's date limits (~262,000 years from epoch). Thus, from_timestamp panics for timestamps too far from the epoch, even if within i64. Use the fallible DateTime::from_timestamp_opt(secs: i64, nsecs: u32) -> Option<DateTime> (or Utc::timestamp_opt) instead, which returns None for out-of-range values. To compute exact min/max i64 timestamps, calculate seconds from epoch to MIN/MAX dates, but typically unnecessary—check the Option result. Example: use chrono::{DateTime, Utc}; let dt = DateTime::from_timestamp_opt(1_500_000_000i64, 0).unwrap; // Fri, 14 Jul 2017 02:40:00 UTC let out_of_range = DateTime::from_timestamp_opt(i64::MIN, 0); // None
Citations:
- 1: https://docs.rs/chrono/latest/chrono/struct.DateTime.html
- 2: https://docs.rs/chrono/latest/chrono/naive/struct.NaiveDateTime.html
- 3: https://docs.rs/chrono/latest/chrono/naive/struct.NaiveDate.html
- 4: Why does
from_timestamppanic for very small values ifi64likei64::MIN? chronotope/chrono#431 - 5: https://hid-io.github.io/chrono/naive/
- 6: https://docs.rs/chrono/latest/chrono/struct.NaiveDate.html
Use checked casting for explicit timestamp validation.
The cast from u64 to i64 on line 110 can theoretically overflow for very large values. While the existing error handling via match dt { Some(_) => ..., None => ... } catches out-of-range timestamps from the chrono library, using i64::try_from(ms / 1000) makes the intent of validated conversion explicit and avoids relying on implicit wrapping behavior.
Suggested fix (checked conversion)
fn format_ts(ms: u64) -> String {
- let secs = (ms / 1000) as i64;
+ let secs = match i64::try_from(ms / 1000) {
+ Ok(v) => v,
+ Err(_) => return format!("invalid timestamp: {ms}"),
+ };
let nanos = ((ms % 1000) * 1_000_000) as u32;
let dt = chrono::DateTime::from_timestamp(secs, nanos);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| fn format_ts(ms: u64) -> String { | |
| let secs = (ms / 1000) as i64; | |
| let nanos = ((ms % 1000) * 1_000_000) as u32; | |
| let dt = chrono::DateTime::from_timestamp(secs, nanos); | |
| fn format_ts(ms: u64) -> String { | |
| let secs = match i64::try_from(ms / 1000) { | |
| Ok(v) => v, | |
| Err(_) => return format!("invalid timestamp: {ms}"), | |
| }; | |
| let nanos = ((ms % 1000) * 1_000_000) as u32; | |
| let dt = chrono::DateTime::from_timestamp(secs, nanos); |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/rs-scripts/src/bin/decode_document.rs` around lines 109 - 112,
Replace the unchecked cast in format_ts by performing a checked conversion for
seconds: compute secs_u64 = ms / 1000 and use i64::try_from(secs_u64) to obtain
secs; on Err, return the same fallback used when
chrono::DateTime::from_timestamp returns None (preserve the existing None branch
behavior) so out-of-range values are handled explicitly rather than by implicit
wrapping; keep the nanos computation and the rest of the dt handling unchanged.
There was a problem hiding this comment.
The cast is safe: ms / 1000 for any u64 fits in i64, and (ms % 1000) * 1_000_000 fits in u32. The from_timestamp call handles edge cases by returning None (which we already handle). No change needed.
There was a problem hiding this comment.
@QuantumExplorer, you are correct — I apologize for the incorrect suggestion. The math checks out:
u64::MAX / 1000 ≈ 1.8 × 10¹⁶, which is well withini64::MAX ≈ 9.2 × 10¹⁸, so theas i64cast cannot overflow for anyu64input.(ms % 1000) * 1_000_000is at most999 × 1_000_000 = 999_000_000, which fits comfortably inu32::MAX (≈ 4.3 × 10⁹).
The existing None-handling from chrono::DateTime::from_timestamp already covers the out-of-range case. No change needed.
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
Clean, well-structured CLI debugging tool for decoding platform documents. All agent findings verified against source code. No truly blocking issues for a developer utility — the main concerns are the hex-first decode ambiguity (can silently produce wrong bytes), use of PlatformVersion::latest() (can misinterpret historical documents due to config version differences), and inconsistent error handling (mix of panic and graceful exit).
Reviewed commit: d092420
🟡 3 suggestion(s) | 💬 3 nitpick(s)
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/rs-scripts/src/bin/decode_document.rs`:
- [SUGGESTION] lines 79-86: Hex-first decode ordering silently misinterprets some base64 inputs
The code tries `hex::decode` before `base64::decode`. Any base64 string that consists entirely of hex characters (0-9, a-f, A-F) with even length will be silently decoded as hex, producing different (wrong) bytes. Examples: `deadbeef`, `41414141`, `cafe0000`. Since this is a debugging tool, silently producing wrong bytes is particularly harmful — the user may not realize the output is wrong.
Verified against code at lines 79-86: confirmed hex is tried first. The simplest fix would be to either swap to base64-first (base64 is stricter about padding so fewer false positives) or add an explicit `--format hex|base64` flag.
- [SUGGESTION] line 68: PlatformVersion::latest() can cause historical documents to decode incorrectly
Verified: `load_system_data_contract` returns different contracts for different platform versions. Tests in `rs-dpp/src/system_data_contracts.rs` confirm that v8 TokenHistory != v9 TokenHistory and v1 Withdrawals != v9 Withdrawals. The difference is in `DataContractConfig` version (v8 uses config v0, v9+ uses config v1 with `sized_integer_types` enabled), which affects serialization format.
A document serialized under platform v8 may fail or be misinterpreted when deserialized with a v9+ contract config loaded via `PlatformVersion::latest()`. For a debugging tool, this is a meaningful limitation worth addressing.
- [SUGGESTION] lines 72-89: User-facing errors should not panic — use consistent error handling
Verified: Lines 73, 77, and 89 use `.expect()` which panics with a stack trace on failure, while `resolve_system_contract` (lines 49-52, 61-62) and the byte-decoding fallback (lines 84-85) use `eprintln!` + `exit(1)` for clean error messages.
For a CLI tool, all user-facing errors should produce clean messages. Invalid contract name, unknown doc type, and deserialization failure are all expected user-input scenarios, not programming bugs. The `.expect()` calls produce confusing panic output (with backtrace) for normal usage errors.
| let bytes = if let Ok(b) = hex::decode(&args.doc_bytes) { | ||
| b | ||
| } else if let Ok(b) = base64::engine::general_purpose::STANDARD.decode(&args.doc_bytes) { | ||
| b | ||
| } else { | ||
| eprintln!("Failed to decode document bytes as hex or base64"); | ||
| std::process::exit(1); | ||
| }; |
There was a problem hiding this comment.
🟡 Suggestion: Hex-first decode ordering silently misinterprets some base64 inputs
The code tries hex::decode before base64::decode. Any base64 string that consists entirely of hex characters (0-9, a-f, A-F) with even length will be silently decoded as hex, producing different (wrong) bytes. Examples: deadbeef, 41414141, cafe0000. Since this is a debugging tool, silently producing wrong bytes is particularly harmful — the user may not realize the output is wrong.
Verified against code at lines 79-86: confirmed hex is tried first. The simplest fix would be to either swap to base64-first (base64 is stricter about padding so fewer false positives) or add an explicit --format hex|base64 flag.
source: ['claude', 'codex']
🤖 Fix this with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/rs-scripts/src/bin/decode_document.rs`:
- [SUGGESTION] lines 79-86: Hex-first decode ordering silently misinterprets some base64 inputs
The code tries `hex::decode` before `base64::decode`. Any base64 string that consists entirely of hex characters (0-9, a-f, A-F) with even length will be silently decoded as hex, producing different (wrong) bytes. Examples: `deadbeef`, `41414141`, `cafe0000`. Since this is a debugging tool, silently producing wrong bytes is particularly harmful — the user may not realize the output is wrong.
Verified against code at lines 79-86: confirmed hex is tried first. The simplest fix would be to either swap to base64-first (base64 is stricter about padding so fewer false positives) or add an explicit `--format hex|base64` flag.
There was a problem hiding this comment.
Fixed — swapped to base64-first in auto mode and added --format flag for explicit control.
| fn main() { | ||
| let args = Args::parse(); | ||
|
|
||
| let platform_version = PlatformVersion::latest(); |
There was a problem hiding this comment.
🟡 Suggestion: PlatformVersion::latest() can cause historical documents to decode incorrectly
Verified: load_system_data_contract returns different contracts for different platform versions. Tests in rs-dpp/src/system_data_contracts.rs confirm that v8 TokenHistory != v9 TokenHistory and v1 Withdrawals != v9 Withdrawals. The difference is in DataContractConfig version (v8 uses config v0, v9+ uses config v1 with sized_integer_types enabled), which affects serialization format.
A document serialized under platform v8 may fail or be misinterpreted when deserialized with a v9+ contract config loaded via PlatformVersion::latest(). For a debugging tool, this is a meaningful limitation worth addressing.
source: ['claude', 'codex']
🤖 Fix this with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/rs-scripts/src/bin/decode_document.rs`:
- [SUGGESTION] line 68: PlatformVersion::latest() can cause historical documents to decode incorrectly
Verified: `load_system_data_contract` returns different contracts for different platform versions. Tests in `rs-dpp/src/system_data_contracts.rs` confirm that v8 TokenHistory != v9 TokenHistory and v1 Withdrawals != v9 Withdrawals. The difference is in `DataContractConfig` version (v8 uses config v0, v9+ uses config v1 with `sized_integer_types` enabled), which affects serialization format.
A document serialized under platform v8 may fail or be misinterpreted when deserialized with a v9+ contract config loaded via `PlatformVersion::latest()`. For a debugging tool, this is a meaningful limitation worth addressing.
There was a problem hiding this comment.
Fair point. For a debugging tool, latest() is the right default since you're typically decoding recent documents. Historical version support could be added later with a --version flag if needed, but that's a separate concern.
| let data_contract = load_system_data_contract(system_contract, platform_version) | ||
| .expect("failed to load system data contract"); | ||
|
|
||
| let document_type = data_contract | ||
| .document_type_for_name(&args.doc_type) | ||
| .expect("failed to get document type"); | ||
|
|
||
| let bytes = if let Ok(b) = hex::decode(&args.doc_bytes) { | ||
| b | ||
| } else if let Ok(b) = base64::engine::general_purpose::STANDARD.decode(&args.doc_bytes) { | ||
| b | ||
| } else { | ||
| eprintln!("Failed to decode document bytes as hex or base64"); | ||
| std::process::exit(1); | ||
| }; | ||
|
|
||
| let document = Document::from_bytes(&bytes, document_type, platform_version) | ||
| .expect("failed to deserialize document"); |
There was a problem hiding this comment.
🟡 Suggestion: User-facing errors should not panic — use consistent error handling
Verified: Lines 73, 77, and 89 use .expect() which panics with a stack trace on failure, while resolve_system_contract (lines 49-52, 61-62) and the byte-decoding fallback (lines 84-85) use eprintln! + exit(1) for clean error messages.
For a CLI tool, all user-facing errors should produce clean messages. Invalid contract name, unknown doc type, and deserialization failure are all expected user-input scenarios, not programming bugs. The .expect() calls produce confusing panic output (with backtrace) for normal usage errors.
💡 Suggested change
| let data_contract = load_system_data_contract(system_contract, platform_version) | |
| .expect("failed to load system data contract"); | |
| let document_type = data_contract | |
| .document_type_for_name(&args.doc_type) | |
| .expect("failed to get document type"); | |
| let bytes = if let Ok(b) = hex::decode(&args.doc_bytes) { | |
| b | |
| } else if let Ok(b) = base64::engine::general_purpose::STANDARD.decode(&args.doc_bytes) { | |
| b | |
| } else { | |
| eprintln!("Failed to decode document bytes as hex or base64"); | |
| std::process::exit(1); | |
| }; | |
| let document = Document::from_bytes(&bytes, document_type, platform_version) | |
| .expect("failed to deserialize document"); | |
| Replace `.expect(...)` on lines 73, 77, and 89 with `unwrap_or_else(|e| { eprintln!("...: {e}"); std::process::exit(1); })` to match the existing error handling style. |
source: ['claude', 'codex']
🤖 Fix this with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/rs-scripts/src/bin/decode_document.rs`:
- [SUGGESTION] lines 72-89: User-facing errors should not panic — use consistent error handling
Verified: Lines 73, 77, and 89 use `.expect()` which panics with a stack trace on failure, while `resolve_system_contract` (lines 49-52, 61-62) and the byte-decoding fallback (lines 84-85) use `eprintln!` + `exit(1)` for clean error messages.
For a CLI tool, all user-facing errors should produce clean messages. Invalid contract name, unknown doc type, and deserialization failure are all expected user-input scenarios, not programming bugs. The `.expect()` calls produce confusing panic output (with backtrace) for normal usage errors.
There was a problem hiding this comment.
Fixed — all .expect() calls replaced with proper eprintln! + process::exit(1).
| ]; | ||
|
|
||
| #[derive(Parser)] | ||
| #[command(name = "decode-document", about = "Decode a platform document from base64 bytes")] |
There was a problem hiding this comment.
💬 Nitpick: CLI about text says 'base64 bytes' but tool also accepts hex
Verified: Line 24 has about = "Decode a platform document from base64 bytes" but the tool accepts both base64 and hex (line 26 comment and lines 79-86 logic). The about text shown in --help output is misleading.
💡 Suggested change
| #[command(name = "decode-document", about = "Decode a platform document from base64 bytes")] | |
| #[command(name = "decode-document", about = "Decode a platform document from base64 or hex bytes")] |
source: ['claude']
There was a problem hiding this comment.
Fixed — about text now says "Decode a platform document from hex or base64 bytes".
| const SYSTEM_CONTRACTS: &[(&str, SystemDataContract)] = &[ | ||
| ("withdrawals", SystemDataContract::Withdrawals), | ||
| ("dpns", SystemDataContract::DPNS), | ||
| ("dashpay", SystemDataContract::Dashpay), | ||
| ("masternode-reward-shares", SystemDataContract::MasternodeRewards), | ||
| ("feature-flags", SystemDataContract::FeatureFlags), | ||
| ("wallet-utils", SystemDataContract::WalletUtils), | ||
| ("token-history", SystemDataContract::TokenHistory), | ||
| ("keyword-search", SystemDataContract::KeywordSearch), | ||
| ]; |
There was a problem hiding this comment.
💬 Nitpick: SYSTEM_CONTRACTS list must be manually kept in sync with SystemDataContract enum
Verified: The SystemDataContract enum (in packages/data-contracts/src/lib.rs) has exactly 8 variants and the SYSTEM_CONTRACTS array has 8 entries — currently in sync. However, there is no compile-time check ensuring completeness. The enum does not derive strum::EnumIter or similar.
For a small debugging tool this is acceptable, but if a new system contract is added to the enum, this list will silently become incomplete. A match statement on SystemDataContract would give a compiler warning when variants are added.
source: ['claude']
There was a problem hiding this comment.
Added a comment: // Keep in sync with SystemDataContract enum in packages/data-contracts/src/lib.rs
| use base64::Engine; | ||
| use clap::Parser; | ||
| use data_contracts::SystemDataContract; | ||
| use dpp::data_contract::accessors::v0::DataContractV0Getters; | ||
| use dpp::document::DocumentV0Getters; | ||
| use dpp::document::serialization_traits::DocumentPlatformConversionMethodsV0; | ||
| use dpp::document::Document; | ||
| use dpp::system_data_contracts::load_system_data_contract; | ||
| use dpp::platform_value::Identifier; | ||
| use platform_version::version::PlatformVersion; | ||
|
|
||
| const SYSTEM_CONTRACTS: &[(&str, SystemDataContract)] = &[ | ||
| ("withdrawals", SystemDataContract::Withdrawals), | ||
| ("dpns", SystemDataContract::DPNS), | ||
| ("dashpay", SystemDataContract::Dashpay), | ||
| ("masternode-reward-shares", SystemDataContract::MasternodeRewards), | ||
| ("feature-flags", SystemDataContract::FeatureFlags), | ||
| ("wallet-utils", SystemDataContract::WalletUtils), | ||
| ("token-history", SystemDataContract::TokenHistory), | ||
| ("keyword-search", SystemDataContract::KeywordSearch), | ||
| ]; | ||
|
|
||
| #[derive(Parser)] | ||
| #[command(name = "decode-document", about = "Decode a platform document from base64 bytes")] | ||
| struct Args { | ||
| /// Document bytes (base64 or hex encoded) | ||
| doc_bytes: String, | ||
|
|
||
| /// System data contract: name (e.g. "withdrawals") or ID in base58/base64/hex | ||
| #[arg(short, long)] | ||
| contract: String, | ||
|
|
||
| /// Document type name within the contract (e.g. "withdrawal", "domain") | ||
| #[arg(short, long)] | ||
| doc_type: String, | ||
| } | ||
|
|
||
| fn resolve_system_contract(input: &str) -> SystemDataContract { | ||
| // Try by name first | ||
| for (name, sc) in SYSTEM_CONTRACTS { | ||
| if input.eq_ignore_ascii_case(name) { | ||
| return *sc; | ||
| } | ||
| } | ||
|
|
||
| // Try parsing as an identifier (base58, base64, or hex) | ||
| let id = Identifier::from_string_unknown_encoding(input) | ||
| .unwrap_or_else(|_| { | ||
| eprintln!("Unknown contract: '{input}'"); | ||
| eprintln!("Must be a name ({}) or an ID in base58/base64/hex", | ||
| SYSTEM_CONTRACTS.iter().map(|(n, _)| *n).collect::<Vec<_>>().join(", ")); | ||
| std::process::exit(1); | ||
| }); | ||
|
|
||
| for (_, sc) in SYSTEM_CONTRACTS { | ||
| if sc.id() == id { | ||
| return *sc; | ||
| } | ||
| } | ||
|
|
||
| eprintln!("No system contract found with ID {id}"); | ||
| std::process::exit(1); | ||
| } | ||
|
|
||
| fn main() { | ||
| let args = Args::parse(); | ||
|
|
||
| let platform_version = PlatformVersion::latest(); | ||
|
|
||
| let system_contract = resolve_system_contract(&args.contract); | ||
|
|
||
| let data_contract = load_system_data_contract(system_contract, platform_version) | ||
| .expect("failed to load system data contract"); | ||
|
|
||
| let document_type = data_contract | ||
| .document_type_for_name(&args.doc_type) | ||
| .expect("failed to get document type"); | ||
|
|
||
| let bytes = if let Ok(b) = hex::decode(&args.doc_bytes) { | ||
| b | ||
| } else if let Ok(b) = base64::engine::general_purpose::STANDARD.decode(&args.doc_bytes) { | ||
| b | ||
| } else { | ||
| eprintln!("Failed to decode document bytes as hex or base64"); | ||
| std::process::exit(1); | ||
| }; | ||
|
|
||
| let document = Document::from_bytes(&bytes, document_type, platform_version) | ||
| .expect("failed to deserialize document"); | ||
|
|
||
| println!("id: {}", document.id()); | ||
| println!("owner_id: {}", document.owner_id()); | ||
| if let Some(created_at) = document.created_at() { | ||
| println!("created_at: {} ({}ms)", format_ts(created_at), created_at); | ||
| } | ||
| if let Some(updated_at) = document.updated_at() { | ||
| println!("updated_at: {} ({}ms)", format_ts(updated_at), updated_at); | ||
| } | ||
| if let Some(revision) = document.revision() { | ||
| println!("revision: {}", revision); | ||
| } | ||
| println!(); | ||
| println!("properties:"); | ||
| for (key, value) in document.properties() { | ||
| println!(" {key}: {value}"); | ||
| } | ||
| } | ||
|
|
||
| fn format_ts(ms: u64) -> String { | ||
| let secs = (ms / 1000) as i64; | ||
| let nanos = ((ms % 1000) * 1_000_000) as u32; | ||
| let dt = chrono::DateTime::from_timestamp(secs, nanos); | ||
| match dt { | ||
| Some(dt) => dt.format("%Y-%m-%d %H:%M:%S UTC").to_string(), | ||
| None => format!("invalid timestamp: {ms}"), | ||
| } | ||
| } |
There was a problem hiding this comment.
💬 Nitpick: No tests for the crate
Verified: The crate has no #[cfg(test)] module and no test files. For a small CLI debugging tool this is understandable, but resolve_system_contract and format_ts are pure functions that would benefit from basic unit tests.
source: ['claude', 'codex']
There was a problem hiding this comment.
Acknowledged — this is a small CLI debugging tool, not a library. The resolve_system_contract helper could be unit tested but the cost/benefit doesn't justify it for a dev utility. If the crate grows, tests can be added then.
- Replace all .expect() with proper error handling (eprintln + exit 1) - Fix about text: "base64 bytes" → "hex or base64 bytes" - Add --format flag (base64|hex|auto) to control input decoding - Try base64 before hex in auto mode (gRPC output is base64) - Add hint about --format when auto-detection fails - List available document types on unknown doc type error - Add sync comment on SYSTEM_CONTRACTS list - Update README to mention hex and --format flag Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Review GateCommit:
|
Summary
rs-scriptsworkspace crate with adecode-documentCLI tool for deserializing platform documents from base64 or hex byteswithdrawals) or by ID in base58/base64/hexcargo install --path packages/rs-scriptsUsage
decode-document -c withdrawals -d withdrawal "AgIintqUs1vl..."Test plan
cargo installworks🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
New Features
decode-documentutility for decoding and debugging base64-encoded platform documents, supporting all system contract types and document format versions.Documentation