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
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
use super::*;

use solana_instruction::AccountMeta;
use spl_tlv_account_resolution::account::ExtraAccountMeta;
use spl_tlv_account_resolution::pubkey_data::PubkeyData;
use spl_tlv_account_resolution::seeds::Seed;
use spl_tlv_account_resolution::state::ExtraAccountMetaList;

use crate::constants::{
	ATA_PROGRAM_ID, DEFAULT_PARTNER, DEX_PROGRAM_ID, LAUNCHPAD_PROGRAM_ID,
	SYSTEM_PROGRAM_ID, TOKEN_2022_PROGRAM_ID,
};
use crate::transfer_hook::{
	AccountView, Execute, FetchedAccount, HookError, HookState, Unresolvable,
	find_validation_address,
};

const HOOK: Address = Address::new_from_array([40; 32]);
const RENT_SYSVAR: Address =
	solana_address::address!("SysvarRent111111111111111111111111111111111");
/// An account a list reads.
const STATE: Address = Address::new_from_array([41; 32]);

const TRADE: TradeAccounts = TradeAccounts {
	user: Address::new_from_array([1; 32]),
	payer: Address::new_from_array([2; 32]),
	market: Address::new_from_array([3; 32]),
	base_mint: Address::new_from_array([4; 32]),
	quote_mint: Address::new_from_array([5; 32]),
	base_vault: Address::new_from_array([6; 32]),
	quote_vault: Address::new_from_array([7; 32]),
	user_base_account: Address::new_from_array([8; 32]),
	user_quote_account: Address::new_from_array([9; 32]),
	partner: DEFAULT_PARTNER,
	partner_config: Address::new_from_array([10; 32]),
	quote_token_program: TOKEN_2022_PROGRAM_ID,
};

const PROGRAMS: [TradeProgram; 2] =
	[TradeProgram::Launchpad, TradeProgram::Dex];
const DIRECTIONS: [TradeDirection; 2] =
	[TradeDirection::Buy, TradeDirection::Sell];

fn list(extras: &[ExtraAccountMeta]) -> Vec<u8> {
	let mut data =
		vec![0; ExtraAccountMetaList::size_of(extras.len()).unwrap()];
	ExtraAccountMetaList::init::<Execute>(&mut data, extras).unwrap();
	data
}

fn fixed(pubkey: Address, writable: bool) -> ExtraAccountMeta {
	ExtraAccountMeta::new_with_pubkey(&pubkey, false, writable).unwrap()
}

/// The owner of the transfer's destination, read from its data.
fn destination_owner(writable: bool) -> ExtraAccountMeta {
	ExtraAccountMeta::new_with_pubkey_data(
		&PubkeyData::AccountData {
			account_index: 2,
			data_index: 32,
		},
		false,
		writable,
	)
	.unwrap()
}

/// Which mint runs the hook.
#[derive(Clone, Copy, Debug)]
enum Hooked {
	Base,
	Quote,
}

impl Hooked {
	const fn mint(self) -> Address {
		match self {
			Self::Base => TRADE.base_mint,
			Self::Quote => TRADE.quote_mint,
		}
	}
}

/// The mints of a market.
struct Market {
	base: MintInfo,
	quote: MintInfo,
}

impl Market {
	const fn exact_in(
		&self,
		program: TradeProgram,
		direction: TradeDirection,
	) -> TradeRoute<'_> {
		TradeRoute {
			program,
			trade: &TRADE,
			base_mint_info: &self.base,
			quote_mint_info: &self.quote,
			direction,
			mode: TradeMode::ExactIn,
			amount: 1_000,
			limit: 0,
		}
	}
}

const fn plain(mint: Address) -> MintInfo {
	MintInfo::plain(mint, TOKEN_2022_PROGRAM_ID, 6)
}

/// `mint`, which runs [`HOOK`]. Its snapshot holds `accounts`.
fn hooked_info(mint: Address, accounts: &[(Address, Vec<u8>)]) -> MintInfo {
	let mut hook = HookState::default();
	for (address, data) in accounts {
		hook.insert(
			*address,
			Some(FetchedAccount {
				owner: HOOK,
				data: data.clone(),
			}),
		);
	}
	MintInfo {
		hook_program: Some(HOOK),
		hook: Some(hook),
		..plain(mint)
	}
}

/// A market whose `hooked` mint runs [`HOOK`] with `extras`. The other mint
/// is hook-free.
fn market_of(hooked: Hooked, extras: &[ExtraAccountMeta]) -> Market {
	let info = |mint: Address| {
		if mint == hooked.mint() {
			hooked_info(mint, &[(validation(hooked), list(extras))])
		} else {
			plain(mint)
		}
	};
	Market {
		base: info(TRADE.base_mint),
		quote: info(TRADE.quote_mint),
	}
}

/// A router cache that holds nothing.
const fn empty(_: &Address) -> Fetched<'static> {
	Fetched::NotFetched
}

fn validation(hooked: Hooked) -> Address {
	find_validation_address(&hooked.mint(), &HOOK)
}

