sendfun-sdk 4.0.0

Rust SDK for send.fun programs
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
//! Reads the transfer fee and the pause of a Token-2022 mint from raw account
//! data.
//!
//! The fee is for the [`math::amm`](crate::math::amm) quotes. Cache a
//! `TransferFeeConfig` only while its `transfer_fee_config_authority` is
//! `None`.

use bytemuck::Pod;
use solana_address::Address;
use solana_program::program_error::ProgramError;
use spl_token_2022_interface::error::TokenError;
use spl_token_2022_interface::extension::pausable::PausableConfig;
use spl_token_2022_interface::extension::{
	AccountType, BaseStateWithExtensions, Extension, PodStateWithExtensions,
};
use spl_token_2022_interface::pod::PodMint;

use crate::constants::{TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID};
use crate::math::amm::MintFee;

pub use spl_token_2022_interface::extension::transfer_fee::{
	TransferFee, TransferFeeConfig,
};

/// A TLV entry header: the `u16` type, then the `u16` length.
const TLV_HEADER_LEN: usize = 4;

/// Unpacks a mint and its extensions.
///
/// `Ok(None)` for an SPL Token mint, which has none. Fails with
/// `ProgramError::IncorrectProgramId` if no token program owns the mint, and
/// with another error if its data is not an initialized mint.
pub fn mint_extensions<'a>(
	data: &'a [u8],
	owner: &Address,
) -> Result<Option<PodStateWithExtensions<'a, PodMint>>, ProgramError> {
	if owner == &TOKEN_PROGRAM_ID {
		spl_token_mint(data)?;
		return Ok(None);
	}
	if owner != &TOKEN_2022_PROGRAM_ID {
		return Err(ProgramError::IncorrectProgramId);
	}
	PodStateWithExtensions::<PodMint>::unpack(data).map(Some)
}

/// An SPL Token mint: the base mint of Token-2022, with nothing after it.
/// `unpack` refuses one that is not initialized.
pub(crate) fn spl_token_mint(data: &[u8]) -> Result<&PodMint, ProgramError> {
	if data.len() != size_of::<PodMint>() {
		return Err(ProgramError::InvalidAccountData);
	}
	Ok(PodStateWithExtensions::<PodMint>::unpack(data)?.base)
}

/// Reads the mint extension `V`.
///
/// `Ok(None)` only when the mint does not have `V`. A malformed extension
/// region is an error, not `Ok(None)`. An account extension type fails with
/// `ProgramError::InvalidAccountData`.
pub fn extension<'a, V: Extension + Pod>(
	mint: &'a PodStateWithExtensions<'_, PodMint>,
) -> Result<Option<&'a V>, ProgramError> {
	match mint.get_extension::<V>() {
		Ok(value) => Ok(Some(value)),
		// The walk reached a zero type before `V`.
		Err(error) if error == TokenError::ExtensionNotFound.into() => Ok(None),
		// The walk ran off the end, the data is cut, or `V` is an account
		// extension. Token-2022 allocates the exact size, so a clean end means
		// `V` is absent.
		Err(ProgramError::InvalidAccountData)
			if V::TYPE.get_account_type() == AccountType::Mint
				&& ends_cleanly(mint.get_tlv_data()) =>
		{
			Ok(None)
		}
		Err(error) => Err(error),
	}
}

/// `true` if every TLV entry is whole, as SPL walks the entries.
/// Does not parse types as `ExtensionType`: an unknown type must not make a
/// fee-free mint unreadable.
fn ends_cleanly(tlv: &[u8]) -> bool {
	let mut rest = tlv;
	loop {
		let Some(&[type_low, type_high]) = rest.get(..2) else {
			return true;
		};
		if u16::from_le_bytes([type_low, type_high]) == 0 {
			return true;
		}
		let Some(&[length_low, length_high]) = rest.get(2..TLV_HEADER_LEN)
		else {
			return false;
		};
		let length = usize::from(u16::from_le_bytes([length_low, length_high]));
		let Some(next) = TLV_HEADER_LEN
			.checked_add(length)
			.and_then(|end| rest.get(end..))
		else {
			return false;
		};
		rest = next;
	}
}

