pina 0.8.0

a solana and pinocchio smart contract framework
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
#![allow(unsafe_code)]

use core::slice::from_raw_parts;
use core::slice::from_raw_parts_mut;

use pinocchio::ProgramResult;
use pinocchio_system::instructions::Transfer;

use crate::AccountDeserialize;
use crate::AccountInfoValidation;
#[cfg(feature = "token")]
use crate::AccountValidation;
use crate::AccountView;
use crate::Address;
use crate::AsAccount;
#[cfg(feature = "token")]
use crate::AsTokenAccount;
use crate::CloseAccountWithRecipient;
use crate::HasDiscriminator;
use crate::LamportTransfer;
use crate::Pod;
use crate::ProgramError;
use crate::log;
use crate::log_caller;

const SYSVAR_ID: Address = crate::address!("Sysvar1111111111111111111111111111111111111");

impl AccountInfoValidation for AccountView {
	#[track_caller]
	fn assert_signer(&self) -> Result<&Self, ProgramError> {
		if !self.is_signer() {
			log!(
				"address: {} is missing a required signature",
				self.address().as_ref()
			);
			log_caller();

			return Err(ProgramError::MissingRequiredSignature);
		}

		Ok(self)
	}

	#[track_caller]
	fn assert_writable(&self) -> Result<&Self, ProgramError> {
		if !self.is_writable() {
			log!(
				"address: {} has not been marked as writable",
				self.address().as_ref()
			);
			log_caller();

			return Err(ProgramError::InvalidAccountData);
		}

		Ok(self)
	}

	#[track_caller]
	fn assert_executable(&self) -> Result<&Self, ProgramError> {
		if !self.executable() {
			log!("address: {} is not executable", self.address().as_ref());
			log_caller();

			return Err(ProgramError::InvalidAccountData);
		}

		Ok(self)
	}

	#[track_caller]
	fn assert_data_len(&self, len: usize) -> Result<&Self, ProgramError> {
		if self.data_len() != len {
			log!(
				"address: {} has an incorrect length",
				self.address().as_ref()
			);
			log_caller();

			return Err(ProgramError::InvalidAccountData);
		}

		Ok(self)
	}

	#[track_caller]
	fn assert_empty(&self) -> Result<&Self, ProgramError> {
		if !self.is_data_empty() {
			log!("address: {} is not empty", self.address().as_ref());
			log_caller();

			return Err(ProgramError::AccountAlreadyInitialized);
		}

		Ok(self)
	}

	#[track_caller]
	fn assert_not_empty(&self) -> Result<&Self, ProgramError> {
		if self.is_data_empty() {
			log!("address: {} is empty", self.address().as_ref());
			log_caller();

			return Err(ProgramError::UninitializedAccount);
		}

		Ok(self)
	}

	#[track_caller]
	fn assert_program(&self, program_id: &Address) -> Result<&Self, ProgramError> {
		self.assert_address(program_id)?.assert_executable()
	}

	fn assert_type<T: HasDiscriminator>(
		&self,
		program_id: &Address,
	) -> Result<&Self, ProgramError> {
		self.assert_owner(program_id)?;
		let data = self.try_borrow()?;

		if !T::matches_discriminator(&data) {
			log!(
				"address: {} has invalid discriminator",
				self.address().as_ref()
			);
			log_caller();

			return Err(ProgramError::InvalidAccountData);
		}

		if data.len() != size_of::<T>() {
			log!(
				"address: {} has invalid data length for the account type",
				self.address().as_ref()
			);
			log_caller();

			return Err(ProgramError::AccountDataTooSmall);
		}

		Ok(self)
	}

	#[track_caller]
	fn assert_sysvar(&self, sysvar_id: &Address) -> Result<&Self, ProgramError> {
		self.assert_owner(&SYSVAR_ID)?.assert_address(sysvar_id)
	}