/// The hook accounts, after the 17 trade accounts.
fn trailing(route: &Route) -> &[AccountMeta] {
	route.instruction.accounts.get(17..).unwrap()
}

/// Each account the chain holds read-only on a trade, wanted writable by an
/// extra outside the leg's own `Execute`. The accounts are the market, the
/// other mint, the partner config, the system program (`DEFAULT_PARTNER`) and a
/// sysvar. The market case uses a buy's quote leg, whose authority is the user.
#[test]
fn a_writable_repeat_of_a_read_only_trade_account_does_not_route() {
	let cases = [
		(Hooked::Quote, TradeDirection::Buy, TRADE.market),
		(Hooked::Quote, TradeDirection::Buy, TRADE.base_mint),
		(Hooked::Base, TradeDirection::Sell, TRADE.quote_mint),
		(Hooked::Quote, TradeDirection::Buy, TRADE.partner_config),
		(Hooked::Quote, TradeDirection::Sell, DEFAULT_PARTNER),
		(Hooked::Base, TradeDirection::Buy, RENT_SYSVAR),
	];
	for program in PROGRAMS {
		for (hooked, direction, account) in cases {
			let market = market_of(hooked, &[fixed(account, true)]);
			assert_eq!(
				trade(market.exact_in(program, direction), empty),
				Err(Unroutable::WritableRepeat(account)),
				"{program:?} {direction:?}: {account}"
			);
			// Read-only, each routes.
			let market = market_of(hooked, &[fixed(account, false)]);
			let route =
				trade(market.exact_in(program, direction), empty).unwrap();
			assert_eq!(
				trailing(&route),
				[
					AccountMeta::new_readonly(account, false),
					AccountMeta::new_readonly(HOOK, false),
					AccountMeta::new_readonly(validation(hooked), false),
				]
			);
		}
	}
	assert_eq!(SYSTEM_PROGRAM_ID, DEFAULT_PARTNER);
	assert_eq!(
		Unroutable::WritableRepeat(TRADE.market).to_string(),
		format!(
			"a transfer hook wants {} writable, which the trade holds \
			 read-only",
			TRADE.market
		)
	);
}

/// The runtime demotes none of these under a router, and each trade lands
/// with it writable: Token-2022, the associated token program and the
/// market's own program. `WritableRepeat` does not check them.
#[test]
fn a_writable_program_the_runtime_does_not_demote_routes() {
	for (program, own) in [
		(TradeProgram::Launchpad, LAUNCHPAD_PROGRAM_ID),
		(TradeProgram::Dex, DEX_PROGRAM_ID),
	] {
		for account in [TOKEN_2022_PROGRAM_ID, ATA_PROGRAM_ID, own] {
			let market = market_of(Hooked::Quote, &[fixed(account, true)]);
			for direction in DIRECTIONS {
				let route =
					trade(market.exact_in(program, direction), empty).unwrap();
				assert_eq!(route.instruction.program_id, own);
				assert_eq!(
					trailing(&route),
					[
						AccountMeta::new(account, false),
						AccountMeta::new_readonly(HOOK, false),
						AccountMeta::new_readonly(
							validation(Hooked::Quote),
							false
						),
					],
					"{program:?} {direction:?}: {account}"
				);
				assert_eq!(route.reads, Vec::<Address>::new());
			}
		}
	}
}

/// A quote hook that wants the destination's owner writable. On a buy that
/// owner is the market, which owns the quote vault: the buy does not route.
/// On a sell it is the seller, which the trade holds untyped: the sell routes
/// with the seller writable. A base hook is the reverse.
#[test]
fn each_direction_routes_on_its_own() {
	for program in PROGRAMS {
		for (hooked, refused, routed) in [
			(Hooked::Quote, TradeDirection::Buy, TradeDirection::Sell),
			(Hooked::Base, TradeDirection::Sell, TradeDirection::Buy),
		] {
			let market = market_of(hooked, &[destination_owner(true)]);
			assert_eq!(
				trade(market.exact_in(program, refused), empty),
				Err(Unroutable::WritableRepeat(TRADE.market)),
				"{program:?} {hooked:?}"
			);
			let route = trade(market.exact_in(program, routed), empty).unwrap();
			assert_eq!(
				trailing(&route),
				[
					AccountMeta::new(TRADE.user, false),
					AccountMeta::new_readonly(HOOK, false),
					AccountMeta::new_readonly(validation(hooked), false),
				],
				"{program:?} {hooked:?}"
			);
			// The owner is read from the moved account's mint and owner, which
			// no transfer changes. The cache holds nothing.
			assert_eq!(route.reads, Vec::<Address>::new());
		}
	}
}

#[test]
fn an_extra_that_must_sign_does_not_route() {
	let signer =
		ExtraAccountMeta::new_with_pubkey(&STATE, true, false).unwrap();
	let market = market_of(Hooked::Quote, &[signer]);
	for program in PROGRAMS {
		for direction in DIRECTIONS {
			assert_eq!(
				trade(market.exact_in(program, direction), empty),
				Err(Unroutable::ExtraSigns)
			);
		}
	}
	assert_eq!(
		Unroutable::ExtraSigns.to_string(),
		"a transfer hook extra must sign"
	);
}

