star_frame 0.29.0

A high performance Solana framework for building fast, scalable, and secure smart contracts.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
use std::{
    borrow::Cow,
    fmt::{Debug, Formatter},
    panic::Location,
};

use derive_more::{Deref, DerefMut, Display, Error as DeriveError};
use itertools::Itertools;
use pinocchio::program_error::ProgramError;
use pinocchio_log::{log, logger::Logger};
pub use star_frame_proc::star_frame_error;

/// Error codes for errors emitted by `star_frame`
#[star_frame_error(offset = 0)]
pub enum ErrorCode {
    // Account set errors
    #[msg("Account is not writable")]
    ExpectedWritable = 1_000,
    #[msg("Account is not a signer")]
    ExpectedSigner,
    #[msg("Account's address does not match expected address")]
    AddressMismatch,
    #[msg("Discriminant mismatch")]
    DiscriminantMismatch,
    #[msg("Funder not set in account cache")]
    EmptyFunderCache,
    #[msg("Recipient not set in account cache")]
    EmptyRecipientCache,
    #[msg("Program not passed in for Optional account set")]
    MissingOptionalProgram,
    #[msg("Conflicting account seeds during init")]
    ConflictingAccountSeeds,
    #[msg("Seeds not set during init")]
    SeedsNotSet,

    // Unsized Type errors
    #[msg("An unexpected unsized type error occurred. This is a bug in star_frame")]
    UnsizedUnexpected = 2_000,
    #[msg("Pointer out of bounds in unsized type operation")]
    PointerOutOfBounds,
    #[msg("RawSliceAdvance out of bounds")]
    RawSliceAdvance,

    // Invalid input errors
    #[msg("Index out of bounds")]
    IndexOutOfBounds = 3_000,
    #[msg("Invalid range")]
    InvalidRange,

    // Conversion from other errors
    #[msg("num_traits::cast::ToPrimitive")]
    ToPrimitiveError = 9_000, // Conversion errors should be the last category
    #[msg("std::io::Error")]
    IoError,
    #[msg("bytemuck::PodCastError")]
    PodCastError,
    #[msg("bytemuck::checked::CheckedCastError")]
    CheckedCastError,
    #[msg("advancer::AdvanceError")]
    AdvanceError,
    #[msg("std::str::Utf8Error")]
    Utf8Error,
    #[msg("core::num::TryFromIntError")]
    TryFromIntError,
    #[msg("core::array::TryFromSliceError")]
    TryFromSliceError,
    #[msg("std::cell::BorrowError")]
    BorrowError,
    #[msg("std::cell::BorrowMutError")]
    BorrowMutError,
    #[msg("serde_json::Error")]
    SerdeJsonError,
    #[msg("star_frame_idl::Error")]
    IdlError,
}

/// Returns an [`Err<Error>`](Error) if left is not equal to right
///
/// left is found, right is expected
#[macro_export]
macro_rules! ensure_eq {
    ($left:expr, $right:expr, $err:expr $(,)?) => {{
        let left = $left;
        let right = $right;
        if left != right {
            return Err($crate::error!($err, "expected {right:?}, found {left:?}").into());
        }
    }};

    ($left:expr, $right:expr, $err:expr, $($ctx:tt)*) => {{
        if $left != $right {
            return Err($crate::error!($err, $($ctx)*).into());
        }
    }};
}

/// Returns an [`Err<Error>`](Error) if left is equal to right
///
/// left is found, right is expected
#[macro_export]
macro_rules! ensure_ne {
    ($left:expr, $right:expr, $err:expr $(,)?) => {{
        let right = $right;
        let left = $left;
        if left == right {
            return Err($crate::error!(
                $err,
                "expected to not be {right:?}, found {left:?}"
            ).into());
        }
    }};
    ($left:expr, $right:expr, $err:expr, $($ctx:tt)*) => {{
        if $left == $right {
            return Err($crate::error!($err, $($ctx)*).into());
        }
    }};
}

/// Returns an [`Err<Error>`](Error) if the condition is false
#[macro_export]
macro_rules! ensure {
    ($cond:expr, $err:expr $(, $($ctx:tt)*)?) => {
        if !$cond {
            return Err($crate::error!($err, $($($ctx)*)*).into());
        }
    };
}

/// Returns an [`Err<Error>`](Error)
#[macro_export]
macro_rules! bail {
    ($err:expr $(, $($ctx:tt)*)?) => {
        return Err($crate::error!($err, $($($ctx)*)*).into())
    };
}