	#[track_caller]
	fn assert_owner(&self, owner: &Address) -> Result<&Self, ProgramError> {
		// SAFETY: `owner()` is unsafe in pinocchio 0.10.x because it reads from
		// raw account memory. The Solana runtime guarantees this memory is valid
		// for the duration of the transaction.
		let account_owner = unsafe { self.owner() };
		if account_owner.ne(owner) {
			log!(
				"address: {} has invalid owner: {}, required: {}",
				self.address().as_ref(),
				account_owner.as_ref(),
				owner.as_ref()
			);
			log_caller();

			return Err(ProgramError::InvalidAccountOwner);
		}

		Ok(self)
	}

	#[track_caller]
	fn assert_owners(&self, owners: &[Address]) -> Result<&Self, ProgramError> {
		// SAFETY: see `assert_owner` above.
		let account_owner = unsafe { self.owner() };
		if owners.contains(account_owner) {
			return Ok(self);
		}

		log!(
			"address: {} has invalid owner: {}",
			self.address().as_ref(),
			account_owner.as_ref(),
		);
		log_caller();

		Err(ProgramError::InvalidAccountOwner)
	}

	#[track_caller]
	fn assert_address(&self, addr: &Address) -> Result<&Self, ProgramError> {
		if self.address() == addr {
			return Ok(self);
		}

		log!(
			"address: {} is invalid, expected: {}",
			self.address().as_ref(),
			addr.as_ref()
		);
		log_caller();

		Err(ProgramError::InvalidAccountData)
	}

	#[track_caller]
	fn assert_addresses(&self, addresses: &[Address]) -> Result<&Self, ProgramError> {
		if addresses.contains(self.address()) {
			return Ok(self);
		}

		log!("address: {} is invalid", self.address().as_ref());
		log_caller();

		Err(ProgramError::InvalidAccountData)
	}

	#[track_caller]
	fn assert_seeds(&self, seeds: &[&[u8]], program_id: &Address) -> Result<&Self, ProgramError> {
		let Some((pda, _bump)) = crate::try_find_program_address(seeds, program_id) else {
			log!(
				"could not find program address from seeds with program id: {}",
				program_id.as_ref()
			);
			log_caller();
			return Err(ProgramError::InvalidSeeds);
		};

		if self.address() == &pda {
			return Ok(self);
		}

		log!(
			"address: {} is invalid, expected pda: {}",
			self.address().as_ref(),
			pda.as_ref()
		);
		log_caller();

		Err(ProgramError::InvalidSeeds)
	}

	#[track_caller]
	fn assert_seeds_with_bump(
		&self,
		seeds: &[&[u8]],
		program_id: &Address,
	) -> Result<&Self, ProgramError> {
		let pda = match crate::create_program_address(seeds, program_id) {
			Ok(pda) => pda,
			Err(_error) => {
				log!(
					"could not create pda for address: {}, with provided seeds and bump",
					self.address().as_ref(),
				);
				log_caller();

				return Err(ProgramError::InvalidSeeds);
			}
		};

		if &pda != self.address() {
			log!(
				"address: {} is invalid, expected pda: {}",
				self.address().as_ref(),
				pda.as_ref()
			);
			log_caller();

			return Err(ProgramError::InvalidSeeds);
		}

		Ok(self)
	}

	#[track_caller]
	fn assert_canonical_bump(
		&self,
		seeds: &[&[u8]],
		program_id: &Address,
	) -> Result<u8, ProgramError> {
		let Some((pda, bump)) = crate::try_find_program_address(seeds, program_id) else {
			log!(
				"could not find program address from seeds with program id: {}",
				program_id.as_ref()
			);
			log_caller();
			return Err(ProgramError::InvalidSeeds);
		};

		if pda.eq(self.address()) {
			return Ok(bump);
		}

		log!(
			"address: {} is invalid, expected pda: {}",
			self.address().as_ref(),
			pda.as_ref()
		);
		log_caller();

		Err(ProgramError::InvalidSeeds)
	}