/// The hook's own `Execute` holds the mint read-only, and SPL's resolver
/// passes a later repeat read-only. A read-only repeat of an extra the
/// `Execute` already holds writable reaches the hook writable. Either way,
/// the account's role is not the one its list declares.
#[test]
fn an_execute_role_conflict_does_not_route() {
	for extras in [
		vec![fixed(TRADE.quote_mint, true)],
		vec![fixed(STATE, true), fixed(STATE, false)],
	] {
		let market = market_of(Hooked::Quote, &extras);
		for program in PROGRAMS {
			for direction in DIRECTIONS {
				assert_eq!(
					trade(market.exact_in(program, direction), empty),
					Err(Unroutable::ExecuteRoleConflict),
					"{program:?} {direction:?}: {extras:?}"
				);
			}
		}
	}
	// The same account writable, then writable again, keeps one role.
	let market =
		market_of(Hooked::Quote, &[fixed(STATE, true), fixed(STATE, true)]);
	let route = trade(
		market.exact_in(TradeProgram::Launchpad, TradeDirection::Buy),
		empty,
	)
	.unwrap();
	assert_eq!(
		trailing(&route),
		[
			AccountMeta::new(STATE, false),
			AccountMeta::new_readonly(HOOK, false),
			AccountMeta::new_readonly(validation(Hooked::Quote), false),
		]
	);
	assert_eq!(
		Unroutable::ExecuteRoleConflict.to_string(),
		"a transfer hook wants one account of its Execute both read-only and \
		 writable"
	);
}

/// A PDA seeded by the data of an earlier extra. The router resolves it only
/// from its cache.
#[test]
fn a_read_the_cache_lacks_is_not_cached() {
	let market = market_of(
		Hooked::Quote,
		&[
			fixed(STATE, false),
			ExtraAccountMeta::new_with_seeds(
				&[Seed::AccountData {
					account_index: 5,
					data_index: 0,
					length: 32,
				}],
				false,
				false,
			)
			.unwrap(),
		],
	);
	let route = market.exact_in(TradeProgram::Launchpad, TradeDirection::Buy);
	assert_eq!(trade(route, empty), Err(Unroutable::NotCached(vec![STATE])));
	let data = [7; 32];
	let routed = trade(route, |key| {
		if *key == STATE {
			Fetched::Account(AccountView {
				owner: &SYSTEM_PROGRAM_ID,
				data: &data,
			})
		} else {
			Fetched::NotFetched
		}
	})
	.unwrap();
	assert_eq!(routed.reads, vec![STATE]);
	assert_eq!(
		trailing(&routed),
		[
			AccountMeta::new_readonly(STATE, false),
			AccountMeta::new_readonly(
				Address::find_program_address(&[&data], &HOOK).0,
				false
			),
			AccountMeta::new_readonly(HOOK, false),
			AccountMeta::new_readonly(validation(Hooked::Quote), false),
		]
	);
}

/// The resolver's refusal of a hook whose list the info does not hold. The
/// list comes from the info alone, never from the router's cache.
#[test]
fn the_resolvers_refusals_do_not_route() {
	let unloaded = Market {
		base: hooked_info(TRADE.base_mint, &[]),
		quote: plain(TRADE.quote_mint),
	};
	let route = unloaded.exact_in(TradeProgram::Launchpad, TradeDirection::Buy);
	let not_loaded =
		Err(Unroutable::Hook(HookError::NotLoaded(vec![validation(
			Hooked::Base,
		)])));
	assert_eq!(trade(route, empty), not_loaded);
	let data = list(&[fixed(STATE, false)]);
	assert_eq!(
		trade(route, |key| {
			if *key == validation(Hooked::Base) {
				Fetched::Account(AccountView {
					owner: &HOOK,
					data: &data,
				})
			} else {
				Fetched::NotFetched
			}
		}),
		not_loaded
	);
}

/// A quote list that reads the data of the hook-free base mint. The base
/// info holds no account, so the read is the router's to cache: not cached
/// until it is, never a list that does not resolve.
#[test]
fn a_hook_free_mint_a_list_reads_is_not_cached_until_cached() {
	let market = market_of(
		Hooked::Quote,
		&[
			fixed(TRADE.base_mint, false),
			// The decimals and `is_initialized`.
			ExtraAccountMeta::new_with_seeds(
				&[Seed::AccountData {
					account_index: 5,
					data_index: 44,
					length: 2,
				}],
				false,
				false,
			)
			.unwrap(),
		],
	);
	for program in PROGRAMS {
		for direction in DIRECTIONS {
			let route = market.exact_in(program, direction);
			assert_eq!(
				trade(route, empty),
				Err(Unroutable::NotCached(vec![TRADE.base_mint])),
				"{program:?} {direction:?}"
			);
			let mut base = vec![0; 82];
			base[44] = 6;
			base[45] = 1;
			let routed = trade(route, |key| {
				if *key == TRADE.base_mint {
					Fetched::Account(AccountView {
						owner: &TOKEN_2022_PROGRAM_ID,
						data: &base,
					})
				} else {
					Fetched::NotFetched
				}
			})
			.unwrap();
			assert_eq!(routed.reads, vec![TRADE.base_mint]);
			assert_eq!(
				trailing(&routed),
				[
					AccountMeta::new_readonly(TRADE.base_mint, false),
					AccountMeta::new_readonly(
						Address::find_program_address(&[&[6, 1]], &HOOK).0,
						false
					),
					AccountMeta::new_readonly(HOOK, false),
					AccountMeta::new_readonly(validation(Hooked::Quote), false),
				],
				"{program:?} {direction:?}"
			);
		}
	}
	assert_eq!(
		Unroutable::NotCached(vec![TRADE.base_mint]).to_string(),
		"transfer hook accounts not cached"
	);
}

