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
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
//! Checks for a router that cannot simulate a trade. The builders do not run
//! them.
//!
//! [`trade`] resolves one trade direction from the [`MintInfo`] of each mint
//! and the router's cache. It refuses the direction for:
//!
//! - a `MintInfo` of another mint, a base mint that is not a Token-2022 mint,
//!   a quote token program that is not the quote mint's, or a `MintInfo` with
//!   a hook program and no hook;
//! - the resolver's refusals ([`HookError`]);
//! - a hook extra that wants writable an account that the chain holds
//!   read-only on a trade ([`Unroutable::WritableRepeat`]);
//! - a list that wants an extra to sign, or a list whose `Execute` holds an
//!   account in a role that the list does not declare. A hook that runs SPL's
//!   `check_account_infos` fails with `0xa261c2c0`.
//!
//! [`screen`] judges one direction for any trader. It runs [`trade`] for two
//! stand-in traders.
//!
//! [`MarketLoad`] loads and screens a market at each update. It names the
//! accounts to fetch, and gives each direction's [`Screen`], the cache that a
//! swap resolves from, and the accounts to declare for the next update.

use solana_address::Address;
use solana_instruction::Instruction;

use super::{Fetched, FetchedAccount, HookError, HookState, LegExecute, Step};
use crate::utils::{
	MintInfo, TradeAccounts, TradeDirection, TradeLegInput, TradeMints,
	TradeMode, check_base_mint, legs_of_trade,
};
use crate::{dex, launchpad};

/// Why a router leaves a trade direction out.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Unroutable {
	Hook(HookError),
	/// The lists read the data of these accounts, which the router has not
	/// cached. Add them to the cache for the next update.
	NotCached(Vec<Address>),
	/// A list reads the data of an account that depends on the trader.
	/// [`trade`] does not return it. A router returns it when the reads change
	/// with the trader.
	UncacheableRead,
	/// A list wants an extra to sign. Token-2022 clears the signer bit, and
	/// the hook's own check refuses all transfers of the mint.
	ExtraSigns,
	/// The hook's `Execute` holds an account in a role its list does not
	/// declare. In one case, an extra wants writable a read-only account of
	/// the `Execute`: its source, mint, destination, authority, validation
	/// account or an earlier read-only extra. In the other case, an extra
	/// wants read-only an account that an earlier extra holds writable.
	ExecuteRoleConflict,
	/// A hook extra wants writable an account that the chain holds read-only
	/// on a trade. A trade holds the market, the mints and the partner config
	/// read-only. The runtime holds the system program (also
	/// `DEFAULT_PARTNER`), the sysvars and the native programs read-only in
	/// all transactions.
	///
	/// It does not check Token-2022, the associated token program or the
	/// market's own program.
	WritableRepeat(Address),
	/// The `MintInfo` for this mint of the trade is the info of another mint.
	MintMismatch(Address),
	/// The base mint is not a Token-2022 mint.
	BaseNotToken2022(Address),
	/// The trade's `quote_token_program` is not the token program of the
	/// `MintInfo` of this quote mint. The program refuses the trade.
	QuoteTokenProgramMismatch(Address),
	/// The `MintInfo` of this mint has a hook program and no hook. The list
	/// comes only from the `MintInfo`, never from the router's cache. Read it
	/// with [`MintInfo::load`].
	HookNotRead(Address),
}

impl std::fmt::Display for Unroutable {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			Self::Hook(error) => error.fmt(f),
			Self::NotCached(_) => {
				write!(f, "transfer hook accounts not cached")
			}
			Self::UncacheableRead => write!(
				f,
				"a transfer hook reads an account that depends on the trader"
			),
			Self::ExtraSigns => {
				write!(f, "a transfer hook extra must sign")
			}
			Self::ExecuteRoleConflict => write!(
				f,
				"a transfer hook wants one account of its Execute both \
				 read-only and writable"
			),
			Self::WritableRepeat(account) => write!(
				f,
				"a transfer hook wants {account} writable, which the trade \
				 holds read-only"
			),
			Self::MintMismatch(mint) => write!(
				f,
				"the mint info is not the info of the trade's mint {mint}"
			),
			Self::BaseNotToken2022(mint) => {
				write!(f, "the base mint {mint} is not a Token-2022 mint")
			}
			Self::QuoteTokenProgramMismatch(mint) => write!(
				f,
				"the quote token program is not the token program of the quote \
				 mint {mint}"
			),
			Self::HookNotRead(mint) => {
				write!(f, "the mint {mint} has a hook program and no hook")
			}
		}
	}
}