	#[cfg(feature = "token")]
	#[track_caller]
	fn assert_associated_token_address(
		&self,
		wallet: &Address,
		mint: &Address,
		token_program: &Address,
	) -> Result<&Self, ProgramError> {
		let Some((ata_address, _bump)) =
			crate::try_get_associated_token_address(wallet, mint, token_program)
		else {
			log!(
				"could not find associated token address for wallet: {}, mint: {}",
				wallet.as_ref(),
				mint.as_ref(),
			);
			log_caller();

			return Err(ProgramError::InvalidSeeds);
		};

		if ata_address.eq(self.address()) {
			return Ok(self);
		}

		log!(
			"address: {} is invalid, expected associated token address: {}",
			self.address().as_ref(),
			ata_address.as_ref()
		);
		log_caller();

		Err(ProgramError::InvalidSeeds)
	}
}

impl AsAccount for AccountView {
	#[track_caller]
	fn as_account<T>(&self, program_id: &Address) -> Result<&T, ProgramError>
	where
		T: AccountDeserialize + HasDiscriminator + Pod,
	{
		self.assert_owner(program_id)?;
		self.assert_data_len(size_of::<T>())?;

		// SAFETY: `try_borrow` yields a guard-backed slice of the account data.
		// We rebuild a raw-parts slice from the same pointer with exactly
		// `size_of::<T>()` bytes, which is guaranteed by `assert_data_len` above.
		// `T::try_from_bytes` then validates the discriminator and performs the
		// bytemuck cast.
		//
		// The returned `&T` intentionally outlives the temporary borrow guard, so
		// callers must not create overlapping mutable borrows of the same account
		// while the reference is still in use.
		unsafe { T::try_from_bytes(from_raw_parts(self.try_borrow()?.as_ptr(), size_of::<T>())) }
	}

	#[track_caller]
	fn as_account_mut<T>(&self, program_id: &Address) -> Result<&mut T, ProgramError>
	where
		T: AccountDeserialize + HasDiscriminator + Pod,
	{
		self.assert_owner(program_id)?;
		self.assert_data_len(size_of::<T>())?;

		// SAFETY: `try_borrow_mut` yields exclusive access to the backing bytes,
		// and `assert_data_len` guarantees the slice is exactly `size_of::<T>()`
		// bytes. `T::try_from_bytes_mut` then validates the discriminator and
		// performs the bytemuck cast.
		//
		// The returned `&mut T` intentionally outlives the temporary borrow
		// guard, so callers must not create any overlapping borrows or aliasing
		// mutable views of the same account while the reference is still in use.
		unsafe {
			T::try_from_bytes_mut(from_raw_parts_mut(
				self.try_borrow_mut()?.as_mut_ptr(),
				size_of::<T>(),
			))
		}
	}
}

/// Implements `AccountValidation` for a token-related type. All four assertion
/// methods follow the same pattern: check the condition, log on failure, and
/// return the appropriate error.
#[cfg(feature = "token")]
macro_rules! impl_account_validation {
	($type:ty, $label:literal) => {
		impl AccountValidation for $type {
			#[track_caller]
			fn assert<F>(&self, condition: F) -> Result<&Self, ProgramError>
			where
				F: Fn(&Self) -> bool,
			{
				if !condition(self) {
					log!($label);
					log_caller();
					return Err(ProgramError::InvalidAccountData);
				}
				Ok(self)
			}

			#[track_caller]
			fn assert_msg<F>(&self, condition: F, log: &str) -> Result<&Self, ProgramError>
			where
				F: Fn(&Self) -> bool,
			{
				match crate::assert(condition(self), ProgramError::InvalidAccountData, log) {
					Err(err) => Err(err),
					Ok(()) => Ok(self),
				}
			}

			#[track_caller]
			fn assert_mut<F>(&mut self, condition: F) -> Result<&mut Self, ProgramError>
			where
				F: Fn(&Self) -> bool,
			{
				if !condition(self) {
					log!($label);
					log_caller();
					return Err(ProgramError::InvalidAccountData);
				}
				Ok(self)
			}

			#[track_caller]
			fn assert_mut_msg<F>(
				&mut self,
				condition: F,
				log: &str,
			) -> Result<&mut Self, ProgramError>
			where
				F: Fn(&Self) -> bool,
			{
				match crate::assert(condition(self), ProgramError::InvalidAccountData, log) {
					Err(err) => Err(err),
					Ok(()) => Ok(self),
				}
			}
		}
	};
}