/// Constructs an [`Error`]
#[macro_export]
macro_rules! error {
    ($err:expr $(,)?) => {
        $crate::errors::Error::new($err)
    };
    ($err:expr, $($ctx:tt)*) => {
        $crate::errors::Error::new_with_ctx($err, format!($($ctx)*))
    };
}

/// Represents something that can be used as a error.
///
/// Can be converted into an [`Error`] via `From`.
///
/// Derivable on enums via [`macro@star_frame_error`].
pub trait StarFrameError: 'static + Debug + Send + Sync {
    fn code(&self) -> u32;
    fn name(&self) -> Cow<'static, str>;
}

/// The kind of error. Either a [`ProgramError`] or a custom error implementing [`StarFrameError`].
#[derive(Debug, Display)]
pub enum ErrorKind {
    #[display("ProgramError: {_0}")]
    ProgramError(ProgramError),
    #[display("StarFrameError: {}", _0.name())]
    Custom(Box<dyn StarFrameError + 'static>),
}

impl PartialEq for ErrorKind {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::ProgramError(l0), Self::ProgramError(r0)) => l0 == r0,
            (Self::Custom(l0), Self::Custom(r0)) => l0.code() == r0.code(),
            _ => false,
        }
    }
}

/// The main body of the error struct, which is boxed to form [`Error`].
#[derive(Debug, DeriveError)]
pub struct ErrorInner {
    kind: ErrorKind,
    account_path: Vec<&'static str>,
    initial_ctx: Option<Cow<'static, str>>,
    initial_source: ErrorSource,
    context: Vec<(ErrorSource, Cow<'static, str>)>,
}

/// The error type returned from `star_frame` traits and functions.
#[derive(Debug, DeriveError, Display, Deref, DerefMut)]
pub struct Error(#[error(source)] Box<ErrorInner>);
static_assertions::assert_impl_all!(Error: Send, Sync);

impl std::fmt::Display for ErrorInner {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.kind)?;
        if let Some(initial_ctx) = &self.initial_ctx {
            write!(f, " - {initial_ctx}")?;
        }
        writeln!(f)?;

        writeln!(f, "Occurred at: {}", self.initial_source)?;

        if !self.account_path.is_empty() {
            writeln!(
                f,
                "For account: {}",
                self.account_path.iter().rev().join(".")
            )?;
        }
        if !self.context.is_empty() {
            for (source, ctx) in &self.context {
                writeln!(f, "{source}: {ctx}")?;
            }
        }
        Ok(())
    }
}

impl From<Error> for ProgramError {
    fn from(error: Error) -> Self {
        match &error.kind {
            ErrorKind::ProgramError(program_error) => *program_error,
            ErrorKind::Custom(custom) => ProgramError::Custom(custom.code()),
        }
    }
}

/// Where the error occurred
#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
#[display("{}:{}", file, line)]
pub struct ErrorSource {
    file: &'static str,
    line: u32,
}

impl ErrorSource {
    /// Creates a new error source for the caller's location
    #[track_caller]
    #[must_use]
    pub const fn new() -> Self {
        let location = Location::caller();
        Self {
            file: location.file(),
            line: location.line(),
        }
    }
}

impl Default for ErrorSource {
    fn default() -> Self {
        Self::new()
    }
}

mod private {
    #[doc(hidden)]
    pub trait Sealed {}
    impl<T, E> Sealed for Result<T, E> where E: Into<super::Error> {}
}

/// Adds additional context to an error, while automatically converting to the [`Error`] type.
pub trait ErrorInfo<T>: private::Sealed {
    /// Adds a ctx to the error
    #[track_caller]
    fn ctx(self, ctx: &'static str) -> Result<T, Error>;

    /// Add a ctx to the error with a closure. The ctx is evaluated lazily, and should be used when
    /// the ctx is not static.
    #[track_caller]
    fn with_ctx<C>(self, with_ctx: impl FnOnce() -> C) -> Result<T, Error>
    where
        C: Into<Cow<'static, str>>;

    /// Add an account path to the error, from the inner account name to outermost
    fn account_path(self, account_path: &'static str) -> Result<T, Error>;
}

impl<T, E> ErrorInfo<T> for Result<T, E>
where
    E: Into<Error>,
{
    #[track_caller]
    fn ctx(self, ctx: &'static str) -> Result<T, Error> {
        match self {
            Ok(ok) => Ok(ok),
            Err(error) => Err(error.into().push_ctx(ctx, Location::caller())),
        }
    }

    #[track_caller]
    fn with_ctx<C>(self, with_ctx: impl FnOnce() -> C) -> Result<T, Error>
    where
        C: Into<Cow<'static, str>>,
    {
        match self {
            Ok(ok) => Ok(ok),
            Err(error) => Err(error.into().push_ctx(with_ctx(), Location::caller())),
        }
    }

    fn account_path(self, account_path: &'static str) -> Result<T, Error> {
        match self {
            Ok(ok) => Ok(ok),
            Err(error) => Err(error.into().push_account_path(account_path)),
        }
    }
}

#[doc(hidden)]
#[diagnostic::on_unimplemented(
    message = "Errors in star_frame can only be made from types that implement StarFrameError or Into<ErrorKind>",
    note = "StarFrameError can be derived on enums with the #[star_frame_error] macro"
)]
pub trait CanMakeError: Into<ErrorKind> {}
impl<T> CanMakeError for T where T: Into<ErrorKind> {}