/// A list reads each info's snapshot before the router's cache.
#[test]
fn a_read_comes_from_the_infos_before_the_cache() {
	let extras = [
		fixed(STATE, false),
		ExtraAccountMeta::new_with_seeds(
			&[Seed::AccountData {
				account_index: 5,
				data_index: 0,
				length: 32,
			}],
			false,
			false,
		)
		.unwrap(),
	];
	let held = vec![7; 32];
	let cached = [8; 32];
	let cache = |key: &Address| {
		if *key == STATE {
			Fetched::Account(AccountView {
				owner: &SYSTEM_PROGRAM_ID,
				data: &cached,
			})
		} else {
			Fetched::NotFetched
		}
	};
	let expected = |seed: &[u8]| {
		vec![
			AccountMeta::new_readonly(STATE, false),
			AccountMeta::new_readonly(
				Address::find_program_address(&[seed], &HOOK).0,
				false,
			),
			AccountMeta::new_readonly(HOOK, false),
			AccountMeta::new_readonly(validation(Hooked::Quote), false),
		]
	};
	let quote = |accounts: &[(Address, Vec<u8>)]| {
		hooked_info(
			TRADE.quote_mint,
			&[
				[(validation(Hooked::Quote), list(&extras))].as_slice(),
				accounts,
			]
			.concat(),
		)
	};
	// The quote's own snapshot, then the base's. The base hook's list has
	// no extra. A buy moves the quote first.
	for (market, expected) in [
		(
			Market {
				base: plain(TRADE.base_mint),
				quote: quote(&[(STATE, held.clone())]),
			},
			expected(&held),
		),
		(
			Market {
				base: hooked_info(
					TRADE.base_mint,
					&[
						(validation(Hooked::Base), list(&[])),
						(STATE, held.clone()),
					],
				),
				quote: quote(&[]),
			},
			[
				expected(&held),
				vec![AccountMeta::new_readonly(
					validation(Hooked::Base),
					false,
				)],
			]
			.concat(),
		),
	] {
		let routed = trade(
			market.exact_in(TradeProgram::Launchpad, TradeDirection::Buy),
			cache,
		)
		.unwrap();
		assert_eq!(trailing(&routed), expected);
		assert_eq!(routed.reads, vec![STATE]);
	}
	// Neither info holds it: the cache's.
	let routed = trade(
		Market {
			base: plain(TRADE.base_mint),
			quote: quote(&[]),
		}
		.exact_in(TradeProgram::Launchpad, TradeDirection::Buy),
		cache,
	)
	.unwrap();
	assert_eq!(trailing(&routed), expected(&cached));
}

/// Two hook-free infos resolve the trade with no hook account, whatever the
/// cache holds.
#[test]
fn two_hook_free_mints_route_hook_free() {
	let market = Market {
		base: plain(TRADE.base_mint),
		quote: plain(TRADE.quote_mint),
	};
	for program in PROGRAMS {
		for direction in DIRECTIONS {
			let routed =
				trade(market.exact_in(program, direction), empty).unwrap();
			assert_eq!(routed.instruction.accounts.len(), 17);
			assert_eq!(routed.reads, Vec::<Address>::new());
		}
	}
}

/// A PDA of the transfer amount. No direction or mode routes with such a hook
/// on either mint.
#[test]
fn an_amount_seed_does_not_route() {
	let amount = ExtraAccountMeta::new_with_seeds(
		&[Seed::InstructionData {
			index: 8,
			length: 8,
		}],
		false,
		false,
	)
	.unwrap();
	let refused = Unroutable::Hook(HookError::Unresolvable(
		Unresolvable::ReadsTransferAmount,
	));
	for hooked in [Hooked::Base, Hooked::Quote] {
		let market = market_of(hooked, &[amount]);
		for program in PROGRAMS {
			for direction in DIRECTIONS {
				for mode in [TradeMode::ExactIn, TradeMode::ExactOut] {
					assert_eq!(
						trade(
							TradeRoute {
								mode,
								..market.exact_in(program, direction)
							},
							empty,
						),
						Err(refused.clone()),
						"{hooked:?} {program:?} {direction:?} {mode:?}"
					);
				}
			}
		}
	}
	assert_eq!(
		refused.to_string(),
		"transfer hook cannot be resolved ahead of the instruction: a seed \
		 reads the transfer amount"
	);
	assert_eq!(
		Unroutable::UncacheableRead.to_string(),
		"a transfer hook reads an account that depends on the trader"
	);
}

