solana_tools_lite_cli/shell/
error.rs1use solana_tools_lite::errors::{
2 AsExitCode, Bip39Error, DeserializeError, ExitCode, GenError, KeypairError, SignError,
3 TransactionParseError, ToolError, VerifyError,
4};
5use std::io;
6use thiserror::Error;
7
8#[derive(Debug, Error)]
9pub enum CliError {
10 #[error(transparent)]
11 Core(#[from] ToolError),
12 #[error("--summary-json requires --output (file) to keep signed tx off stdout")]
13 SummaryRequiresOutput,
14 #[error("Fee {fee_lamports} exceeds max-fee limit {max_lamports} lamports")]
15 FeeLimitExceeded {
16 fee_lamports: u128,
17 max_lamports: u64,
18 },
19 #[error("User rejected signing")]
20 UserRejected,
21 #[error("failed to encode summary json: {0}")]
22 SummaryEncode(String),
23 #[error("failed to encode json output: {0}")]
24 PresentationEncode(String),
25 #[error("failed to read stdin: {0}")]
26 StdinRead(String),
27}
28
29impl AsExitCode for CliError {
30 fn as_exit_code(&self) -> i32 {
31 match self {
32 CliError::Core(err) => err.as_exit_code(),
33 CliError::SummaryRequiresOutput | CliError::UserRejected => ExitCode::Usage.as_i32(),
34 CliError::FeeLimitExceeded { .. } => ExitCode::DataErr.as_i32(),
35 CliError::SummaryEncode(_) | CliError::PresentationEncode(_) => {
36 ExitCode::Software.as_i32()
37 }
38 CliError::StdinRead(_) => ExitCode::IoErr.as_i32(),
39 }
40 }
41}
42
43pub fn fail_invalid_input(context: &str, message: &str) -> ! {
45 eprintln!("{}: {}", context, message);
46 std::process::exit(64);
47}
48
49pub fn report_cli_error(context: &str, err: CliError) -> ! {
51 eprintln!("{}: {}", context, format_cli_error(&err));
52 std::process::exit(err.as_exit_code());
53}
54
55fn format_cli_error(err: &CliError) -> String {
56 match err {
57 CliError::Core(core) => format_user_friendly(core),
58 CliError::SummaryRequiresOutput => {
59 "--summary-json requires --output (file) to keep signed tx off stdout".to_string()
60 }
61 CliError::FeeLimitExceeded {
62 fee_lamports,
63 max_lamports,
64 } => format!(
65 "Fee {} exceeds max-fee limit {} lamports",
66 fee_lamports, max_lamports
67 ),
68 CliError::UserRejected => "User rejected signing".to_string(),
69 CliError::SummaryEncode(msg) => format!("failed to encode summary json: {msg}"),
70 CliError::PresentationEncode(msg) => format!("failed to encode json output: {msg}"),
71 CliError::StdinRead(msg) => format!("failed to read stdin: {msg}"),
72 }
73}
74
75fn format_user_friendly(err: &ToolError) -> String {
76 match err {
77 ToolError::Bip39(e) => format_bip39(e),
78 ToolError::Base58(e) => format!("Invalid Base58 encoding: {}", e),
79 ToolError::Sign(e) => format_sign(e),
80 ToolError::Keypair(e) => format_keypair(e),
81 ToolError::Gen(e) => format_gen(e),
82 ToolError::TransactionParse(e) => format_tx_parse(e),
83 ToolError::Deserialize(e) => format_deserialize(e),
84 ToolError::Verify(e) => format_verify(e),
85 ToolError::Io(io_err) => format_io(io_err),
86 ToolError::FileExists { path } => {
87 format!(
88 "Cannot create file '{}': already exists\nHint: Use --force to overwrite",
89 path
90 )
91 }
92 ToolError::InvalidInput(msg) => msg.clone(),
93 }
94}
95
96fn format_bip39(e: &Bip39Error) -> String {
97 match e {
98 Bip39Error::InvalidWordCount(got) => {
99 format!(
100 "Invalid mnemonic length: got {} words, expected 12 or 24",
101 got
102 )
103 }
104 Bip39Error::Mnemonic(msg) => {
105 format!(
106 "Mnemonic validation failed: {}\nHint: Check that all words are from the BIP-39 wordlist",
107 msg
108 )
109 }
110 }
111}
112
113fn format_sign(e: &SignError) -> String {
114 match e {
115 SignError::InvalidBase58 => "Invalid Base58 encoding in secret key".to_string(),
116 SignError::InvalidPubkeyFormat => {
117 "Invalid public key format\nHint: Public keys must be valid Base58-encoded Ed25519 keys"
118 .to_string()
119 }
120 SignError::InvalidKeyLength => "Secret key must be exactly 32 bytes".to_string(),
121 SignError::SigningFailed(msg) => {
122 format!(
123 "Failed to sign transaction: {}\nHint: Verify your secret key is valid",
124 msg
125 )
126 }
127 SignError::SignerKeyNotFound => {
128 "Signer public key not found in transaction account keys\nHint: The keypair you're using doesn't match any signer in this transaction".to_string()
129 }
130 SignError::SigningNotRequiredForKey => {
131 "The provided signer is not a required signer for this transaction\nHint: Check that you're using the correct keypair".to_string()
132 }
133 SignError::JsonParse(e) => {
134 format!(
135 "Failed to parse input JSON: {}\nHint: Check that your JSON is valid",
136 e
137 )
138 }
139 }
140}
141
142fn format_keypair(e: &KeypairError) -> String {
143 match e {
144 KeypairError::SeedTooShort(got) => {
145 format!(
146 "Seed is too short: got {} bytes, expected at least 32 bytes",
147 got
148 )
149 }
150 KeypairError::SeedSlice(msg) => {
151 format!("Invalid seed data: {}", msg)
152 }
153 }
154}
155
156fn format_gen(e: &GenError) -> String {
157 match e {
158 GenError::InvalidSeedLength => {
159 "Invalid seed length: expected 64 bytes\nHint: Use a valid BIP-39 mnemonic or provide a 64-byte seed".to_string()
160 }
161 GenError::CryptoError(msg) => {
162 format!(
163 "Cryptographic error: {}\nHint: Check your mnemonic and derivation path",
164 msg
165 )
166 }
167 GenError::InvalidDerivationPath(msg) => {
168 format!(
169 "Invalid derivation path: {}\nHint: Use BIP-44 format like m/44'/501'/0'/0'",
170 msg
171 )
172 }
173 }
174}
175
176fn format_tx_parse(e: &TransactionParseError) -> String {
177 match e {
178 TransactionParseError::InvalidBase64(msg) => {
179 format!(
180 "Invalid Base64 encoding in transaction: {}\nHint: Check that the transaction is properly Base64-encoded",
181 msg
182 )
183 }
184 TransactionParseError::InvalidBase58(msg) => {
185 format!(
186 "Invalid Base58 encoding in transaction: {}\nHint: Check that the transaction is properly Base58-encoded",
187 msg
188 )
189 }
190 TransactionParseError::InvalidInstructionData(msg) => {
191 format!("Invalid instruction data: {}", msg)
192 }
193 TransactionParseError::InvalidPubkeyFormat(msg) => {
194 format!("Invalid public key in transaction: {}", msg)
195 }
196 TransactionParseError::InvalidSignatureLength(len) => {
197 format!("Invalid signature length: expected 64 bytes, got {}", len)
198 }
199 TransactionParseError::InvalidPubkeyLength(len) => {
200 format!("Invalid public key length: expected 32 bytes, got {}", len)
201 }
202 TransactionParseError::InvalidSignatureFormat(msg) => {
203 format!("Invalid signature format: {}", msg)
204 }
205 TransactionParseError::InvalidBlockhashLength(len) => {
206 format!("Invalid blockhash length: expected 32 bytes, got {}", len)
207 }
208 TransactionParseError::InvalidBlockhashFormat(msg) => {
209 format!("Invalid blockhash format: {}", msg)
210 }
211 TransactionParseError::InvalidFormat(msg) => {
212 format!(
213 "Invalid transaction format: {}\nHint: Ensure the transaction is in JSON, Base64, or Base58 format",
214 msg
215 )
216 }
217 TransactionParseError::Serialization(msg) => {
218 format!("Failed to serialize transaction: {}", msg)
219 }
220 }
221}
222
223fn format_deserialize(e: &DeserializeError) -> String {
224 match e {
225 DeserializeError::Deserialization(msg) => {
226 format!(
227 "Failed to deserialize transaction: {}\nHint: Check that the input is a valid Solana transaction",
228 msg
229 )
230 }
231 }
232}
233
234fn format_verify(e: &VerifyError) -> String {
235 match e {
236 VerifyError::Base58Decode(e) => format!("Invalid Base58 encoding: {}", e),
237 VerifyError::InvalidSignatureLength(len) => {
238 format!("Invalid signature length: expected 64 bytes, got {}", len)
239 }
240 VerifyError::InvalidPubkeyLength(len) => {
241 format!("Invalid public key length: expected 32 bytes, got {}", len)
242 }
243 VerifyError::InvalidSignatureFormat => {
244 "Invalid signature format\nHint: Signatures must be 64-byte Ed25519 signatures".to_string()
245 }
246 VerifyError::InvalidPubkeyFormat => {
247 "Invalid public key format\nHint: Public keys must be 32-byte Ed25519 public keys"
248 .to_string()
249 }
250 VerifyError::VerificationFailed => {
251 "Signature verification failed\nHint: The signature does not match the message and public key"
252 .to_string()
253 }
254 }
255}
256
257
258fn format_io(err: &solana_tools_lite::errors::IoError) -> String {
259 let hint = match err.kind() {
263 io::ErrorKind::NotFound => "\nHint: Check that the file path is correct",
264 io::ErrorKind::PermissionDenied => {
265 "\nHint: Ensure you have read/write permissions for this file"
266 }
267 io::ErrorKind::AlreadyExists => "\nHint: Use --force to overwrite existing files",
268 _ => "",
269 };
270
271 format!("{}{}", err, hint)
273}