#[cfg(feature = "token")]
impl_account_validation!(crate::token::state::Mint, "Mint account data is invalid");
#[cfg(feature = "token")]
impl_account_validation!(
	crate::token_2022::state::Mint,
	"Mint account data is invalid"
);
#[cfg(feature = "token")]
impl_account_validation!(
	crate::token::state::TokenAccount,
	"Token account data is invalid"
);
#[cfg(feature = "token")]
impl_account_validation!(
	crate::token_2022::state::TokenAccount,
	"Token account data is invalid"
);

#[cfg(feature = "token")]
impl AsTokenAccount for AccountView {
	#[track_caller]
	fn as_token_mint(&self) -> Result<&crate::token::state::Mint, ProgramError> {
		self.check_borrow()?;

		// SECURITY: relies on pinocchio's internal layout validation inside
		// `from_account_view_unchecked`. Callers should verify ownership before
		// trusting the result.
		unsafe { crate::token::state::Mint::from_account_view_unchecked(self) }
	}

	#[track_caller]
	fn as_token_mint_checked(&self) -> Result<&crate::token::state::Mint, ProgramError> {
		self.as_token_mint_checked_with_owners(&[crate::token::ID])
	}

	#[track_caller]
	fn as_token_mint_checked_with_owners(
		&self,
		owners: &[Address],
	) -> Result<&crate::token::state::Mint, ProgramError> {
		self.assert_owners(owners)?;
		self.as_token_mint()
	}

	fn as_token_account(&self) -> Result<&crate::token::state::TokenAccount, ProgramError> {
		self.check_borrow()?;

		// SAFETY: `check_borrow()` verified the account is not already mutably
		// borrowed. `from_account_view_unchecked` performs a pointer cast from
		// the account data to the target type layout. The caller is responsible
		// for verifying ownership before trusting the result — the `_checked`
		// variants handle this automatically.
		unsafe { crate::token::state::TokenAccount::from_account_view_unchecked(self) }
	}

	#[track_caller]
	fn as_token_account_checked(&self) -> Result<&crate::token::state::TokenAccount, ProgramError> {
		self.as_token_account_checked_with_owners(&[crate::token::ID])
	}

	#[track_caller]
	fn as_token_account_checked_with_owners(
		&self,
		owners: &[Address],
	) -> Result<&crate::token::state::TokenAccount, ProgramError> {
		self.assert_owners(owners)?;
		self.as_token_account()
	}

	fn as_token_2022_mint(&self) -> Result<&crate::token_2022::state::Mint, ProgramError> {
		self.check_borrow()?;

		// SAFETY: `check_borrow()` verified the account is not already mutably
		// borrowed. `from_account_view_unchecked` performs a pointer cast from
		// the account data to the target type layout. The caller is responsible
		// for verifying ownership before trusting the result — the `_checked`
		// variants handle this automatically.
		unsafe { crate::token_2022::state::Mint::from_account_view_unchecked(self) }
	}

	#[track_caller]
	fn as_token_2022_mint_checked(&self) -> Result<&crate::token_2022::state::Mint, ProgramError> {
		self.as_token_2022_mint_checked_with_owners(&[crate::token_2022::ID])
	}

	#[track_caller]
	fn as_token_2022_mint_checked_with_owners(
		&self,
		owners: &[Address],
	) -> Result<&crate::token_2022::state::Mint, ProgramError> {
		self.assert_owners(owners)?;
		self.as_token_2022_mint()
	}