impl std::error::Error for Unroutable {}

impl From<HookError> for Unroutable {
	fn from(error: HookError) -> Self {
		Self::Hook(error)
	}
}

/// A routable trade: its instruction with the hook accounts, and the accounts
/// whose data a list read. Cache these accounts for the next update.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Route {
	pub instruction: Instruction,
	pub reads: Vec<Address>,
}

/// The program a market trades on.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TradeProgram {
	Launchpad,
	Dex,
}

/// One trade, as a router would send it.
#[derive(Clone, Copy, Debug)]
pub struct TradeRoute<'r> {
	pub program: TradeProgram,
	pub trade: &'r TradeAccounts,
	/// The mint at `trade.base_mint`, from [`MintInfo::load`].
	pub base_mint_info: &'r MintInfo,
	/// The mint at `trade.quote_mint`, from [`MintInfo::load`].
	pub quote_mint_info: &'r MintInfo,
	pub direction: TradeDirection,
	pub mode: TradeMode,
	/// `amount_in` for `ExactIn`. `amount_out` for `ExactOut`.
	pub amount: u64,
	/// `min_amount_out` for `ExactIn`. `max_amount_in` for `ExactOut`.
	pub limit: u64,
}

impl TradeRoute<'_> {
	/// The trade instruction without hook accounts, and its legs.
	fn build(&self) -> (Instruction, super::HookLegs) {
		let input = TradeLegInput {
			accounts: *self.trade,
			direction: self.direction,
		};
		match self.program {
			TradeProgram::Launchpad => (
				launchpad::trade::trade_instruction(
					self.trade,
					launchpad::trade::TradeArgs {
						direction: self.direction,
						mode: self.mode,
						amount: self.amount,
						limit: self.limit,
					},
				),
				legs_of_trade(&input, launchpad::trade::WRITES_MARKET),
			),
			TradeProgram::Dex => (
				dex::trade::trade_instruction(
					self.trade,
					dex::trade::TradeArgs {
						direction: self.direction.into(),
						mode: self.mode,
						amount: self.amount,
						limit: self.limit,
					},
				),
				legs_of_trade(&input, dex::trade::WRITES_MARKET),
			),
		}
	}
}

/// Keys the runtime holds read-only in every transaction (agave's reserved
/// account keys): the system program, the sysvars and the native programs.
const DEMOTED: [Address; 31] = [
	solana_address::address!("11111111111111111111111111111111"),
	solana_address::address!("NativeLoader1111111111111111111111111111111"),
	solana_address::address!("BPFLoader1111111111111111111111111111111111"),
	solana_address::address!("BPFLoader2111111111111111111111111111111111"),
	solana_address::address!("BPFLoaderUpgradeab1e11111111111111111111111"),
	solana_address::address!("LoaderV411111111111111111111111111111111111"),
	solana_address::address!("ComputeBudget111111111111111111111111111111"),
	solana_address::address!("AddressLookupTab1e1111111111111111111111111"),
	solana_address::address!("Config1111111111111111111111111111111111111"),
	solana_address::address!("Stake11111111111111111111111111111111111111"),
	solana_address::address!("StakeConfig11111111111111111111111111111111"),
	solana_address::address!("Vote111111111111111111111111111111111111111"),
	solana_address::address!("Ed25519SigVerify111111111111111111111111111"),
	solana_address::address!("KeccakSecp256k11111111111111111111111111111"),
	solana_address::address!("Secp256r1SigVerify1111111111111111111111111"),
	solana_address::address!("Feature111111111111111111111111111111111111"),
	solana_address::address!("ZkE1Gama1Proof11111111111111111111111111111"),
	solana_address::address!("ZkTokenProof1111111111111111111111111111111"),
	solana_address::address!("Sysvar1111111111111111111111111111111111111"),
	solana_address::address!("SysvarC1ock11111111111111111111111111111111"),
	solana_address::address!("SysvarEpochRewards1111111111111111111111111"),
	solana_address::address!("SysvarEpochSchedu1e111111111111111111111111"),
	solana_address::address!("SysvarFees111111111111111111111111111111111"),
	solana_address::address!("Sysvar1nstructions1111111111111111111111111"),
	solana_address::address!("SysvarLastRestartS1ot1111111111111111111111"),
	solana_address::address!("SysvarRecentB1ockHashes11111111111111111111"),
	solana_address::address!("SysvarRent111111111111111111111111111111111"),
	solana_address::address!("SysvarRewards111111111111111111111111111111"),
	solana_address::address!("SysvarS1otHashes111111111111111111111111111"),
	solana_address::address!("SysvarS1otHistory11111111111111111111111111"),
	solana_address::address!("SysvarStakeHistory1111111111111111111111111"),
];