impl Error {
    /// Creates a new error at the caller's location
    #[cold]
    #[must_use]
    #[track_caller]
    pub fn new(error: impl CanMakeError) -> Self {
        Self::new_inner(error, None, Location::caller())
    }

    /// Creates a new error with additional context at the caller's location
    #[cold]
    #[must_use]
    #[track_caller]
    pub fn new_with_ctx(error: impl CanMakeError, ctx: impl Into<Cow<'static, str>>) -> Self {
        Self::new_inner(error, Some(ctx.into()), Location::caller())
    }

    #[cold]
    fn new_inner(
        error: impl CanMakeError,
        ctx: Option<Cow<'static, str>>,
        source: &'static Location<'static>,
    ) -> Self {
        Error(
            ErrorInner {
                kind: error.into(),
                account_path: vec![],
                initial_ctx: ctx,
                initial_source: ErrorSource {
                    file: source.file(),
                    line: source.line(),
                },
                context: vec![],
            }
            .into(),
        )
    }

    #[cold]
    #[must_use]
    fn push_ctx(
        mut self,
        ctx: impl Into<Cow<'static, str>>,
        location: &'static Location<'static>,
    ) -> Self {
        self.context.push((
            ErrorSource {
                file: location.file(),
                line: location.line(),
            },
            ctx.into(),
        ));
        self
    }

    #[cold]
    #[must_use]
    fn push_account_path(mut self, account_path: &'static str) -> Self {
        self.account_path.push(account_path);
        self
    }

    /// Logs the error using [`pinocchio_log`]
    pub fn log(&self) {
        {
            let mut logger = Logger::<1000>::default();
            match &self.kind {
                ErrorKind::ProgramError(program_error) => {
                    logger.append("ProgramError: ");
                    logger.append(program_error.to_string().as_str());
                }
                ErrorKind::Custom(custom) => {
                    logger.append("StarFrameError: ");
                    logger.append(custom.name().as_ref());
                }
            }
            if let Some(initial_ctx) = &self.initial_ctx {
                logger.append(" - ");
                logger.append(initial_ctx.as_ref());
            }
            logger.log();
        }

        log!(
            "Occurred at: {}:{}",
            self.initial_source.file,
            self.initial_source.line
        );

        if let Some((last, rest)) = self.account_path.split_last() {
            let mut logger = Logger::<200>::default();
            logger.append("For account: ");
            logger.append(*last);
            for account in rest.iter().rev() {
                logger.append(".");
                logger.append(*account);
            }
            logger.log();
        }

        for (source, ctx) in &self.context {
            log!(1000, "{}:{}: {}", source.file, source.line, ctx.as_ref(),);
        }
    }
}

// CONVERSIONS

impl<T> From<T> for ErrorKind
where
    T: StarFrameError + 'static,
{
    fn from(error: T) -> Self {
        ErrorKind::Custom(Box::new(error))
    }
}

impl<T> From<T> for Error
where
    T: Into<ErrorKind>,
{
    #[track_caller]
    fn from(value: T) -> Self {
        Error::new_inner(value, None, Location::caller())
    }
}

impl From<std::io::Error> for Error {
    #[track_caller]
    fn from(error: std::io::Error) -> Self {
        Error::new_inner(
            ErrorCode::IoError,
            Some(error.to_string().into()),
            Location::caller(),
        )
    }
}