	fn as_token_2022_account(
		&self,
	) -> Result<&crate::token_2022::state::TokenAccount, ProgramError> {
		self.check_borrow()?;

		// SAFETY: `check_borrow()` verified the account is not already mutably
		// borrowed. `from_account_view_unchecked` performs a pointer cast from
		// the account data to the target type layout. The caller is responsible
		// for verifying ownership before trusting the result — the `_checked`
		// variants handle this automatically.
		unsafe { crate::token_2022::state::TokenAccount::from_account_view_unchecked(self) }
	}

	#[track_caller]
	fn as_token_2022_account_checked(
		&self,
	) -> Result<&crate::token_2022::state::TokenAccount, ProgramError> {
		self.as_token_2022_account_checked_with_owners(&[crate::token_2022::ID])
	}

	#[track_caller]
	fn as_token_2022_account_checked_with_owners(
		&self,
		owners: &[Address],
	) -> Result<&crate::token_2022::state::TokenAccount, ProgramError> {
		self.assert_owners(owners)?;
		self.as_token_2022_account()
	}

	fn as_associated_token_account(
		&self,
		owner: &Address,
		mint: &Address,
		token_program: &Address,
	) -> Result<&crate::token::state::TokenAccount, ProgramError> {
		self.check_borrow()?;

		// SAFETY: `check_borrow()` verified the account is not already mutably
		// borrowed. `from_account_view_unchecked` performs a pointer cast from
		// the account data to the target type layout. The caller is responsible
		// for verifying ownership before trusting the result — the `_checked`
		// variants handle this automatically. Additionally, the address is
		// verified against the derived ATA address before the unchecked cast.
		unsafe {
			crate::token::state::TokenAccount::from_account_view_unchecked(
				self.assert_associated_token_address(owner, mint, token_program)?,
			)
		}
	}

	#[track_caller]
	fn as_associated_token_account_checked(
		&self,
		owner: &Address,
		mint: &Address,
		token_program: &Address,
	) -> Result<&crate::token::state::TokenAccount, ProgramError> {
		self.assert_owner(token_program)?;
		self.as_associated_token_account(owner, mint, token_program)
	}
}

fn checked_send_balances(
	current: u64,
	recipient_balance: u64,
	lamports: u64,
) -> Result<(u64, u64), ProgramError> {
	let new_balance = current
		.checked_sub(lamports)
		.ok_or(ProgramError::InsufficientFunds)?;
	let new_recipient_balance = recipient_balance
		.checked_add(lamports)
		.ok_or(ProgramError::ArithmeticOverflow)?;

	Ok((new_balance, new_recipient_balance))
}

fn checked_close_balance(sender_balance: u64, recipient_balance: u64) -> Result<u64, ProgramError> {
	recipient_balance
		.checked_add(sender_balance)
		.ok_or(ProgramError::ArithmeticOverflow)
}

impl<'a> LamportTransfer<'a> for AccountView {
	/// Send the specified lamports to the `recipient` account.
	/// The sender must be writable and owned by the executing program.
	#[inline(always)]
	#[track_caller]
	fn send(&'a self, lamports: u64, recipient: &'a AccountView) -> ProgramResult {
		self.assert_writable()?;
		recipient.assert_writable()?;

		if self.address() == recipient.address() {
			log!("Could not send lamports: sender and recipient must differ");
			log_caller();
			return Err(ProgramError::InvalidArgument);
		}

		let current = self.lamports();
		let recipient_balance = recipient.lamports();
		let (new_balance, new_recipient_balance) =
			checked_send_balances(current, recipient_balance, lamports).map_err(|error| {
				match error {
					ProgramError::InsufficientFunds => {
						log!("Could not subtract lamports: insufficient funds");
					}
					ProgramError::ArithmeticOverflow => {
						log!("Could not add lamports: arithmetic overflow");
					}
					_ => {}
				}
				log_caller();
				error
			})?;

		self.set_lamports(new_balance);
		recipient.set_lamports(new_recipient_balance);

		Ok(())
	}