/// An info of another mint gives the wrong hook accounts.
#[test]
fn an_info_of_another_mint_does_not_route() {
	let other = Address::new_from_array([42; 32]);
	for (base, quote, refused) in [
		(plain(other), plain(TRADE.quote_mint), TRADE.base_mint),
		(plain(TRADE.base_mint), plain(other), TRADE.quote_mint),
		(
			plain(TRADE.quote_mint),
			plain(TRADE.base_mint),
			TRADE.base_mint,
		),
	] {
		let market = Market { base, quote };
		for program in PROGRAMS {
			for direction in DIRECTIONS {
				assert_eq!(
					trade(market.exact_in(program, direction), empty),
					Err(Unroutable::MintMismatch(refused)),
					"{program:?} {direction:?}"
				);
			}
		}
	}
	assert_eq!(
		Unroutable::MintMismatch(TRADE.base_mint).to_string(),
		format!(
			"the mint info is not the info of the trade's mint {}",
			TRADE.base_mint
		)
	);
}

/// The builders refuse the same base mint.
#[test]
fn a_base_mint_that_is_not_a_token_2022_mint_does_not_route() {
	let market = Market {
		base: MintInfo::plain(
			TRADE.base_mint,
			crate::constants::TOKEN_PROGRAM_ID,
			6,
		),
		quote: plain(TRADE.quote_mint),
	};
	for program in PROGRAMS {
		for direction in DIRECTIONS {
			assert_eq!(
				trade(market.exact_in(program, direction), empty),
				Err(Unroutable::BaseNotToken2022(TRADE.base_mint)),
				"{program:?} {direction:?}"
			);
		}
	}
	assert_eq!(
		Unroutable::BaseNotToken2022(TRADE.base_mint).to_string(),
		format!("the base mint {} is not a Token-2022 mint", TRADE.base_mint)
	);
}

/// The builders take the quote token program from the info and cannot
/// mismatch.
#[test]
fn a_quote_token_program_that_is_not_the_quote_mints_does_not_route() {
	let market = Market {
		base: plain(TRADE.base_mint),
		quote: MintInfo::plain(
			TRADE.quote_mint,
			crate::constants::TOKEN_PROGRAM_ID,
			6,
		),
	};
	for program in PROGRAMS {
		for direction in DIRECTIONS {
			assert_eq!(
				trade(market.exact_in(program, direction), empty),
				Err(Unroutable::QuoteTokenProgramMismatch(TRADE.quote_mint)),
				"{program:?} {direction:?}"
			);
		}
	}
	assert_eq!(
		Unroutable::QuoteTokenProgramMismatch(TRADE.quote_mint).to_string(),
		format!(
			"the quote token program is not the token program of the quote \
			 mint {}",
			TRADE.quote_mint
		)
	);
}

/// The builders refuse the same info. A list in the router's cache does not
/// help: the list comes only from the `MintInfo`.
#[test]
fn a_hook_program_with_no_hook_does_not_route() {
	let data = list(&[fixed(RENT_SYSVAR, false)]);
	for hooked in [Hooked::Base, Hooked::Quote] {
		let mut market = market_of(hooked, &[fixed(RENT_SYSVAR, false)]);
		match hooked {
			Hooked::Base => market.base.hook = None,
			Hooked::Quote => market.quote.hook = None,
		}
		let cached = |address: &Address| {
			if *address == validation(hooked) {
				Fetched::Account(AccountView {
					owner: &HOOK,
					data: &data,
				})
			} else {
				Fetched::NotFetched
			}
		};
		for program in PROGRAMS {
			for direction in DIRECTIONS {
				assert_eq!(
					trade(market.exact_in(program, direction), cached),
					Err(Unroutable::HookNotRead(hooked.mint())),
					"{hooked:?} {program:?} {direction:?}"
				);
			}
		}
	}
	assert_eq!(
		Unroutable::HookNotRead(TRADE.quote_mint).to_string(),
		format!(
			"the mint {} has a hook program and no hook",
			TRADE.quote_mint
		)
	);
}

/// The users of the two stand-in traders.
const STAND_IN_USERS: [Address; 2] = [
	Address::new_from_array([1; 32]),
	Address::new_from_array([5; 32]),
];

fn hook_pda(seed: &Address) -> Address {
	Address::find_program_address(&[seed.as_ref()], &HOOK).0
}