#[must_use]
pub fn mint_fee(fee: &TransferFee) -> MintFee {
	MintFee {
		bps: fee.transfer_fee_basis_points.into(),
		maximum_fee: fee.maximum_fee.into(),
	}
}

/// The fees of a mint's `TransferFeeConfig`, and the epoch of the read.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FeeSchedule {
	pub older: MintFee,
	pub newer: MintFee,
	/// The first epoch of `newer`.
	pub newer_epoch: u64,
	/// The epoch the mint was read at.
	pub read_epoch: u64,
}

impl FeeSchedule {
	/// The schedule of `config`, read at `read_epoch`.
	pub(crate) fn of(config: &TransferFeeConfig, read_epoch: u64) -> Self {
		Self {
			older: mint_fee(&config.older_transfer_fee),
			newer: mint_fee(&config.newer_transfer_fee),
			newer_epoch: config.newer_transfer_fee.epoch.into(),
			read_epoch,
		}
	}

	/// The fee at `read_epoch`. Builders use this.
	#[must_use]
	pub const fn fee(&self) -> MintFee {
		self.fee_at(self.read_epoch)
	}

	/// The fee at `epoch`, as SPL `get_epoch_fee`: `newer` when
	/// `epoch >= newer_epoch`, else `older`.
	#[must_use]
	pub const fn fee_at(&self, epoch: u64) -> MintFee {
		if epoch >= self.newer_epoch {
			self.newer
		} else {
			self.older
		}
	}
}

/// The transfer fee of a mint at `epoch`. `Ok(None)` only when the mint has no
/// `TransferFeeConfig`. A 0 bps config gives `Some`.
pub fn mint_fee_at_epoch(
	data: &[u8],
	owner: &Address,
	epoch: u64,
) -> Result<Option<MintFee>, ProgramError> {
	let Some(mint) = mint_extensions(data, owner)? else {
		return Ok(None);
	};
	Ok(extension::<TransferFeeConfig>(&mint)?
		.map(|config| mint_fee(config.get_epoch_fee(epoch))))
}