/// Resolves one trade direction and checks it.
///
/// Each hooked mint's list comes from its [`MintInfo`]'s [`HookState`]
/// (`MintInfo::missing` names what to insert). A list read looks in both
/// infos, then in `accounts`, the router's cache: the market's PDAs and the
/// trader's accounts. An account in neither gives [`Unroutable::NotCached`].
/// A hook-free mint's info holds no account, its own included.
///
/// [`HookState`]: super::HookState
pub fn trade<'a>(
	route: TradeRoute<'_>,
	accounts: impl Fn(&Address) -> Fetched<'a>,
) -> Result<Route, Unroutable> {
	let trade = route.trade;
	let mints = TradeMints {
		base: route.base_mint_info,
		quote: route.quote_mint_info,
	};
	check_mints(&route)?;
	let (mut instruction, legs) = route.build();
	let resolved = match super::resolve_market(mints, &legs, accounts)? {
		Step::Done(resolved) => resolved,
		Step::Fetch(addresses) => return Err(Unroutable::NotCached(addresses)),
	};
	for execute in &resolved.executes {
		screen_execute(execute)?;
	}
	let read_only = [
		trade.market,
		trade.base_mint,
		trade.quote_mint,
		trade.partner_config,
	];
	if let Some(meta) = resolved.accounts.iter().find(|meta| {
		meta.is_writable
			&& (read_only.contains(&meta.pubkey)
				|| DEMOTED.contains(&meta.pubkey))
	}) {
		return Err(Unroutable::WritableRepeat(meta.pubkey));
	}
	instruction.accounts.extend(resolved.accounts);
	Ok(Route {
		instruction,
		reads: resolved.reads,
	})
}

/// One trade direction as [`screen`] judges it for any trader.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Screen {
	/// `Ok` when the direction routes for any trader.
	pub route: Result<(), Unroutable>,
	/// The accounts that both stand-ins need and the cache lacks. Fetch them,
	/// add them to the cache and screen again.
	pub not_cached: Vec<Address>,
	/// [`trade`] for each stand-in trader.
	pub stand_ins: [Result<Route, Unroutable>; 2],
}

/// Two traders that no wallet holds. A list that reads an account whose key
/// or data differs between them depends on the trader.
const STAND_INS: [u8; 2] = [1, 5];

/// `trade` with a trader that no wallet holds. Its user, payer, base account
/// and quote account keys are arrays of `seed`, `seed + 1`, `seed + 2` and
/// `seed + 3`.
const fn stand_in(trade: &TradeAccounts, seed: u8) -> TradeAccounts {
	TradeAccounts {
		user: Address::new_from_array([seed; 32]),
		payer: Address::new_from_array([seed.wrapping_add(1); 32]),
		user_base_account: Address::new_from_array([seed.wrapping_add(2); 32]),
		user_quote_account: Address::new_from_array([seed.wrapping_add(3); 32]),
		..*trade
	}
}