/// A buy's quote leg: a PDA of the authority (the user), then a PDA of that
/// PDA's first 32 bytes. The second read depends on the trader.
fn reads_a_pda_of_the_trader() -> Market {
	market_of(
		Hooked::Quote,
		&[
			ExtraAccountMeta::new_with_seeds(
				&[Seed::AccountKey { index: 3 }],
				false,
				false,
			)
			.unwrap(),
			ExtraAccountMeta::new_with_seeds(
				&[Seed::AccountData {
					account_index: 5,
					data_index: 0,
					length: 32,
				}],
				false,
				false,
			)
			.unwrap(),
		],
	)
}

fn screen_buy(
	market: &Market,
	accounts: impl Fn(&Address) -> Fetched<'static>,
) -> Screen {
	screen(
		market.exact_in(TradeProgram::Launchpad, TradeDirection::Buy),
		accounts,
	)
}

/// Each stand-in's route resolves its own trader's PDA, whatever trader the
/// route names.
#[test]
fn screen_resolves_the_trade_for_each_stand_in_trader() {
	let market = market_of(
		Hooked::Quote,
		&[ExtraAccountMeta::new_with_seeds(
			&[Seed::AccountKey { index: 3 }],
			false,
			false,
		)
		.unwrap()],
	);
	let screened = screen_buy(&market, empty);
	assert_eq!(screened.route, Ok(()));
	assert_eq!(screened.not_cached, Vec::<Address>::new());
	for (route, user) in screened.stand_ins.iter().zip(STAND_IN_USERS) {
		let route = route.as_ref().unwrap();
		assert_eq!(route.instruction.accounts[0].pubkey, user);
		assert_eq!(
			trailing(route),
			[
				AccountMeta::new_readonly(hook_pda(&user), false),
				AccountMeta::new_readonly(HOOK, false),
				AccountMeta::new_readonly(validation(Hooked::Quote), false),
			]
		);
	}
	let other_trader = TradeAccounts {
		user: Address::new_from_array([77; 32]),
		..TRADE
	};
	assert_eq!(
		screen(
			TradeRoute {
				trade: &other_trader,
				..market.exact_in(TradeProgram::Launchpad, TradeDirection::Buy)
			},
			empty,
		),
		screened
	);
}

#[test]
fn screen_routes_a_hook_free_market() {
	let market = Market {
		base: plain(TRADE.base_mint),
		quote: plain(TRADE.quote_mint),
	};
	for program in PROGRAMS {
		for direction in DIRECTIONS {
			let screened = screen(market.exact_in(program, direction), empty);
			assert_eq!(screened.route, Ok(()));
			assert_eq!(screened.not_cached, Vec::<Address>::new());
			for route in &screened.stand_ins {
				assert_eq!(
					route.as_ref().unwrap().instruction.accounts.len(),
					17
				);
			}
		}
	}
}

/// Both stand-ins lack the same account: cache it for the next update.
#[test]
fn screen_names_what_both_stand_ins_lack() {
	let market = market_of(
		Hooked::Quote,
		&[
			fixed(STATE, false),
			ExtraAccountMeta::new_with_seeds(
				&[Seed::AccountData {
					account_index: 5,
					data_index: 0,
					length: 32,
				}],
				false,
				false,
			)
			.unwrap(),
		],
	);
	let screened = screen_buy(&market, empty);
	assert_eq!(screened.route, Err(Unroutable::NotCached(vec![STATE])));
	assert_eq!(screened.not_cached, vec![STATE]);

	let screened = screen_buy(&market, |key| {
		if *key == STATE {
			Fetched::Account(AccountView {
				owner: &SYSTEM_PROGRAM_ID,
				data: &[7; 32],
			})
		} else {
			Fetched::NotFetched
		}
	});
	assert_eq!(screened.route, Ok(()));
	assert_eq!(screened.not_cached, Vec::<Address>::new());
	assert_eq!(
		screened.stand_ins.map(|route| route.unwrap().reads),
		[vec![STATE], vec![STATE]]
	);
}

/// Each stand-in lacks its own PDA.
#[test]
fn screen_refuses_a_list_that_lacks_a_different_account_per_trader() {
	let screened = screen_buy(&reads_a_pda_of_the_trader(), empty);
	assert_eq!(screened.route, Err(Unroutable::UncacheableRead));
	assert_eq!(screened.not_cached, Vec::<Address>::new());
	assert_eq!(
		screened.stand_ins.map(Result::err),
		STAND_IN_USERS
			.map(|user| Some(Unroutable::NotCached(vec![hook_pda(&user)])))
	);
}

/// Each stand-in reads its own PDA: the reads differ.
#[test]
fn screen_refuses_a_list_that_reads_a_different_account_per_trader() {
	let [first, second] = STAND_IN_USERS.map(|user| hook_pda(&user));
	let screened = screen_buy(&reads_a_pda_of_the_trader(), move |key| {
		if *key == first || *key == second {
			Fetched::Account(AccountView {
				owner: &SYSTEM_PROGRAM_ID,
				data: &[7; 32],
			})
		} else {
			Fetched::NotFetched
		}
	});
	assert_eq!(screened.route, Err(Unroutable::UncacheableRead));
	assert_eq!(
		screened.stand_ins.map(|route| route.unwrap().reads),
		[vec![first], vec![second]]
	);
}