/// `true` when the mint's `PausableConfig` is paused. Token-2022 then fails
/// every transfer of the mint. An SPL Token mint cannot be paused.
pub fn mint_paused(data: &[u8], owner: &Address) -> Result<bool, ProgramError> {
	let Some(mint) = mint_extensions(data, owner)? else {
		return Ok(false);
	};
	Ok(extension::<PausableConfig>(&mint)?
		.is_some_and(|config| bool::from(config.paused)))
}

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

	use spl_token_2022_interface::extension::transfer_fee::TransferFeeAmount;

	/// SPL's `unpack` refuses a mint with this byte unset.
	const IS_INITIALIZED_OFFSET: usize = 45;

	/// Token-2022 pads the mint to the token-account length before this byte.
	const ACCOUNT_TYPE_OFFSET: usize = 165;

	const TLV_START: usize = 166;

	const FEE_TYPE: u16 = 1;

	/// Above every type that SPL 3.1.1 defines.
	const FUTURE_TYPE: u16 = 250;

	const NEWER: Option<MintFee> = Some(MintFee {
		bps: 250,
		maximum_fee: 2_000,
	});

	fn entry(epoch: u64, maximum_fee: u64, basis_points: u16) -> TransferFee {
		TransferFee {
			epoch: epoch.into(),
			maximum_fee: maximum_fee.into(),
			transfer_fee_basis_points: basis_points.into(),
		}
	}

	fn fee_payload(authority: Option<Address>) -> Vec<u8> {
		bytemuck::bytes_of(&TransferFeeConfig {
			transfer_fee_config_authority: authority.try_into().unwrap(),
			older_transfer_fee: entry(5, 1_000, 100),
			newer_transfer_fee: entry(7, 2_000, 250),
			..TransferFeeConfig::default()
		})
		.to_vec()
	}

	/// `MetadataPointer`, then `TokenMetadata`. `create_token` writes both.
	fn other_extensions() -> Vec<(u16, Vec<u8>)> {
		vec![(18, vec![0; 64]), (19, vec![0; 90])]
	}

	fn tlv_image(entries: &[(u16, Vec<u8>)]) -> Vec<u8> {
		let mut data = vec![0_u8; ACCOUNT_TYPE_OFFSET];
		data[IS_INITIALIZED_OFFSET] = 1;
		// `AccountType::Mint`.
		data.push(1);
		for (extension_type, payload) in entries {
			data.extend_from_slice(&extension_type.to_le_bytes());
			data.extend_from_slice(
				&u16::try_from(payload.len()).unwrap().to_le_bytes(),
			);
			data.extend_from_slice(payload);
		}
		data
	}

	fn fee(data: &[u8]) -> Result<Option<MintFee>, ProgramError> {
		mint_fee_at_epoch(data, &TOKEN_2022_PROGRAM_ID, 7)
	}

	#[test]
	fn the_walk_finds_the_config_wherever_it_sits() {
		for at in 0..=2 {
			let mut entries = other_extensions();
			entries.insert(at, (FEE_TYPE, fee_payload(None)));
			assert_eq!(fee(&tlv_image(&entries)), Ok(NEWER), "at {at}");
		}
	}

	#[test]
	fn the_owner_picks_the_reader() {
		let image = tlv_image(&[(FEE_TYPE, fee_payload(None))]);
		assert_eq!(fee(&image), Ok(NEWER));
		// An SPL Token mint is the 82-byte base mint alone: no extension.
		let mut spl_mint = [0; 82];
		spl_mint[45] = 1;
		assert_eq!(
			mint_fee_at_epoch(&spl_mint, &TOKEN_PROGRAM_ID, 7),
			Ok(None)
		);
		// SPL Token never writes a TLV region.
		assert_eq!(
			mint_fee_at_epoch(&image, &TOKEN_PROGRAM_ID, 7),
			Err(ProgramError::InvalidAccountData)
		);
		assert_eq!(
			mint_fee_at_epoch(&spl_mint.map(|_| 0), &TOKEN_PROGRAM_ID, 7),
			Err(ProgramError::UninitializedAccount)
		);
		assert_eq!(
			mint_fee_at_epoch(&image, &crate::constants::SYSTEM_PROGRAM_ID, 7),
			Err(ProgramError::IncorrectProgramId)
		);
	}

	const PAUSABLE_TYPE: u16 = 26;

	fn pausable_payload(paused: bool) -> Vec<u8> {
		bytemuck::bytes_of(&PausableConfig {
			paused: paused.into(),
			..PausableConfig::default()
		})
		.to_vec()
	}

	#[test]
	fn the_pause_reads_off_the_pausable_config() {
		for paused in [false, true] {
			let mut entries = other_extensions();
			entries.push((PAUSABLE_TYPE, pausable_payload(paused)));
			assert_eq!(
				mint_paused(&tlv_image(&entries), &TOKEN_2022_PROGRAM_ID),
				Ok(paused),
				"paused {paused}"
			);
		}
		assert_eq!(
			mint_paused(
				&tlv_image(&other_extensions()),
				&TOKEN_2022_PROGRAM_ID
			),
			Ok(false)
		);
	}

	#[test]
	fn the_owner_picks_the_pause_reader() {
		let mut spl_mint = [0; 82];
		spl_mint[IS_INITIALIZED_OFFSET] = 1;
		assert_eq!(mint_paused(&spl_mint, &TOKEN_PROGRAM_ID), Ok(false));
		let paused = tlv_image(&[(PAUSABLE_TYPE, pausable_payload(true))]);
		assert_eq!(
			mint_paused(&paused, &crate::constants::SYSTEM_PROGRAM_ID),
			Err(ProgramError::IncorrectProgramId)
		);
	}

	#[test]
	fn the_newer_entry_applies_from_its_own_epoch() {
		let image = tlv_image(&[(FEE_TYPE, fee_payload(None))]);
		assert_eq!(
			mint_fee_at_epoch(&image, &TOKEN_2022_PROGRAM_ID, 6),
			Ok(Some(MintFee {
				bps: 100,
				maximum_fee: 1_000,
			}))
		);
		assert_eq!(fee(&image), Ok(NEWER));
	}

	#[test]
	fn a_revoked_authority_reads_as_none() {
		for authority in [None, Some(Address::new_from_array([9; 32]))] {
			let image = tlv_image(&[(FEE_TYPE, fee_payload(authority))]);
			let mint = mint_extensions(&image, &TOKEN_2022_PROGRAM_ID)
				.unwrap()
				.unwrap();
			let config =
				extension::<TransferFeeConfig>(&mint).unwrap().unwrap();
			assert_eq!(
				Option::from(config.transfer_fee_config_authority),
				authority
			);
		}
	}

	#[test]
	fn a_bare_mint_has_no_tlv_region_to_walk() {
		let mut bare = tlv_image(&[]);
		bare.truncate(82);
		assert_eq!(fee(&bare), Ok(None));
		bare[IS_INITIALIZED_OFFSET] = 0;
		assert_eq!(fee(&bare), Err(ProgramError::UninitializedAccount));
	}

	/// Extensions that total `Multisig::LEN` get two bytes of padding. SPL
	/// reads one trailing byte as slack.
	#[test]
	fn a_region_that_ends_cleanly_carries_no_config() {
		for tail in [
			vec![],
			vec![0],
			vec![0; 2],
			vec![0; 3],
			vec![0; 512],
			vec![7],
		] {
			let mut image = tlv_image(&other_extensions());
			image.extend_from_slice(&tail);
			assert_eq!(fee(&image), Ok(None), "tail {tail:?}");
		}
	}

	/// Token-2022 also stops at the first match. It does not read the entries
	/// after it.
	#[test]
	fn a_cut_entry_past_the_config_is_not_read() {
		let mut image = tlv_image(&[(FEE_TYPE, fee_payload(None))]);
		image.extend_from_slice(&[18, 0, 64, 0]);
		assert_eq!(fee(&image), Ok(NEWER));
	}

	/// An account extension on a mint is a caller error, not an absent
	/// extension.
	#[test]
	fn an_account_extension_is_not_read_off_a_mint() {
		let image = tlv_image(&other_extensions());
		let mint = mint_extensions(&image, &TOKEN_2022_PROGRAM_ID)
			.unwrap()
			.unwrap();
		assert_eq!(
			extension::<TransferFeeAmount>(&mint),
			Err(ProgramError::InvalidAccountData)
		);
	}

	/// SPL's `get_extension_types` refuses unknown types. The region check must
	/// not use it.
	#[test]
	fn a_future_extension_type_leaves_the_mint_readable() {
		let future = (FUTURE_TYPE, vec![0; 16]);
		let fee_free = tlv_image(&[(18, vec![0; 64]), future.clone()]);
		let mint = mint_extensions(&fee_free, &TOKEN_2022_PROGRAM_ID)
			.unwrap()
			.unwrap();
		assert_eq!(
			mint.get_extension_types(),
			Err(ProgramError::InvalidAccountData)
		);
		assert_eq!(extension::<TransferFeeConfig>(&mint), Ok(None));
		let fee_after = tlv_image(&[future, (FEE_TYPE, fee_payload(None))]);
		assert_eq!(fee(&fee_after), Ok(NEWER));
	}

	#[test]
	fn a_cut_region_is_malformed() {
		let mut short = tlv_image(&[]);
		short.truncate(ACCOUNT_TYPE_OFFSET);
		let mut header = tlv_image(&other_extensions());
		header.truncate(TLV_START + 4 + 64 + 2);
		let mut overrun = tlv_image(&[(18, vec![0; 64])]);
		overrun.truncate(TLV_START + 4 + 32);
		let mut payload = tlv_image(&other_extensions());
		payload.extend_from_slice(&[18, 0, 64, 0]);
		let mut config = tlv_image(&[(FEE_TYPE, fee_payload(None))]);
		config.pop();
		for (label, image) in [
			("no account type", short),
			("cut header", header),
			("length past the end", overrun),
			("payload never arrives", payload),
			("config payload cut", config),
		] {
			assert_eq!(
				fee(&image),
				Err(ProgramError::InvalidAccountData),
				"{label}"
			);
		}
	}

	#[test]
	fn a_config_payload_of_the_wrong_length_is_malformed() {
		for length in [100_usize, 116] {
			let image = tlv_image(&[(FEE_TYPE, vec![0; length])]);
			assert_eq!(
				fee(&image),
				Err(ProgramError::InvalidArgument),
				"payload length {length}"
			);
		}
	}

	const OLDER: MintFee = MintFee {
		bps: 100,
		maximum_fee: 1_000,
	};

	/// The schedule of [`fee_payload`]: `OLDER` before epoch 7, then `NEWER`.
	fn schedule(read_epoch: u64) -> FeeSchedule {
		let config: TransferFeeConfig =
			bytemuck::pod_read_unaligned(&fee_payload(None));
		FeeSchedule::of(&config, read_epoch)
	}

	#[test]
	fn a_schedule_holds_both_entries_and_the_read_epoch() {
		assert_eq!(
			schedule(6),
			FeeSchedule {
				older: OLDER,
				newer: NEWER.unwrap(),
				newer_epoch: 7,
				read_epoch: 6,
			}
		);
	}

	#[test]
	fn the_newer_fee_applies_from_newer_epoch() {
		let schedule = schedule(0);
		assert_eq!(schedule.fee_at(6), OLDER);
		assert_eq!(schedule.fee_at(7), NEWER.unwrap());
		assert_eq!(schedule.fee_at(8), NEWER.unwrap());
		assert_eq!(schedule.fee_at(0), OLDER);
		assert_eq!(schedule.fee_at(u64::MAX), NEWER.unwrap());
	}

	#[test]
	fn fee_is_the_fee_at_the_read_epoch() {
		for (read_epoch, fee) in [
			(0, OLDER),
			(6, OLDER),
			(7, NEWER.unwrap()),
			(8, NEWER.unwrap()),
		] {
			let schedule = schedule(read_epoch);
			assert_eq!(schedule.fee(), fee, "read at {read_epoch}");
			assert_eq!(schedule.fee(), schedule.fee_at(read_epoch));
		}
	}

	/// SPL's `get_epoch_fee` picks the same entry at every epoch.
	#[test]
	fn fee_at_matches_get_epoch_fee() {
		let config: TransferFeeConfig =
			bytemuck::pod_read_unaligned(&fee_payload(None));
		let schedule = FeeSchedule::of(&config, 0);
		for epoch in [0, 5, 6, 7, 8, u64::MAX] {
			assert_eq!(
				schedule.fee_at(epoch),
				mint_fee(config.get_epoch_fee(epoch)),
				"epoch {epoch}"
			);
		}
	}

	#[test]
	fn a_non_mint_account_type_is_malformed() {
		let mut image = tlv_image(&[(FEE_TYPE, fee_payload(None))]);
		// `AccountType::Account`.
		image[ACCOUNT_TYPE_OFFSET] = 2;
		assert_eq!(fee(&image), Err(ProgramError::InvalidAccountData));
	}
}