impl From<bytemuck::PodCastError> for Error {
    #[track_caller]
    fn from(error: bytemuck::PodCastError) -> Self {
        Error::new_inner(
            ErrorCode::PodCastError,
            Some(error.to_string().into()),
            Location::caller(),
        )
    }
}

impl From<bytemuck::checked::CheckedCastError> for Error {
    #[track_caller]
    fn from(error: bytemuck::checked::CheckedCastError) -> Self {
        Error::new_inner(
            ErrorCode::CheckedCastError,
            Some(error.to_string().into()),
            Location::caller(),
        )
    }
}

impl From<advancer::AdvanceError> for Error {
    #[track_caller]
    fn from(error: advancer::AdvanceError) -> Self {
        Error::new_inner(
            ErrorCode::AdvanceError,
            Some(error.to_string().into()),
            Location::caller(),
        )
    }
}

impl From<std::str::Utf8Error> for Error {
    #[track_caller]
    fn from(error: std::str::Utf8Error) -> Self {
        Error::new_inner(
            ErrorCode::Utf8Error,
            Some(error.to_string().into()),
            Location::caller(),
        )
    }
}

impl From<core::array::TryFromSliceError> for Error {
    #[track_caller]
    fn from(error: core::array::TryFromSliceError) -> Self {
        Error::new_inner(
            ErrorCode::TryFromSliceError,
            Some(error.to_string().into()),
            Location::caller(),
        )
    }
}

// Static error messages with no useful extra information to log.

impl From<ProgramError> for ErrorKind {
    fn from(error: ProgramError) -> Self {
        ErrorKind::ProgramError(error)
    }
}

impl From<core::num::TryFromIntError> for ErrorKind {
    fn from(_error: core::num::TryFromIntError) -> Self {
        ErrorCode::TryFromIntError.into()
    }
}

impl From<std::cell::BorrowError> for ErrorKind {
    fn from(_error: std::cell::BorrowError) -> Self {
        ErrorCode::BorrowError.into()
    }
}

impl From<std::cell::BorrowMutError> for ErrorKind {
    fn from(_error: std::cell::BorrowMutError) -> Self {
        ErrorCode::BorrowMutError.into()
    }
}

impl From<solana_pubkey::PubkeyError> for ErrorKind {
    fn from(error: solana_pubkey::PubkeyError) -> Self {
        let program_error = match error {
            solana_pubkey::PubkeyError::MaxSeedLengthExceeded => {
                ProgramError::MaxSeedLengthExceeded
            }
            solana_pubkey::PubkeyError::InvalidSeeds => ProgramError::InvalidSeeds,
            solana_pubkey::PubkeyError::IllegalOwner => ProgramError::IllegalOwner,
        };
        ErrorKind::ProgramError(program_error)
    }
}

#[cfg(all(feature = "idl", not(target_os = "solana")))]
mod idl_impls {
    use super::*;
    impl From<star_frame_idl::Error> for Error {
        #[track_caller]
        fn from(error: star_frame_idl::Error) -> Self {
            Error::new_inner(
                ErrorCode::IdlError,
                Some(error.to_string().into()),
                Location::caller(),
            )
        }
    }

    impl From<serde_json::Error> for Error {
        #[track_caller]
        fn from(error: serde_json::Error) -> Self {
            Error::new_inner(
                ErrorCode::SerdeJsonError,
                Some(error.to_string().into()),
                Location::caller(),
            )
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_ensure() -> Result<(), Error> {
        ensure!(0 == 0, ProgramError::IllegalOwner, "Static str");
        ensure!(true, ProgramError::IllegalOwner);
        ensure!(true, ErrorCode::BorrowError, "Hello {}!", "world");
        let res: Result<(), Error> = (|| {
            ensure_eq!(0, 1, ProgramError::IllegalOwner, "Test {:?}", "aaa");
            ensure_eq!(0, 1, ProgramError::IllegalOwner);
            ensure_ne!(0, 1, ProgramError::IllegalOwner, "Test {}", "aaa");
            ensure_ne!(0, 1, ProgramError::IllegalOwner);
            Ok(())
        })();

        let res = res.ctx("AAA").unwrap_err();

        res.log();
        println!("{res}");
        Ok(())
    }

    #[test]
    fn test_bail() {
        let _: fn() -> Result<(), Error> = || bail!(ProgramError::IllegalOwner, "Static str");
        let _: fn() -> Result<(), Error> = || bail!(ProgramError::IllegalOwner);
        let _: fn() -> Result<(), Error> = || bail!(ErrorCode::BorrowError, "Hello {}!", "world");
    }
}