-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinstruction.rs
2176 lines (2042 loc) · 77.8 KB
/
instruction.rs
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
use crate::engine::json::OrderItems;
use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::{
instruction::{AccountMeta, Instruction},
pubkey::Pubkey,
sysvar,
};
use spl_token::{self};
use std::collections::BTreeMap;
#[derive(Clone, Debug, BorshSerialize, BorshDeserialize, PartialEq)]
pub enum PaymentProcessorInstruction {
/// Register for a merchant account.
///
/// Accounts expected:
///
/// 0. `[signer]` The account of the person initializing the merchant account
/// 1. `[writable]` The merchant account. Owned by this program
/// 2. `[]` System program
/// 3. `[]` The rent sysvar
/// 4. `[optional]` The sponsor account
RegisterMerchant {
/// the seed used when creating the account
#[allow(dead_code)] // not dead code..
seed: Option<String>,
/// the amount (in SOL lamports) that will be charged as a fee
#[allow(dead_code)] // not dead code..
fee: Option<u64>,
/// arbitrary merchant data (maybe as a JSON string)
#[allow(dead_code)] // not dead code..
data: Option<String>,
},
/// Express Checkout
///
/// Meant to be used to process payments initialized by systems that reside off-chain
/// such as traditional e-commerce software.
///
/// Accounts expected:
///
/// 0. `[signer]` The account of the person initializing the transaction
/// 1. `[writable]` The order account. Owned by this program
/// 2. `[]` The merchant account. Owned by this program
/// 3. `[writable]` The seller token account - this is where the amount paid will go. Owned by this program
/// 4. `[writable]` The buyer token account
/// 5. `[writable]` The program owner account (where we will send program owner fee)
/// 6. `[writable]` The sponsor account (where we will send sponsor fee)
/// 7. `[]` The token mint account - represents the 'currency' being used
/// 8. `[]` This program's derived address
/// 9. `[]` The token program
/// 10. `[]` The System program
/// 11. `[]` The rent sysvar
ExpressCheckout {
#[allow(dead_code)] // not dead code..
amount: u64,
/// the external order id (as in issued by the merchant)
#[allow(dead_code)] // not dead code..
order_id: String,
// An extra field that can store an encrypted (ot not encrypted) string
// that the merchant can use to assert if a transaction is authentic
#[allow(dead_code)] // not dead code..
secret: String,
/// arbitrary merchant data (maybe as a JSON string)
#[allow(dead_code)] // not dead code..
data: Option<String>,
},
/// Chain Checkout
///
/// Meant to process payments that are validated completely on chain. That is,
/// all the information required to check that the payment is valid is available
/// on-chain.
///
/// This is made possible by relying on a merchant account that has certain defined
/// items for which payment can be made. See the engine::json::Item struct as well
/// as the chain checkout tests for more on how this works.
///
/// Accounts expected:
///
/// 0. `[signer]` The account of the person initializing the transaction
/// 1. `[writable]` The order account. Owned by this program
/// 2. `[]` The merchant account. Owned by this program
/// 3. `[writable]` The seller token account - this is where the amount paid will go. Owned by this program
/// 4. `[writable]` The buyer token account
/// 5. `[writable]` The program owner account (where we will send program owner fee)
/// 6. `[writable]` The sponsor account (where we will send sponsor fee)
/// 7. `[]` The token mint account - represents the 'currency' being used
/// 8. `[]` This program's derived address
/// 9. `[]` The token program
/// 10. `[]` The System program
/// 11. `[]` The rent sysvar
ChainCheckout {
#[allow(dead_code)] // not dead code..
amount: u64,
/// the external order id (as in issued by the merchant)
#[allow(dead_code)] // not dead code..
order_items: BTreeMap<String, u64>, // use this instead of OrderItems for readability in API
/// arbitrary merchant data (maybe as a JSON string)
#[allow(dead_code)] // not dead code..
data: Option<String>,
},
/// Withdraw funds for a particular order
///
/// Note that a payment cannot be withdrawn for an order made for a subscription
/// payment that is still within the subscription trial period.
///
/// Accounts expected:
///
/// 0. `[signer]` The account of the person initializing the transaction
/// 1. `[writable]` The order account. Owned by this program
/// 2. `[]` The merchant account. Owned by this program
/// 3. `[writable]` The order token account (where the money was put during payment)
/// 4. `[writable]` The merchant token account (where we will withdraw to)
/// 5. `[writable]` This account receives the refunded SOL after closing order token account
/// 6. `[]` This program's derived address
/// 7. `[]` The token program
Withdraw {
/// should we close the order account?
/// can be sent as 0 for false; 1 for true from a dApp
#[allow(dead_code)] // not dead code..
close_order_account: bool,
},
/// Initialize a subscription
///
/// A subscription is possible by relying on a merchant account that was created with
/// the correct subscription package information. See engine::json::Packages as well as
/// subscription tests for more on this.
///
/// A complete subscription transaction includes an ExpressCheckout instruction followed
/// by a Subscribe instruction. The actual payment is made in the ExpressCheckout instruction
/// and subsequently thr subscription is activated in the Subscribe instruction.
///
/// Accounts expected:
///
/// 0. `[signer]` The account of the person initializing the transaction
/// 1. `[writable]` The subscription account. Owned by this program
/// 2. `[]` The merchant account. Owned by this program
/// 3. `[]` The order account. Owned by this program
/// 4. `[]` The System program
/// 5. `[]` The rent sysvar
Subscribe {
/// the subscription package name
#[allow(dead_code)] // not dead code..
name: String,
/// arbitrary merchant data (maybe as a JSON string)
#[allow(dead_code)] // not dead code..
data: Option<String>,
},
/// Renew a subscription
///
/// A complete RenewSubscription transaction includes an ExpressCheckout instruction
/// followed by a RenewSubscription instruction. The actual payment is made in the
/// ExpressCheckout instruction and subsequently thr subscription is activated in the
/// RenewSubscription instruction.
///
/// Accounts expected:
///
/// 0. `[signer]` The account of the person initializing the transaction
/// 1. `[writable]` The subscription account. Owned by this program
/// 2. `[]` The merchant account. Owned by this program
/// 3. `[]` The order account. Owned by this program
RenewSubscription {
/// the number of periods to renew e.g. if the subscription period is a year
/// you can choose to renew for 1 year, 2 years, n years, etc
#[allow(dead_code)] // not dead code..
quantity: i64,
},
/// Cancel a subscription
///
/// If a CancelSubscription instruction is sent during the trial period of a
/// subscription, the amount initially paid for the subscription will be refunded in
/// full.
///
/// Accounts expected:
///
/// 0. `[signer]` The account of the person initializing the transaction
/// 1. `[writable]` The subscription account. Owned by this program
/// 2. `[]` The merchant account. Owned by this program
/// 3. `[writable]` The order account. Owned by this program
/// 4. `[writable]` The order token account - this is where the amount was paid into. Owned by this program
/// 5. `[writable]` The refund token account - this is where the refund will go
/// 6. `[writable]` This account receives the refunded SOL after closing order token account
/// 7. `[]` This program's derived address
/// 8. `[]` The token program
CancelSubscription,
}
/// Creates an 'RegisterMerchant' instruction.
pub fn register_merchant(
program_id: Pubkey,
signer: Pubkey,
merchant: Pubkey,
seed: Option<String>,
fee: Option<u64>,
data: Option<String>,
sponsor: Option<&Pubkey>,
) -> Instruction {
let mut account_metas = vec![
AccountMeta::new(signer, true),
AccountMeta::new(merchant, false),
AccountMeta::new_readonly(solana_program::system_program::id(), false),
AccountMeta::new_readonly(sysvar::rent::id(), false),
];
if let Some(sponsor) = sponsor {
account_metas.push(AccountMeta::new_readonly(*sponsor, false));
}
Instruction {
program_id,
accounts: account_metas,
data: PaymentProcessorInstruction::RegisterMerchant { seed, fee, data }
.try_to_vec()
.unwrap(),
}
}
/// Creates an 'ExpressCheckout' instruction.
pub fn express_checkout(
program_id: Pubkey,
signer: Pubkey,
order: Pubkey,
merchant: Pubkey,
seller_token: Pubkey,
buyer_token: Pubkey,
mint: Pubkey,
program_owner: Pubkey,
sponsor: Pubkey,
pda: Pubkey,
amount: u64,
order_id: String,
secret: String,
data: Option<String>,
) -> Instruction {
Instruction {
program_id,
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(order, true),
AccountMeta::new_readonly(merchant, false),
AccountMeta::new(seller_token, false),
AccountMeta::new(buyer_token, false),
AccountMeta::new(program_owner, false),
AccountMeta::new(sponsor, false),
AccountMeta::new_readonly(mint, false),
AccountMeta::new_readonly(pda, false),
AccountMeta::new_readonly(spl_token::id(), false),
AccountMeta::new_readonly(solana_program::system_program::id(), false),
AccountMeta::new_readonly(sysvar::rent::id(), false),
],
data: PaymentProcessorInstruction::ExpressCheckout {
amount,
order_id,
secret,
data,
}
.try_to_vec()
.unwrap(),
}
}
/// Creates an 'ChainCheckout' instruction.
pub fn chain_checkout(
program_id: Pubkey,
signer: Pubkey,
order: Pubkey,
merchant: Pubkey,
seller_token: Pubkey,
buyer_token: Pubkey,
mint: Pubkey,
program_owner: Pubkey,
sponsor: Pubkey,
pda: Pubkey,
amount: u64,
order_items: OrderItems,
data: Option<String>,
) -> Instruction {
Instruction {
program_id,
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(order, true),
AccountMeta::new_readonly(merchant, false),
AccountMeta::new(seller_token, false),
AccountMeta::new(buyer_token, false),
AccountMeta::new(program_owner, false),
AccountMeta::new(sponsor, false),
AccountMeta::new_readonly(mint, false),
AccountMeta::new_readonly(pda, false),
AccountMeta::new_readonly(spl_token::id(), false),
AccountMeta::new_readonly(solana_program::system_program::id(), false),
AccountMeta::new_readonly(sysvar::rent::id(), false),
],
data: PaymentProcessorInstruction::ChainCheckout {
amount,
order_items,
data,
}
.try_to_vec()
.unwrap(),
}
}
/// Creates an 'Withdraw' instruction.
pub fn withdraw(
program_id: Pubkey,
signer: Pubkey,
order: Pubkey,
merchant: Pubkey,
order_payment_token: Pubkey,
merchant_token: Pubkey,
account_to_receive_sol_refund: Pubkey,
pda: Pubkey,
subscription: Option<Pubkey>,
close_order_account: bool,
) -> Instruction {
let mut account_metas = vec![
AccountMeta::new(signer, true),
AccountMeta::new(order, false),
AccountMeta::new_readonly(merchant, false),
AccountMeta::new(order_payment_token, false),
AccountMeta::new(merchant_token, false),
AccountMeta::new(account_to_receive_sol_refund, false),
AccountMeta::new_readonly(pda, false),
AccountMeta::new_readonly(spl_token::id(), false),
];
if let Some(subscription) = subscription {
account_metas.push(AccountMeta::new_readonly(subscription, false));
}
Instruction {
program_id,
accounts: account_metas,
data: PaymentProcessorInstruction::Withdraw {
close_order_account,
}
.try_to_vec()
.unwrap(),
}
}
/// creates a 'Subscribe' instruction
pub fn subscribe(
program_id: Pubkey,
signer: Pubkey,
subscription: Pubkey,
merchant: Pubkey,
order: Pubkey,
name: String,
data: Option<String>,
) -> Instruction {
Instruction {
program_id,
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(subscription, false),
AccountMeta::new_readonly(merchant, false),
AccountMeta::new_readonly(order, false),
AccountMeta::new_readonly(solana_program::system_program::id(), false),
AccountMeta::new_readonly(sysvar::rent::id(), false),
],
data: PaymentProcessorInstruction::Subscribe { name, data }
.try_to_vec()
.unwrap(),
}
}
/// creates a 'RenewSubscription' instruction
pub fn renew_subscription(
program_id: Pubkey,
signer: Pubkey,
subscription: Pubkey,
merchant: Pubkey,
order: Pubkey,
quantity: i64,
) -> Instruction {
Instruction {
program_id,
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(subscription, false),
AccountMeta::new_readonly(merchant, false),
AccountMeta::new_readonly(order, false),
],
data: PaymentProcessorInstruction::RenewSubscription { quantity }
.try_to_vec()
.unwrap(),
}
}
/// creates a 'CancelSubscription' instruction
pub fn cancel_subscription(
program_id: Pubkey,
signer: Pubkey,
subscription: Pubkey,
merchant: Pubkey,
order: Pubkey,
order_token: Pubkey,
refund_token: Pubkey,
account_to_receive_sol_refund: Pubkey,
pda: Pubkey,
) -> Instruction {
Instruction {
program_id,
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(subscription, false),
AccountMeta::new_readonly(merchant, false),
AccountMeta::new(order, false),
AccountMeta::new(order_token, false),
AccountMeta::new(refund_token, false),
AccountMeta::new(account_to_receive_sol_refund, false),
AccountMeta::new_readonly(pda, false),
AccountMeta::new_readonly(spl_token::id(), false),
],
data: PaymentProcessorInstruction::CancelSubscription
.try_to_vec()
.unwrap(),
}
}
#[cfg(test)]
mod test {
use {
super::*,
crate::engine::constants::{
DEFAULT_FEE_IN_LAMPORTS, INITIAL, MERCHANT, MIN_FEE_IN_LAMPORTS, PAID, PDA_SEED,
PROGRAM_OWNER, SPONSOR_FEE,
},
crate::error::PaymentProcessorError,
crate::instruction::PaymentProcessorInstruction,
crate::state::{
MerchantAccount, OrderAccount, OrderStatus, Serdes, SubscriptionAccount,
SubscriptionStatus,
},
crate::utils::{get_amounts, get_order_account_size},
assert_matches::*,
serde_json::{json, Value},
solana_program::{
hash::Hash,
program_pack::{IsInitialized, Pack},
rent::Rent,
system_instruction,
},
solana_program_test::*,
solana_sdk::{
instruction::InstructionError,
signature::{Keypair, Signer},
transaction::{Transaction, TransactionError},
transport::TransportError,
},
spl_token::{
instruction::{initialize_account, initialize_mint, mint_to},
state::{Account as TokenAccount, Mint},
},
std::str::FromStr,
};
type MerchantResult = (Pubkey, Pubkey, BanksClient, Keypair, Hash);
fn create_mint_transaction(
payer: &Keypair,
mint: &Keypair,
mint_authority: &Keypair,
recent_blockhash: Hash,
) -> Transaction {
let instructions = [
system_instruction::create_account(
&payer.pubkey(),
&mint.pubkey(),
Rent::default().minimum_balance(Mint::LEN),
Mint::LEN as u64,
&spl_token::id(),
),
initialize_mint(
&spl_token::id(),
&mint.pubkey(),
&mint_authority.pubkey(),
None,
0,
)
.unwrap(),
];
let mut transaction = Transaction::new_with_payer(&instructions, Some(&payer.pubkey()));
transaction.partial_sign(&[payer, mint], recent_blockhash);
transaction
}
fn create_token_account_transaction(
payer: &Keypair,
mint: &Keypair,
recent_blockhash: Hash,
token_account: &Keypair,
token_account_owner: &Pubkey,
amount: u64,
) -> Transaction {
let instructions = [
system_instruction::create_account(
&payer.pubkey(),
&token_account.pubkey(),
Rent::default().minimum_balance(TokenAccount::LEN),
TokenAccount::LEN as u64,
&spl_token::id(),
),
initialize_account(
&spl_token::id(),
&token_account.pubkey(),
&mint.pubkey(),
token_account_owner,
)
.unwrap(),
mint_to(
&spl_token::id(),
&mint.pubkey(),
&token_account.pubkey(),
token_account_owner,
&[&payer.pubkey()],
amount,
)
.unwrap(),
];
let mut transaction = Transaction::new_with_payer(&instructions, Some(&payer.pubkey()));
transaction.partial_sign(&[payer, token_account], recent_blockhash);
transaction
}
async fn create_merchant_account(
seed: Option<String>,
fee: Option<u64>,
sponsor: Option<&Pubkey>,
data: Option<String>,
) -> MerchantResult {
let program_id = Pubkey::from_str(&"mosh111111111111111111111111111111111111111").unwrap();
let (mut banks_client, payer, recent_blockhash) = ProgramTest::new(
"sol_payment_processor",
program_id,
processor!(PaymentProcessorInstruction::process),
)
.start()
.await;
let real_seed = match &seed {
None => MERCHANT,
Some(value) => &value,
};
// first we create a public key for the merchant account
let merchant_acc_pubkey =
Pubkey::create_with_seed(&payer.pubkey(), real_seed, &program_id).unwrap();
// then call register merchant ix
let mut transaction = Transaction::new_with_payer(
&[register_merchant(
program_id,
payer.pubkey(),
merchant_acc_pubkey,
Some(real_seed.to_string()),
fee,
data,
sponsor,
)],
Some(&payer.pubkey()),
);
transaction.sign(&[&payer], recent_blockhash);
assert_matches!(banks_client.process_transaction(transaction).await, Ok(()));
return (
program_id,
merchant_acc_pubkey,
banks_client,
payer,
recent_blockhash,
);
}
async fn prepare_order(
program_id: &Pubkey,
merchant: &Pubkey,
mint: &Pubkey,
banks_client: &mut BanksClient,
) -> (Keypair, Pubkey, Pubkey, MerchantAccount) {
let order_acc_keypair = Keypair::new();
let (pda, _bump_seed) = Pubkey::find_program_address(&[PDA_SEED], &program_id);
let (seller_token, _bump_seed) = Pubkey::find_program_address(
&[
&order_acc_keypair.pubkey().to_bytes(),
&spl_token::id().to_bytes(),
&mint.to_bytes(),
],
program_id,
);
let merchant_account = banks_client.get_account(*merchant).await;
let merchant_data = match merchant_account {
Ok(data) => match data {
None => panic!("Oo"),
Some(value) => match MerchantAccount::unpack(&value.data) {
Ok(data) => data,
Err(error) => panic!("Problem: {:?}", error),
},
},
Err(error) => panic!("Problem: {:?}", error),
};
(order_acc_keypair, seller_token, pda, merchant_data)
}
async fn create_token_account(
amount: u64,
mint_keypair: &Keypair,
merchant_result: &mut MerchantResult,
) -> Keypair {
// next create token account for test
let buyer_token_keypair = Keypair::new();
// create and initialize mint
assert_matches!(
merchant_result
.2
.process_transaction(create_mint_transaction(
&merchant_result.3,
&mint_keypair,
&merchant_result.3,
merchant_result.4
))
.await,
Ok(())
);
// create and initialize buyer token account
assert_matches!(
merchant_result
.2
.process_transaction(create_token_account_transaction(
&merchant_result.3,
&mint_keypair,
merchant_result.4,
&buyer_token_keypair,
&merchant_result.3.pubkey(),
amount + 2000000,
))
.await,
Ok(())
);
buyer_token_keypair
}
async fn create_order_express_checkout(
amount: u64,
order_id: &String,
secret: &String,
data: Option<String>,
merchant_result: &mut MerchantResult,
mint_keypair: &Keypair,
) -> (Pubkey, Pubkey) {
let buyer_token_keypair = create_token_account(amount, mint_keypair, merchant_result).await;
let (order_acc_keypair, seller_token, pda, merchant_data) = prepare_order(
&merchant_result.0,
&merchant_result.1,
&mint_keypair.pubkey(),
&mut merchant_result.2,
)
.await;
// call express checkout ix
let mut transaction = Transaction::new_with_payer(
&[express_checkout(
merchant_result.0,
merchant_result.3.pubkey(),
order_acc_keypair.pubkey(),
merchant_result.1,
seller_token,
buyer_token_keypair.pubkey(),
mint_keypair.pubkey(),
Pubkey::from_str(PROGRAM_OWNER).unwrap(),
Pubkey::new_from_array(merchant_data.sponsor),
pda,
amount,
(&order_id).to_string(),
(&secret).to_string(),
data,
)],
Some(&merchant_result.3.pubkey()),
);
transaction.sign(&[&merchant_result.3, &order_acc_keypair], merchant_result.4);
assert_matches!(
&mut merchant_result.2.process_transaction(transaction).await,
Ok(())
);
(order_acc_keypair.pubkey(), seller_token)
}
async fn create_chain_checkout_transaction(
amount: u64,
order_items: &OrderItems,
data: Option<String>,
merchant_result: &mut MerchantResult,
mint_keypair: &Keypair,
) -> Result<(Pubkey, Pubkey), TransportError> {
let buyer_token_keypair = create_token_account(amount, mint_keypair, merchant_result).await;
let (order_acc_keypair, seller_token, pda, merchant_data) = prepare_order(
&merchant_result.0,
&merchant_result.1,
&mint_keypair.pubkey(),
&mut merchant_result.2,
)
.await;
let order_items = order_items.clone();
// call chain checkout ix
let mut transaction = Transaction::new_with_payer(
&[chain_checkout(
merchant_result.0,
merchant_result.3.pubkey(),
order_acc_keypair.pubkey(),
merchant_result.1,
seller_token,
buyer_token_keypair.pubkey(),
mint_keypair.pubkey(),
Pubkey::from_str(PROGRAM_OWNER).unwrap(),
Pubkey::new_from_array(merchant_data.sponsor),
pda,
amount,
order_items,
data,
)],
Some(&merchant_result.3.pubkey()),
);
transaction.sign(&[&merchant_result.3, &order_acc_keypair], merchant_result.4);
let _result = merchant_result.2.process_transaction(transaction).await?;
Ok((order_acc_keypair.pubkey(), seller_token))
}
async fn create_order_chain_checkout(
amount: u64,
order_items: &OrderItems,
data: Option<String>,
merchant_result: &mut MerchantResult,
mint_keypair: &Keypair,
) -> (Pubkey, Pubkey) {
let transaction = create_chain_checkout_transaction(
amount,
order_items,
data,
merchant_result,
mint_keypair,
)
.await;
assert!(transaction.is_ok());
transaction.unwrap()
}
async fn run_merchant_tests(result: MerchantResult) -> MerchantAccount {
let program_id = result.0;
let merchant = result.1;
let mut banks_client = result.2;
let payer = result.3;
// test contents of merchant account
let merchant_account = banks_client.get_account(merchant).await;
let merchant_account = match merchant_account {
Ok(data) => match data {
None => panic!("Oo"),
Some(value) => value,
},
Err(error) => panic!("Problem: {:?}", error),
};
assert_eq!(merchant_account.owner, program_id);
let merchant_data = MerchantAccount::unpack(&merchant_account.data);
let merchant_data = match merchant_data {
Ok(data) => data,
Err(error) => panic!("Problem: {:?}", error),
};
assert_eq!(true, merchant_data.is_initialized());
assert_eq!(payer.pubkey(), Pubkey::new_from_array(merchant_data.owner));
merchant_data
}
#[tokio::test]
async fn test_register_merchant() {
let result =
create_merchant_account(Option::None, Option::None, Option::None, Option::None).await;
let merchant_data = run_merchant_tests(result).await;
assert_eq!(DEFAULT_FEE_IN_LAMPORTS, merchant_data.fee);
assert_eq!(String::from("{}"), merchant_data.data);
}
#[tokio::test]
async fn test_register_merchant_with_seed() {
let result = create_merchant_account(
Some(String::from("mosh")),
Option::None,
Option::None,
Option::None,
)
.await;
let merchant = result.1;
let payer = result.3;
let program_id = result.0;
assert_eq!(
merchant,
Pubkey::create_with_seed(&payer.pubkey(), "mosh", &program_id).unwrap()
);
}
#[tokio::test]
/// assert that the minimum fee is used when custom fee too low
async fn test_register_merchant_fee_default() {
let result =
create_merchant_account(Option::None, Some(10), Option::None, Option::None).await;
let merchant_data = run_merchant_tests(result).await;
assert_eq!(MIN_FEE_IN_LAMPORTS, merchant_data.fee);
}
#[tokio::test]
async fn test_register_merchant_with_all_stuff() {
let seed = String::from("mosh");
let sponsor_pk = Pubkey::new_unique();
let data = String::from(
r#"{"code":200,"success":true,"payload":{"features":["awesome","easyAPI","lowLearningCurve"]}}"#,
);
let datas = data.clone();
let result =
create_merchant_account(Some(seed), Some(90000), Some(&sponsor_pk), Some(data)).await;
let merchant_data = run_merchant_tests(result).await;
assert_eq!(datas, merchant_data.data);
assert_eq!(90000, merchant_data.fee);
assert_eq!(sponsor_pk, Pubkey::new_from_array(merchant_data.sponsor));
// just for sanity verify that you can get some of the JSON values
let json_value: Value = serde_json::from_str(&merchant_data.data).unwrap();
assert_eq!(200, json_value["code"]);
assert_eq!(true, json_value["success"]);
}
async fn run_common_checkout_tests(
amount: u64,
merchant_result: &mut MerchantResult,
order_acc_pubkey: &Pubkey,
seller_account_pubkey: &Pubkey,
mint_keypair: &Keypair,
) -> OrderAccount {
// program_id => merchant_result.0;
// merchant_account_pubkey => merchant_result.1;
// banks_client => merchant_result.2;
// payer => merchant_result.3;
let order_account = merchant_result.2.get_account(*order_acc_pubkey).await;
let order_account = match order_account {
Ok(data) => match data {
None => panic!("Oo"),
Some(value) => value,
},
Err(error) => panic!("Problem: {:?}", error),
};
assert_eq!(order_account.owner, merchant_result.0,);
let order_data = OrderAccount::unpack(&order_account.data);
let order_data = match order_data {
Ok(data) => data,
Err(error) => panic!("Problem: {:?}", error),
};
assert_eq!(true, order_data.is_initialized());
assert_eq!(OrderStatus::Paid as u8, order_data.status);
assert_eq!(merchant_result.1.to_bytes(), order_data.merchant);
assert_eq!(mint_keypair.pubkey().to_bytes(), order_data.mint);
assert_eq!(seller_account_pubkey.to_bytes(), order_data.token);
assert_eq!(merchant_result.3.pubkey().to_bytes(), order_data.payer);
assert_eq!(amount, order_data.expected_amount);
assert_eq!(amount, order_data.paid_amount);
assert_eq!(
order_account.lamports,
Rent::default().minimum_balance(get_order_account_size(
&order_data.order_id,
&order_data.secret,
&order_data.data,
))
);
// test contents of seller token account
let seller_token_account = merchant_result.2.get_account(*seller_account_pubkey).await;
let seller_token_account = match seller_token_account {
Ok(data) => match data {
None => panic!("Oo"),
Some(value) => value,
},
Err(error) => panic!("Problem: {:?}", error),
};
let seller_account_data = spl_token::state::Account::unpack(&seller_token_account.data);
let seller_account_data = match seller_account_data {
Ok(data) => data,
Err(error) => panic!("Problem: {:?}", error),
};
let (pda, _bump_seed) = Pubkey::find_program_address(&[PDA_SEED], &merchant_result.0);
assert_eq!(amount, seller_account_data.amount);
assert_eq!(pda, seller_account_data.owner);
assert_eq!(mint_keypair.pubkey(), seller_account_data.mint);
// test that sponsor was saved okay
let merchant_account = merchant_result.2.get_account(merchant_result.1).await;
let merchant_data = match merchant_account {
Ok(data) => match data {
None => panic!("Oo"),
Some(value) => match MerchantAccount::unpack(&value.data) {
Ok(data) => data,
Err(error) => panic!("Problem: {:?}", error),
},
},
Err(error) => panic!("Problem: {:?}", error),
};
let program_owner_key = Pubkey::from_str(PROGRAM_OWNER).unwrap();
let sponsor = Pubkey::new_from_array(merchant_data.sponsor);
let program_owner_account = merchant_result.2.get_account(program_owner_key).await;
let program_owner_account = match program_owner_account {
Ok(data) => match data {
None => panic!("Oo"),
Some(value) => value,
},
Err(error) => panic!("Problem: {:?}", error),
};
if sponsor == program_owner_key {
// test contents of program owner account
assert_eq!(merchant_data.fee, program_owner_account.lamports);
} else {
// test contents of program owner account and sponsor account
let (program_owner_fee, sponsor_fee) = get_amounts(merchant_data.fee, SPONSOR_FEE);
let sponsor_account = merchant_result.2.get_account(sponsor).await;
let sponsor_account = match sponsor_account {
Ok(data) => match data {
None => panic!("Oo"),
Some(value) => value,
},
Err(error) => panic!("Problem: {:?}", error),
};
assert_eq!(program_owner_fee, program_owner_account.lamports);
assert_eq!(sponsor_fee, sponsor_account.lamports);
}
order_data
}
async fn run_checkout_tests(
amount: u64,
order_id: String,
secret: String,
data: Option<String>,
merchant_result: &mut MerchantResult,
order_acc_pubkey: &Pubkey,
seller_account_pubkey: &Pubkey,
mint_keypair: &Keypair,
) {
let order_data = run_common_checkout_tests(
amount,
merchant_result,
order_acc_pubkey,
seller_account_pubkey,
mint_keypair,
)
.await;
let data_string = match data {
None => String::from("{}"),
Some(value) => value,
};
assert_eq!(order_id, order_data.order_id);
assert_eq!(secret, order_data.secret);
assert_eq!(data_string, order_data.data);
}
async fn run_chain_checkout_tests(
amount: u64,
order_items: &OrderItems,
data: Option<String>,
merchant_result: &mut MerchantResult,
order_acc_pubkey: &Pubkey,
seller_account_pubkey: &Pubkey,
mint_keypair: &Keypair,
) {
// test contents of order account
let order_data = run_common_checkout_tests(
amount,
merchant_result,
order_acc_pubkey,
seller_account_pubkey,
mint_keypair,
)
.await;
match data {
None => {
assert_eq!(json!({ PAID: order_items }).to_string(), order_data.data);
}
Some(value) => {
let json_data: Value = match serde_json::from_str(&value) {
Err(error) => panic!("Problem: {:?}", error),
Ok(data) => data,