/// Judges one trade direction for any trader. The trader accounts of
/// `route.trade` are not read.
///
/// It runs [`trade`] for two stand-in traders. The direction routes when both
/// resolve it with the same reads. When both stand-ins lack the same accounts,
/// it gives [`Unroutable::NotCached`]. When both fail alike, it gives that
/// error. When the stand-ins resolve differently, the lists depend on the
/// trader: [`Unroutable::UncacheableRead`].
///
/// A screen does not name the accounts that it found in `accounts`. A router
/// that serves only declared accounts must screen against a cache of only the
/// accounts that `not_cached` named in this update. It must declare each of
/// them for the next update. [`MarketLoad`] does this.
pub fn screen<'a>(
	route: TradeRoute<'_>,
	accounts: impl Fn(&Address) -> Fetched<'a>,
) -> Screen {
	let stand_ins = STAND_INS.map(|seed| {
		trade(
			TradeRoute {
				trade: &stand_in(route.trade, seed),
				..route
			},
			&accounts,
		)
	});
	let (route, not_cached) = match &stand_ins {
		[Ok(first), Ok(second)] => (
			if same(&first.reads, &second.reads) {
				Ok(())
			} else {
				Err(Unroutable::UncacheableRead)
			},
			Vec::new(),
		),
		[
			Err(Unroutable::NotCached(first)),
			Err(Unroutable::NotCached(second)),
		] if same(first, second) => {
			(Err(Unroutable::NotCached(first.clone())), first.clone())
		}
		[Err(first), Err(second)] if first == second => {
			(Err(first.clone()), Vec::new())
		}
		_ => (Err(Unroutable::UncacheableRead), Vec::new()),
	};
	Screen {
		route,
		not_cached,
		stand_ins,
	}
}

/// Both trade directions, in the order of [`LoadedMarket::screens`].
const DIRECTIONS: [TradeDirection; 2] =
	[TradeDirection::Buy, TradeDirection::Sell];

/// Loads and screens one market at each update, for a router.
///
/// Make a new load at each update, with the mints just read. Fetch what
/// [`missing`](Self::missing) names, [`insert`](Self::insert) each account
/// that the fetch gives, and call `missing` again. When it is empty, call
/// [`finish`](Self::finish). `missing` names each account once. Insert
/// nothing for an account that the router cannot fetch: a direction that
/// reads it does not route.
///
/// Declare [`LoadedMarket::declare`] for the next update. A router that
/// serves only declared accounts then loads one more link of a chain of reads
/// at each update.
#[derive(Clone, Debug)]
pub struct MarketLoad {
	program: TradeProgram,
	market: TradeAccounts,
	/// The base mint, then the quote mint.
	mints: [MintInfo; 2],
	/// Each account inserted in this load. The screens read only these.
	cache: HookState,
	/// Each account that `missing` named.
	named: Vec<Address>,
}

/// What [`MarketLoad::new`] takes.
#[derive(Clone, Debug)]
pub struct MarketLoadArgs {
	pub program: TradeProgram,
	/// The market's side of a trade. The load does not read its trader
	/// accounts.
	pub market: TradeAccounts,
	/// The mints of this update, from [`MintInfo::load`].
	pub base_mint_info: MintInfo,
	pub quote_mint_info: MintInfo,
}

impl MarketLoad {
	#[must_use]
	pub fn new(args: MarketLoadArgs) -> Self {
		Self {
			program: args.program,
			market: args.market,
			mints: [args.base_mint_info, args.quote_mint_info],
			cache: HookState::default(),
			named: Vec::new(),
		}
	}

	/// The accounts to fetch next: what [`MintInfo::missing`] names for each
	/// mint, and what the screens lack. It leaves out each account that it
	/// named before. Empty when the load can learn nothing more.
	///
	/// # Errors
	///
	/// The error of [`MintInfo::missing`].
	pub fn missing(&mut self) -> Result<Vec<Address>, HookError> {
		let mut next: Vec<Address> = Vec::new();
		for info in &self.mints {
			push_new(&mut next, &info.missing()?);
		}
		for screen in self.screens().iter().flatten() {
			push_new(&mut next, &screen.not_cached);
		}
		next.retain(|address| !self.named.contains(address));
		push_new(&mut self.named, &next);
		Ok(next)
	}