	/// The `from` account must be mutable and a signer for this to be
	/// possible.
	#[inline(always)]
	fn collect(&'a self, lamports: u64, from: &'a AccountView) -> Result<(), ProgramError> {
		Transfer {
			from,
			to: self,
			lamports,
		}
		.invoke()
	}
}

impl<'a> CloseAccountWithRecipient<'a> for AccountView {
	#[track_caller]
	fn close_with_recipient(&'a self, recipient: &'a AccountView) -> ProgramResult {
		self.assert_writable()?;
		recipient.assert_writable()?;

		if self.address() == recipient.address() {
			log!("Could not close account: recipient must differ from account");
			log_caller();
			return Err(ProgramError::InvalidArgument);
		}

		let new_balance = checked_close_balance(self.lamports(), recipient.lamports())
			.inspect_err(|_| {
				log!("Could not close account: lamport overflow");
				log_caller();
			})?;
		recipient.set_lamports(new_balance);
		self.set_lamports(0);
		self.resize(0)?;
		self.close()
	}
}

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

	#[test]
	fn checked_send_balances_rejects_insufficient_funds() {
		let result = checked_send_balances(3, 10, 4);
		assert_eq!(result, Err(ProgramError::InsufficientFunds));
	}

	#[test]
	fn checked_send_balances_rejects_destination_overflow() {
		let result = checked_send_balances(10, u64::MAX, 1);
		assert_eq!(result, Err(ProgramError::ArithmeticOverflow));
	}

	#[test]
	fn checked_send_balances_conserves_lamports() {
		let (sender, recipient) = checked_send_balances(10, 4, 3)
			.unwrap_or_else(|err| panic!("expected valid transfer: {err:?}"));
		assert_eq!(sender + recipient, 14);
	}

	#[test]
	fn checked_close_balance_rejects_overflow() {
		let result = checked_close_balance(1, u64::MAX);
		assert_eq!(result, Err(ProgramError::ArithmeticOverflow));
	}

	#[test]
	fn checked_close_balance_moves_all_lamports() {
		let result = checked_close_balance(7, 2)
			.unwrap_or_else(|err| panic!("expected valid close balance: {err:?}"));
		assert_eq!(result, 9);
	}

	#[test]
	fn checked_send_balances_exact_balance() {
		let (sender, recipient) = checked_send_balances(5, 3, 5)
			.unwrap_or_else(|err| panic!("expected valid transfer: {err:?}"));
		assert_eq!(sender, 0);
		assert_eq!(recipient, 8);
	}

	#[test]
	fn checked_send_balances_zero_transfer() {
		let (sender, recipient) = checked_send_balances(10, 5, 0)
			.unwrap_or_else(|err| panic!("expected valid transfer: {err:?}"));
		assert_eq!(sender, 10);
		assert_eq!(recipient, 5);
	}

	#[test]
	fn checked_send_balances_max_values() {
		// Test with large values near u64::MAX boundaries.
		let result = checked_send_balances(u64::MAX, 0, u64::MAX);
		let (sender, recipient) =
			result.unwrap_or_else(|err| panic!("expected valid transfer: {err:?}"));
		assert_eq!(sender, 0);
		assert_eq!(recipient, u64::MAX);
	}

	#[test]
	fn checked_close_balance_zero_sender() {
		let result = checked_close_balance(0, 5)
			.unwrap_or_else(|err| panic!("expected valid close: {err:?}"));
		assert_eq!(result, 5);
	}

	#[test]
	fn checked_close_balance_both_zero() {
		let result = checked_close_balance(0, 0)
			.unwrap_or_else(|err| panic!("expected valid close: {err:?}"));
		assert_eq!(result, 0);
	}

	#[test]
	fn checked_close_balance_max_sender_zero_recipient() {
		let result = checked_close_balance(u64::MAX, 0)
			.unwrap_or_else(|err| panic!("expected valid close: {err:?}"));
		assert_eq!(result, u64::MAX);
	}
}