/// One stand-in fails on its own data, and the other lacks its account. The
/// outcomes differ, so the list depends on the trader, whichever stand-in
/// fails first.
#[test]
fn screen_refuses_stand_ins_that_fail_differently() {
	let short = |cut: Address| {
		move |key: &Address| {
			if *key == cut {
				Fetched::Account(AccountView {
					owner: &SYSTEM_PROGRAM_ID,
					data: &[7; 8],
				})
			} else {
				Fetched::NotFetched
			}
		}
	};
	let unresolved = Unroutable::Hook(HookError::Unresolvable(
		Unresolvable::ExtraUnresolved,
	));
	let [first, second] = STAND_IN_USERS.map(|user| hook_pda(&user));
	for (cut, outcomes) in [
		(
			first,
			[
				Some(unresolved.clone()),
				Some(Unroutable::NotCached(vec![second])),
			],
		),
		(
			second,
			[Some(Unroutable::NotCached(vec![first])), Some(unresolved)],
		),
	] {
		let screened = screen_buy(&reads_a_pda_of_the_trader(), short(cut));
		assert_eq!(screened.stand_ins.clone().map(Result::err), outcomes);
		assert_eq!(screened.route, Err(Unroutable::UncacheableRead));
		assert_eq!(screened.not_cached, Vec::<Address>::new());
	}
}

/// Both stand-ins fail alike: the list fails for any trader.
#[test]
fn screen_keeps_an_error_both_stand_ins_share() {
	let amount = ExtraAccountMeta::new_with_seeds(
		&[Seed::InstructionData {
			index: 8,
			length: 8,
		}],
		false,
		false,
	)
	.unwrap();
	let screened = screen_buy(&market_of(Hooked::Quote, &[amount]), empty);
	assert_eq!(
		screened.route,
		Err(Unroutable::Hook(HookError::Unresolvable(
			Unresolvable::ReadsTransferAmount
		)))
	);
}

/// The quote mint's Token-2022 account. It runs [`HOOK`].
fn hooked_quote_mint() -> FetchedAccount {
	let mut data = vec![0; 165];
	// `decimals`, `is_initialized`, then `AccountType::Mint`.
	data[44] = 6;
	data[45] = 1;
	data.push(1);
	data.extend_from_slice(
		&u16::from(
			spl_token_2022_interface::extension::ExtensionType::TransferHook,
		)
		.to_le_bytes(),
	);
	data.extend_from_slice(&64_u16.to_le_bytes());
	data.extend_from_slice(&[7; 32]);
	data.extend_from_slice(&HOOK.to_bytes());
	FetchedAccount {
		owner: TOKEN_2022_PROGRAM_ID,
		data,
	}
}

/// The key stored at the start of `account_index`'s data.
fn stored_in(account_index: u8, signer: bool) -> ExtraAccountMeta {
	ExtraAccountMeta::new_with_pubkey_data(
		&PubkeyData::AccountData {
			account_index,
			data_index: 0,
		},
		signer,
		false,
	)
	.unwrap()
}

/// A PDA of the hook, keyed on the transfer's destination: the quote vault
/// on a buy, the trader's account on a sell.
fn record_of_destination() -> ExtraAccountMeta {
	ExtraAccountMeta::new_with_seeds(
		&[
			Seed::Literal {
				bytes: b"rec".to_vec(),
			},
			Seed::AccountKey { index: 2 },
		],
		false,
		false,
	)
	.unwrap()
}

fn record_of(destination: &Address) -> Address {
	Address::find_program_address(&[b"rec", destination.as_ref()], &HOOK).0
}

/// A router that serves only the accounts that its last update declared. The
/// quote mint runs [`HOOK`] with `extras`.
struct Declared {
	accounts: Vec<(Address, FetchedAccount)>,
	declared: Vec<Address>,
}

impl Declared {
	fn new(
		extras: &[ExtraAccountMeta],
		accounts: &[(Address, Address)],
	) -> Self {
		let mut all = vec![(
			validation(Hooked::Quote),
			FetchedAccount {
				owner: HOOK,
				data: list(extras),
			},
		)];
		for (address, stored) in accounts {
			all.push((
				*address,
				FetchedAccount {
					owner: HOOK,
					data: stored.to_bytes().to_vec(),
				},
			));
		}
		Self {
			accounts: all,
			declared: Vec::new(),
		}
	}

	fn update(&mut self) -> LoadedMarket {
		let mint = hooked_quote_mint();
		let quote = MintInfo::load_at(
			TRADE.quote_mint,
			AccountView {
				owner: &mint.owner,
				data: &mint.data,
			},
			0,
		)
		.unwrap();
		let mut load = MarketLoad::new(MarketLoadArgs {
			program: TradeProgram::Launchpad,
			market: TRADE,
			base_mint_info: plain(TRADE.base_mint),
			quote_mint_info: quote,
		});
		loop {
			let next = load.missing().unwrap();
			if next.is_empty() {
				break;
			}
			for address in next {
				if self.declared.contains(&address) {
					let account = self
						.accounts
						.iter()
						.find(|(key, _)| *key == address)
						.map(|(_, account)| account.clone());
					load.insert(address, account);
				}
			}
		}
		let loaded = load.finish();
		self.declared.clone_from(&loaded.declare);
		loaded
	}