	/// Records what a fetch of `address` gave: `None` for no account. A mint
	/// whose [`MintInfo::missing`] names it also holds it.
	pub fn insert(
		&mut self,
		address: Address,
		account: Option<FetchedAccount>,
	) {
		for info in &mut self.mints {
			if info
				.missing()
				.is_ok_and(|missing| missing.contains(&address))
			{
				info.insert(address, account.clone());
			}
		}
		self.cache.insert(address, account);
	}

	#[must_use]
	pub fn finish(self) -> LoadedMarket {
		let screens = self.screens();
		let [base_mint_info, quote_mint_info] = self.mints;
		LoadedMarket {
			base_mint_info,
			quote_mint_info,
			cache: self.cache,
			screens,
			declare: self.named,
		}
	}

	/// Each direction, buy first, screened against the inserted accounts.
	/// `None` when neither mint has a hook.
	fn screens(&self) -> Option<[Screen; 2]> {
		let [base_mint_info, quote_mint_info] = &self.mints;
		if base_mint_info.hook_program.is_none()
			&& quote_mint_info.hook_program.is_none()
		{
			return None;
		}
		Some(DIRECTIONS.map(|direction| {
			screen(
				TradeRoute {
					program: self.program,
					trade: &self.market,
					base_mint_info,
					quote_mint_info,
					direction,
					// Both modes resolve alike: no leg's amount is known.
					mode: TradeMode::ExactIn,
					// `trade` refuses a list that reads the amount.
					amount: 0,
					limit: 0,
				},
				|address| self.cache.fetched(address),
			)
		}))
	}
}

/// A market as a [`MarketLoad`] read it.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct LoadedMarket {
	pub base_mint_info: MintInfo,
	pub quote_mint_info: MintInfo,
	/// Each account that the load fetched. A swap resolves from it and the
	/// mint infos with [`trade`].
	pub cache: HookState,
	/// The buy, then the sell, as [`screen`] judges each for any trader.
	/// `None` when neither mint has a hook: every trader builds the same
	/// hook-free trade.
	pub screens: Option<[Screen; 2]>,
	/// Each account that the load named. Declare them for the next update.
	pub declare: Vec<Address>,
}

fn push_new(all: &mut Vec<Address>, keys: &[Address]) {
	for key in keys {
		if !all.contains(key) {
			all.push(*key);
		}
	}
}

/// The same accounts, in any order.
fn same(first: &[Address], second: &[Address]) -> bool {
	first.len() == second.len() && first.iter().all(|key| second.contains(key))
}

/// Each info must be the info of the trade's mint, before any other check reads
/// it.
fn check_mints(route: &TradeRoute<'_>) -> Result<(), Unroutable> {
	let infos = [
		(route.trade.base_mint, route.base_mint_info),
		(route.trade.quote_mint, route.quote_mint_info),
	];
	if let Some((mint, _)) =
		infos.iter().find(|(mint, info)| info.address != *mint)
	{
		return Err(Unroutable::MintMismatch(*mint));
	}
	if check_base_mint(route.base_mint_info).is_err() {
		return Err(Unroutable::BaseNotToken2022(route.trade.base_mint));
	}
	if route.trade.quote_token_program != route.quote_mint_info.token_program {
		return Err(Unroutable::QuoteTokenProgramMismatch(
			route.trade.quote_mint,
		));
	}
	if let Some((mint, _)) = infos.iter().find(|(_, info)| info.hook_not_read())
	{
		return Err(Unroutable::HookNotRead(*mint));
	}
	Ok(())
}

/// The hook's `check_account_infos`: each extra must reach it as a
/// non-signer with the writable flag its list declares. The runtime gives an
/// account the roles of all its repeats in the `Execute`.
fn screen_execute(execute: &LegExecute) -> Result<(), Unroutable> {
	let extras = execute.metas.iter().skip(super::EXECUTE_ACCOUNTS);
	for (meta, (signer, writable)) in extras.zip(&execute.declared) {
		if *signer {
			return Err(Unroutable::ExtraSigns);
		}
		let held = execute
			.metas
			.iter()
			.any(|other| other.pubkey == meta.pubkey && other.is_writable);
		if held != *writable {
			return Err(Unroutable::ExecuteRoleConflict);
		}
	}
	Ok(())
}

#[cfg(test)]
mod tests;