	/// The buy of each update, and what it declares.
	fn buys(
		&mut self,
		updates: usize,
	) -> Vec<(Result<(), Unroutable>, Vec<Address>)> {
		(0..updates)
			.map(|_| {
				let loaded = self.update();
				let [buy, _] = loaded.screens.unwrap();
				(buy.route, loaded.declare)
			})
			.collect()
	}
}

fn list_not_loaded() -> Result<(), Unroutable> {
	Err(Unroutable::Hook(HookError::NotLoaded(vec![validation(
		Hooked::Quote,
	)])))
}

/// A chain of two reads that the market sets: a record keyed on the
/// destination, then the account whose key the record stores. Each update
/// declares every link it named, so the chain loads one link at each update.
#[test]
fn a_market_load_loads_a_chain_of_market_reads_one_link_at_each_update() {
	let record = record_of(&TRADE.quote_vault);
	let [second, third] = [[61; 32], [62; 32]].map(Address::new_from_array);
	let mut router = Declared::new(
		&[
			record_of_destination(),
			stored_in(5, false),
			stored_in(6, false),
		],
		&[(record, second), (second, third)],
	);
	let list = validation(Hooked::Quote);
	assert_eq!(
		router.buys(5),
		[
			(list_not_loaded(), vec![list]),
			(Err(Unroutable::NotCached(vec![record])), vec![list, record]),
			(
				Err(Unroutable::NotCached(vec![second])),
				vec![list, record, second]
			),
			(Ok(()), vec![list, record, second]),
			(Ok(()), vec![list, record, second]),
		]
	);
	let loaded = router.update();
	let [_, sell] = loaded.screens.unwrap();
	assert_eq!(sell.route, Err(Unroutable::UncacheableRead));
	let resolved = trade(
		TradeRoute {
			program: TradeProgram::Launchpad,
			trade: &TRADE,
			base_mint_info: &loaded.base_mint_info,
			quote_mint_info: &loaded.quote_mint_info,
			direction: TradeDirection::Buy,
			mode: TradeMode::ExactIn,
			amount: 1_000,
			limit: 0,
		},
		|address| loaded.cache.fetched(address),
	)
	.unwrap();
	assert_eq!(
		trailing(&resolved),
		[
			AccountMeta::new_readonly(record, false),
			AccountMeta::new_readonly(second, false),
			AccountMeta::new_readonly(third, false),
			AccountMeta::new_readonly(HOOK, false),
			AccountMeta::new_readonly(list, false),
		]
	);
}

/// A direction refused after a read that the market sets keeps declaring
/// that read, so its reason does not change between updates.
#[test]
fn a_market_load_keeps_a_refused_directions_reads_declared() {
	let record = record_of(&TRADE.quote_vault);
	let mut router = Declared::new(
		&[record_of_destination(), stored_in(5, true)],
		&[(record, Address::new_from_array([61; 32]))],
	);
	let list = validation(Hooked::Quote);
	assert_eq!(
		router.buys(5),
		[
			(list_not_loaded(), vec![list]),
			(Err(Unroutable::NotCached(vec![record])), vec![list, record]),
			(Err(Unroutable::ExtraSigns), vec![list, record]),
			(Err(Unroutable::ExtraSigns), vec![list, record]),
			(Err(Unroutable::ExtraSigns), vec![list, record]),
		]
	);
}

/// Two fixed reads load in the same update.
#[test]
fn a_market_load_names_independent_fixed_reads_together() {
	let [first, second] = [[61; 32], [62; 32]].map(Address::new_from_array);
	let mut router = Declared::new(
		&[
			fixed(first, false),
			fixed(second, false),
			stored_in(5, false),
			stored_in(6, false),
		],
		&[
			(first, Address::new_from_array([63; 32])),
			(second, Address::new_from_array([64; 32])),
		],
	);
	let list = validation(Hooked::Quote);
	assert_eq!(
		router.buys(3),
		[
			(list_not_loaded(), vec![list]),
			(
				Err(Unroutable::NotCached(vec![first])),
				vec![list, first, second]
			),
			(Ok(()), vec![list, first, second]),
		]
	);
}

/// A hook-free market names nothing and has no screens.
#[test]
fn a_market_load_of_hook_free_mints_names_nothing() {
	let mut load = MarketLoad::new(MarketLoadArgs {
		program: TradeProgram::Dex,
		market: TRADE,
		base_mint_info: plain(TRADE.base_mint),
		quote_mint_info: plain(TRADE.quote_mint),
	});
	assert_eq!(load.missing(), Ok(Vec::new()));
	let loaded = load.finish();
	assert_eq!(loaded.screens, None);
	assert_eq!(loaded.declare, Vec::<Address>::new());
	assert_eq!(loaded.cache, HookState::default());
}