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
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
#![forbid(unsafe_code)]
#![deny(clippy::all)]
#![allow(clippy::too_many_arguments)]
#![cfg(not(feature = "no-entrypoint"))]
pub mod consts;
pub mod error;
pub mod state;
pub mod vest;

use std::mem;

use crate::consts::*;
use crate::error::Error;
use crate::state::{
    init_state, try_migrate_state, ContractState, PostInfo, RepostRecord, STATE_ACC_SIZE,
};

use borsh::{BorshDeserialize, BorshSerialize};

use human_common::entity::{initialize_entity, next_entity, Entity};
use mpl_token_metadata::state::{CollectionDetails, Creator, TokenMetadataAccount};
use solana_program::clock::{Clock, UnixTimestamp};
use solana_program::program_memory::sol_memset;
use solana_program::{
    account_info::{next_account_info, AccountInfo},
    entrypoint,
    entrypoint::ProgramResult,
    instruction::{self, AccountMeta},
    msg,
    program::{invoke, invoke_signed},
    program_error::ProgramError,
    program_option::COption,
    program_pack::Pack,
    pubkey::Pubkey,
    rent::Rent,
    system_instruction, system_program,
    sysvar::{self, Sysvar},
};
use spl_associated_token_account::get_associated_token_address;
use spl_math::precise_number::PreciseNumber;
use spl_token::instruction::{close_account, initialize_account2};
use spl_token_swap::instruction as swap_instruction;

use human_common::utils::{
    next_atoken_wallet, next_expected_account, next_expected_token_wallet, next_signer_account,
};

use shank::ShankInstruction;

use anchor_lang::AccountDeserialize;
use anchor_lang::InstructionData;

#[derive(Debug, BorshDeserialize, BorshSerialize)]
#[repr(C)]
pub struct InitInstruction {
    /// Alice
    pub owner: Pubkey,
    /// required for priveleged operations
    pub admin: Pubkey,
    /// comission account, could be changed by the admin
    pub commission: Pubkey,
    /// treasury comission
    pub treasury: Pubkey,
    /// swap to deposit liquidity to
    pub swap_state: Pubkey,
}

#[derive(Debug, BorshDeserialize, BorshSerialize)]
#[repr(C)]
pub struct CreateDropInstruction {
    // some unique ID
    pub id: u64,
    // how much to sell
    pub amount: u64,
    // price per chatlan
    pub price: u64,

    pub start_date: UnixTimestamp,
    pub end_date: UnixTimestamp,
}

#[derive(Debug, BorshDeserialize, BorshSerialize)]
#[repr(C)]
pub struct EmitInstruction {
    // amount to emit
    pub amount: u64,
}

#[derive(Debug, BorshDeserialize, BorshSerialize)]
#[repr(C)]
pub struct BuyInstruction {
    // amount of chatlans to buy
    pub amount: u64,
    // expected price per chatlan
    pub expected_price: u64,
}

#[derive(Debug, BorshDeserialize, BorshSerialize)]
#[repr(C)]
pub struct SetAdminInstruction {
    pub admin: Pubkey,
}

#[derive(Debug, BorshDeserialize, BorshSerialize)]
#[repr(C)]
pub struct RegisterPostInstruction {
    pub royalty_addr: Pubkey,
    pub post_id: [u8; 32],
    pub created_at: UnixTimestamp,
    pub post_name: String,
    pub post_metadata_uri: String,
    pub collection_name: String,
    pub collection_metadata_uri: String,
    pub symbol: String,
    pub repost_price: u64,
}

#[derive(Debug, BorshDeserialize, BorshSerialize)]
#[repr(C)]
pub struct RepostInstruction {}

#[derive(Debug, BorshDeserialize, BorshSerialize)]
#[repr(C)]
pub struct CreateRoundInstruction {
    bidding_start: UnixTimestamp,
    bidding_end: UnixTimestamp,
    offer_amount: u64,
    target_bid: u64,
}

#[derive(Debug, BorshDeserialize, BorshSerialize, ShankInstruction)]
#[repr(u8)]
#[non_exhaustive]
pub enum Instruction {
    CreateWallets,
    Init(InitInstruction),
    Emit(EmitInstruction),
    Buy(BuyInstruction),
    CreateDrop(CreateDropInstruction),
    Withdraw,
    Vest,
    MigrateState,
    SetAdmin(SetAdminInstruction),
    DepositCommission,
    RegisterPost(RegisterPostInstruction),
    Repost(RepostInstruction),
    RedeemRepost,
    CreateRound(CreateRoundInstruction),
    ClaimRoundVesting,
}

entrypoint!(process_instruction);
pub fn process_instruction(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    instruction_data: &[u8],
) -> ProgramResult {
    let instruction = Instruction::try_from_slice(instruction_data).map_err(|e| {
        msg!("error parsing instruction: {}", e);
        ProgramError::InvalidInstructionData
    })?;

    match instruction {
        Instruction::CreateWallets => {
            msg!("creating wallets");
            process_create_wallets(program_id, accounts)?
        }
        Instruction::Init(ii) => {
            msg!("initializing account");
            process_init_state(program_id, accounts, ii)?;
        }
        Instruction::Emit(EmitInstruction { amount }) => {
            msg!("emitting {} tokens", amount);
            emit(program_id, accounts, amount)?;
        }
        Instruction::Buy(BuyInstruction {
            amount,
            expected_price,
        }) => {
            msg!(
                "buying {} chatlans with expected price {}",
                amount,
                expected_price
            );
            buy(program_id, accounts, amount, expected_price)?;
        }
        Instruction::CreateDrop(inst) => {
            msg!("creating drop");
            process_create_drop(program_id, accounts, inst)?;
        }
        Instruction::Withdraw => {
            msg!("withdrawing all tokens");
            withdraw(program_id, accounts)?;
        }
        Instruction::Vest => {
            msg!("vesting disabled");
            //process_vest(program_id, accounts)?;
        }
        Instruction::MigrateState => {
            msg!("migrating state");
            process_migrate_state(program_id, accounts)?;
        }
        Instruction::SetAdmin(SetAdminInstruction { admin }) => {
            msg!("updating admin state");
            process_set_admin(program_id, accounts, admin)?;
        }
        Instruction::DepositCommission => {
            msg!("depositing commission");
            process_deposit_commission(program_id, accounts)?;
        }
        Instruction::RegisterPost(args) => {
            msg!("registering post");
            process_register_post(program_id, accounts, args)?;
        }
        Instruction::Repost(args) => {
            msg!("reposting");
            process_repost(program_id, accounts, args)?;
        }
        Instruction::RedeemRepost => {
            msg!("redeem repost");
            process_redeem_repost(program_id, accounts)?;
        }
        Instruction::CreateRound(args) => {
            msg!("creating round");
            process_create_round(program_id, accounts, args)?;
        }
        Instruction::ClaimRoundVesting => {
            msg!("claiming round vesting");
            process_claim_round_vesting(program_id, accounts)?;
        }
    }

    Ok(())
}

#[macro_export]
macro_rules! find_keyed_address {
    ($program_id:expr, $seed:expr) => {
        $crate::find_keyed_address!($program_id, $seed, &[])
    };
    ($program_id:expr, $seed:expr, $token:expr) => {{
        let _: (&Pubkey, &[u8]) = ($program_id, $token);

        let seeds = &[V1, $seed, ($token)];
        let (addr, bump) = Pubkey::find_program_address(seeds, $program_id);

        (addr, &[V1, $seed, $token, &[bump]])
    }};
}

#[macro_export]
macro_rules! authority {
    ($program_id:expr) => {
        $crate::find_keyed_address!($program_id, AUTHORITY_SEED)
    };
}

#[macro_export]
macro_rules! contract_state {
    ($program_id:expr, $token:expr) => {
        $crate::find_keyed_address!($program_id, STATE_SEED, $token.as_ref())
    };
}

#[macro_export]
macro_rules! contract_wallet {
    ($program_id:expr, $token:expr) => {
        $crate::find_keyed_address!($program_id, WALLET_SEED, $token.as_ref())
    };
}

#[macro_export]
macro_rules! contract_vault {
    ($program_id:expr, $token:expr) => {
        $crate::find_keyed_address!($program_id, VAULT_SEED, $token.as_ref())
    };
}

#[macro_export]
macro_rules! contract_stash {
    ($program_id:expr, $token:expr) => {
        $crate::find_keyed_address!($program_id, STASH_SEED, $token.as_ref())
    };
}

#[macro_export]
macro_rules! master_post_mint {
    ($program_id:expr, $id:expr) => {
        $crate::find_keyed_address!($program_id, MASTER_POST_MINT_SEED, $id.as_ref())
    };
}

#[macro_export]
macro_rules! post_info {
    ($program_id:expr, $id:expr) => {
        $crate::find_keyed_address!($program_id, POST_INFO_SEED, $id.as_ref())
    };
}

#[macro_export]
macro_rules! repost_record {
    ($program_id:expr, $token:expr) => {
        $crate::find_keyed_address!($program_id, REPOST_RECORD_SEED, $token.as_ref())
    };
}

#[macro_export]
macro_rules! collection_mint {
    ($program_id:expr, $token:expr) => {
        $crate::find_keyed_address!($program_id, COLLECTION_MINT_SEED, $token.as_ref())
    };
}

// [] derived state account
// [] token mint addr
// [signer] funder
// [] token prog
// [] sysprog
fn process_init_state(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    args: InitInstruction,
) -> Result<(), ProgramError> {
    let account_info_iter = &mut accounts.iter();

    let state = next_account_info(account_info_iter)?;
    let mint_acc = next_account_info(account_info_iter)?;
    let fee_payer = next_account_info(account_info_iter)?;
    next_expected_account(account_info_iter, &spl_token::ID)?;
    next_expected_account(account_info_iter, &system_program::ID)?;

    let rent = Rent::get()?;
    let clock = Clock::get()?;

    if !spl_token::check_id(mint_acc.owner) {
        return Err(ProgramError::InvalidArgument);
    }

    let (state_addr, state_seed) = contract_state!(program_id, mint_acc.key);

    if *state.key != state_addr {
        msg!("invalid derived address {} != {}", state.key, state_addr);
        return Err(ProgramError::InvalidArgument);
    }

    // check token has no mint authority
    let mint = spl_token::state::Mint::unpack(&mint_acc.data.borrow())?;
    if mint.mint_authority != COption::None {
        msg!("token should have fixed supply");
        return Err(ProgramError::InvalidArgument);
    }

    msg!("creating state account");

    let lamports = rent.minimum_balance(STATE_ACC_SIZE);

    let create_instruction = system_instruction::create_account(
        fee_payer.key,
        &state_addr,
        lamports,
        STATE_ACC_SIZE as u64,
        program_id,
    );

    invoke_signed(&create_instruction, accounts, &[state_seed])?;

    if state.owner != program_id {
        return Err(ProgramError::IllegalOwner);
    }

    let mut data = state.try_borrow_mut_data()?;

    msg!("initializing state");
    init_state(&mut data, *mint_acc.key, args, clock.unix_timestamp)?;

    Ok(())
}

pub fn create_init_instruction(
    program_id: &Pubkey,
    state: &Pubkey,
    token: &Pubkey,
    feepayer: &Pubkey,
    args: InitInstruction,
) -> Result<instruction::Instruction, ProgramError> {
    let accounts = vec![
        AccountMeta::new(state.to_owned(), false),
        AccountMeta::new_readonly(token.to_owned(), false),
        AccountMeta::new_readonly(feepayer.to_owned(), true),
        AccountMeta::new_readonly(spl_token::id(), false),
        AccountMeta::new_readonly(system_program::id(), false),
        AccountMeta::new_readonly(*program_id, false),
    ];

    Ok(instruction::Instruction {
        program_id: *program_id,
        accounts,
        data: Instruction::Init(args).try_to_vec()?,
    })
}

// [write] state
// [] swap state
// [] wsol account
pub fn process_migrate_state(
    _program_id: &Pubkey,
    accounts: &[AccountInfo],
) -> Result<(), ProgramError> {
    let account_info_iter = &mut accounts.iter();

    let state = next_account_info(account_info_iter)?;
    let token_mint = next_account_info(account_info_iter)?;
    let wsol_commission = next_account_info(account_info_iter)?;
    let treasury = next_account_info(account_info_iter)?;

    let mut state_data = state.data.borrow_mut();

    if state_data.is_empty() {
        return Err(ProgramError::InvalidAccountData);
    }

    try_migrate_state(
        &mut state_data,
        *token_mint.key,
        *wsol_commission.key,
        *treasury.key,
        Clock::get()?.unix_timestamp,
    )?;

    Ok(())
}

// [] token mint addr
// [write] derived wallet
// [write] derived vault wallet
// [signer] fee payer
// [] token prog
// [] sysprog
// [] rent var TODO fix weird local validator error
fn process_create_wallets(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
) -> Result<(), ProgramError> {
    let account_info_iter = &mut accounts.iter();

    let token_mint = next_account_info(account_info_iter)?;
    let wallet = next_account_info(account_info_iter)?;
    let vault = next_account_info(account_info_iter)?;
    let fee_payer = next_account_info(account_info_iter)?;

    let _ = next_account_info(account_info_iter)?;
    let _ = next_account_info(account_info_iter)?;
    let rent = Rent::get()?;

    let (wallet_addr, wallet_seed) = contract_wallet!(program_id, token_mint.key);
    if *wallet.key != wallet_addr {
        return Err(ProgramError::InvalidArgument);
    }

    let (vault_addr, vault_seed) = contract_vault!(program_id, token_mint.key);
    if *vault.key != vault_addr {
        return Err(ProgramError::InvalidArgument);
    }

    let (transfer_authority, _) = authority!(program_id);

    let acc_size = spl_token::state::Account::LEN;
    let min_balance = rent.minimum_balance(acc_size);

    let create_wallet = solana_program::system_instruction::create_account(
        fee_payer.key,
        &wallet_addr,
        min_balance,
        acc_size as u64,
        &spl_token::ID,
    );
    invoke_signed(&create_wallet, accounts, &[wallet_seed])?;

    let initialize_wallet = spl_token::instruction::initialize_account2(
        &spl_token::ID,
        &wallet_addr,
        token_mint.key,
        &transfer_authority,
    )?;
    invoke(&initialize_wallet, accounts)?;

    let create_vault = solana_program::system_instruction::create_account(
        fee_payer.key,
        &vault_addr,
        min_balance,
        acc_size as u64,
        &spl_token::ID,
    );
    invoke_signed(&create_vault, accounts, &[vault_seed])?;

    let initialize_vault = spl_token::instruction::initialize_account2(
        &spl_token::ID,
        &vault_addr,
        token_mint.key,
        &transfer_authority,
    )?;
    invoke(&initialize_vault, accounts)?;

    Ok(())
}

pub fn create_wallets(
    program_id: &Pubkey,
    token_mint: &Pubkey,
    fee_payer: &Pubkey,
) -> instruction::Instruction {
    let (wallet_addr, _) = contract_wallet!(program_id, token_mint);
    let (vault_addr, _) = contract_vault!(program_id, token_mint);

    let accounts = vec![
        AccountMeta::new_readonly(token_mint.to_owned(), false),
        AccountMeta::new(wallet_addr.to_owned(), false),
        AccountMeta::new(vault_addr.to_owned(), false),
        AccountMeta::new_readonly(fee_payer.to_owned(), true),
        AccountMeta::new_readonly(spl_token::id(), false),
        AccountMeta::new_readonly(system_program::id(), false),
        AccountMeta::new_readonly(sysvar::rent::ID, false),
        AccountMeta::new_readonly(*program_id, false),
    ];

    instruction::Instruction {
        program_id: *program_id,
        accounts,
        data: Instruction::CreateWallets.try_to_vec().unwrap(),
    }
}

// [write] state
// [singer] owner account
// [singer] admin authority
// [write] wallet to transfer tokens to
// [write] vault
// [] transfer authority
// [] token program
fn emit(_program_id: &Pubkey, _accounts: &[AccountInfo], _amount: u64) -> Result<(), ProgramError> {
    unimplemented!("not used, so disabled");

    // let account_info_iter = &mut accounts.iter();

    // let (state, _) = next_entity::<_, ContractState>(account_info_iter, program_id)?;

    // next_signer_account(account_info_iter, &state.owner)?;
    // next_signer_account(account_info_iter, &state.admin)?;

    // let wallet = next_account_info(account_info_iter)?;
    // let vault = next_account_info(account_info_iter)?;
    // let transfer_authority = next_account_info(account_info_iter)?;

    // let tokenprog = next_account_info(account_info_iter)?;

    // let (derived_authority, authority_seed) = transfer_authority!(program_id);

    // if *transfer_authority.key != derived_authority {
    //     return Err(ProgramError::InvalidArgument);
    // }

    // if !spl_token::check_id(tokenprog.key) {
    //     return Err(ProgramError::InvalidArgument);
    // }

    // let inst = spl_token::instruction::transfer(
    //     &spl_token::ID,
    //     vault.key,
    //     wallet.key,
    //     &derived_authority,
    //     &[],
    //     amount,
    // )?;

    // invoke_signed(&inst, accounts, &[authority_seed])?;

    // Ok(())
}

// [writable] state
// [singer] owner account
fn process_create_drop(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    args: CreateDropInstruction,
) -> Result<(), ProgramError> {
    let account_info_iter = &mut accounts.iter();

    let (mut state, _) = next_entity::<_, ContractState>(account_info_iter, program_id)?;
    next_signer_account(account_info_iter, &state.owner)?;

    let clock = Clock::get()?;

    state.create_drop(
        args.price,
        args.id,
        args.amount,
        clock.unix_timestamp,
        args.start_date,
        args.end_date,
    )?;

    Ok(())
}

pub fn create_drop_instruction(
    program_id: &Pubkey,
    token_mint: &Pubkey,
    owner: &Pubkey,
    id: u64,
    amount: u64,
    price: u64,
    start_date: UnixTimestamp,
    end_date: UnixTimestamp,
) -> Result<instruction::Instruction, ProgramError> {
    let (state, _) = contract_state!(program_id, token_mint);

    let accounts = vec![
        AccountMeta::new(state, false),
        AccountMeta::new(owner.to_owned(), true),
    ];

    Ok(instruction::Instruction {
        program_id: *program_id,
        accounts,
        data: Instruction::CreateDrop(CreateDropInstruction {
            id,
            amount,
            price,
            start_date,
            end_date,
        })
        .try_to_vec()?,
    })
}

// [writable] state
// [signer] owner account
// [write] owner wallet
// [writable] derived wallet
// [] contract transfer authority
// [] token program
fn withdraw(program_id: &Pubkey, accounts: &[AccountInfo]) -> Result<(), ProgramError> {
    let account_info_iter = &mut accounts.iter();

    let (mut state, _) = next_entity::<_, ContractState>(account_info_iter, program_id)?;
    let _owner = next_signer_account(account_info_iter, &state.owner)?;
    let (owner_wallet, _) = next_atoken_wallet(account_info_iter, &state.owner, &state.token)?;

    let (derived_contract_wallet, _) = contract_wallet!(program_id, state.token);
    let contract_wallet = next_expected_token_wallet(account_info_iter, &derived_contract_wallet)?;

    let (authority, authority_seed) = authority!(program_id);
    next_expected_account(account_info_iter, &authority)?;
    next_expected_account(account_info_iter, &spl_token::ID)?;

    // withdraw all funds
    let inst = spl_token::instruction::transfer(
        &spl_token::ID,
        &derived_contract_wallet,
        &owner_wallet,
        &authority,
        &[],
        contract_wallet.amount,
    )?;

    invoke_signed(&inst, accounts, &[authority_seed])?;

    state.clear_drop();

    Ok(())
}

// [] state account
// [write] contract wallet
// [] transfer authority
// [write, sign] buyer
// [write] tokens dest
//
// [write] owner acc
// [write] treasury
//
// [] token prog
// [] system prog
fn buy(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    amount: u64,
    expected_price: u64,
) -> Result<(), ProgramError> {
    let account_info_iter = &mut accounts.iter();

    let (mut state, state_acc) = next_entity::<_, ContractState>(account_info_iter, program_id)?; // 1

    let (derived_contract_wallet, _) = contract_wallet!(program_id, state.token);
    next_expected_token_wallet(account_info_iter, &derived_contract_wallet)?; // 2

    let (transfer_authority, transfer_seed) = authority!(program_id);
    let _transfer_authority_info = next_expected_account(account_info_iter, &transfer_authority)?; // 3

    let buyer = next_account_info(account_info_iter)?; // 4
    let tokens_dest = next_account_info(account_info_iter)?; // 5

    next_expected_account(account_info_iter, &state.owner)?; // 6
    next_expected_account(account_info_iter, &state.treasury_addr)?; // 7

    next_expected_account(account_info_iter, &spl_token::ID)?; // 8
    next_expected_account(account_info_iter, &system_program::ID)?; // 9

    let clock = Clock::get()?;

    let split = state.calculate_buy_split(clock.unix_timestamp, amount, expected_price)?;

    invoke(
        &system_instruction::transfer(buyer.key, &state.owner, split.owner_split),
        accounts,
    )?;
    invoke(
        &system_instruction::transfer(buyer.key, &state.treasury_addr, split.treasury_split),
        accounts,
    )?;
    invoke(
        &system_instruction::transfer(buyer.key, state_acc.key, split.commission),
        accounts,
    )?;

    msg!("selling {} tokens", amount);

    let transfer = spl_token::instruction::transfer(
        &spl_token::ID,
        &derived_contract_wallet,
        tokens_dest.key,
        &transfer_authority,
        &[],
        amount,
    )?;
    invoke_signed(&transfer, accounts, &[transfer_seed])?;

    state.sold = state.sold.checked_add(amount).ok_or(Error::Overflow)?;

    Ok(())
}

#[allow(clippy::too_many_arguments)]
pub fn create_buy_instruction(
    program_id: &Pubkey,
    state: &Pubkey,
    token_mint: &Pubkey,

    buyer: &Pubkey,
    buyer_token_acc: &Pubkey,

    owner: &Pubkey,
    treasury: &Pubkey,

    amount: u64,
    expected_price: u64,
) -> Result<instruction::Instruction, ProgramError> {
    let (wallet_addr, _) = contract_wallet!(program_id, token_mint);
    let (transfer, _) = authority!(program_id);

    let accounts = vec![
        AccountMeta::new(state.to_owned(), false),
        AccountMeta::new(wallet_addr.to_owned(), false),
        AccountMeta::new_readonly(transfer.to_owned(), false),
        AccountMeta::new(buyer.to_owned(), true),
        AccountMeta::new(buyer_token_acc.to_owned(), false),
        AccountMeta::new(owner.to_owned(), false),
        AccountMeta::new(treasury.to_owned(), false),
        AccountMeta::new_readonly(spl_token::ID, false),
        AccountMeta::new_readonly(system_program::ID, false),
        AccountMeta::new_readonly(*program_id, false),
    ];

    Ok(instruction::Instruction {
        program_id: *program_id,
        accounts,
        data: Instruction::Buy(BuyInstruction {
            amount,
            expected_price,
        })
        .try_to_vec()?,
    })
}

// [writable] state
// [signer] current admin
fn process_set_admin(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    new_admin: Pubkey,
) -> Result<(), ProgramError> {
    let account_info_iter = &mut accounts.iter();

    let (mut state, _) = next_entity::<_, ContractState>(account_info_iter, program_id)?;
    let _admin = next_signer_account(account_info_iter, &state.admin)?;

    state.admin = new_admin;

    Ok(())
}

pub mod swap_program {
    use solana_program::declare_id;

    declare_id!("SWPHMNgqcgHbZEa36JNXNNgbUD15yYLWp5uJUJktbGN");
}

pub mod old_program {
    use solana_program::declare_id;

    declare_id!("Human1nfyFpJsPU3BBKqWPwD9FeaZgdPYzDVrBj32Xj");
}

pub mod new_program {
    use solana_program::declare_id;

    declare_id!("Human1nfyFpJsPU3BBKqWPwD9FeaZgdPYzDVrBj32Xj");
}

// [writable] state
// [write] vault
// [write, sign] any account
// [] contract transfer authority
//
// [] swap state
// [] swap authority
// [write] swap token account (a)
// [write] swap wsol account (b)
//
// [write] pool mint
// [write] owner lp token addr
// [write] comission wSOL acc
// [sign] funder
// [] token program
// [] swap program
// [] sysprog
fn process_deposit_commission(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
) -> Result<(), ProgramError> {
    let account_info_iter = &mut accounts.iter();
    let rent = Rent::get()?;

    let (state, state_acc) = next_entity::<_, ContractState>(account_info_iter, program_id)?; // 1

    let (vault, _) = contract_vault!(program_id, state.token);
    let vault_wallet = next_expected_token_wallet(account_info_iter, &vault)?; // 2

    // any empty account
    let stash = next_account_info(account_info_iter)?; // 3

    let (authority, authority_seeds) = authority!(program_id);
    next_expected_account(account_info_iter, &authority)?; // 4

    let swap_state_acc = next_expected_account(account_info_iter, &state.swap_state)?; // 5
    let swap_state =
        spl_token_swap::state::SwapVersion::unpack(&swap_state_acc.try_borrow_data()?)?;

    let (swap_auth, _) =
        Pubkey::find_program_address(&[state.swap_state.as_ref()], &swap_program::ID);

    next_expected_account(account_info_iter, &swap_auth)?; // 6

    let swap_wallet_a = next_expected_account(account_info_iter, swap_state.token_a_account())?; // 7
    let swap_wallet_b = next_expected_account(account_info_iter, swap_state.token_b_account())?; // 8

    let pool_token_mint = next_expected_account(account_info_iter, swap_state.pool_mint())?; // 9

    let (owner_lp_wallet, _) =
        next_atoken_wallet(account_info_iter, &state.owner, swap_state.pool_mint())?; // 10

    let token_acc_size = spl_token::state::Account::LEN;
    let wallet_rent = rent.minimum_balance(token_acc_size);
    let state_rent = rent.minimum_balance(STATE_ACC_SIZE);

    // calculate deposit amount
    let to_deposit_lp = state_acc
        .lamports()
        .checked_sub(state_rent)
        .ok_or(Error::Overflow)?;

    let to_fund_wsol_account = to_deposit_lp
        .checked_add(wallet_rent)
        .ok_or(Error::Overflow)?;

    let pool_mint = spl_token::state::Mint::unpack(&pool_token_mint.try_borrow_data()?)?;
    let swap_token_wallet = spl_token::state::Account::unpack(&swap_wallet_a.try_borrow_data()?)?;
    let swap_wsol_wallet = spl_token::state::Account::unpack(&swap_wallet_b.try_borrow_data()?)?;

    let pool_tokens =
        calculate_pool_tokens(to_deposit_lp, pool_mint.supply, swap_wsol_wallet.amount)?;

    let calculated_tokens = spl_token_swap::curve::constant_product::pool_tokens_to_trading_tokens(
        pool_tokens as u128,
        pool_mint.supply as u128,
        swap_token_wallet.amount as u128,
        swap_wsol_wallet.amount as u128,
        spl_token_swap::curve::calculator::RoundDirection::Floor,
    )
    .ok_or(Error::Overflow)?;

    if calculated_tokens.token_a_amount > vault_wallet.amount.into() {
        msg!("lp deposit: insufficient tokens in vault");
        return Ok(());
    }

    // create wSOL acc
    {
        let mut state_lamports = state_acc.try_borrow_mut_lamports()?;
        let mut stash_lamports = stash.try_borrow_mut_lamports()?;

        **state_lamports = state_lamports.checked_sub(to_fund_wsol_account).unwrap();
        **stash_lamports = stash_lamports.checked_add(to_fund_wsol_account).unwrap();

        drop(state_lamports);
        drop(stash_lamports);

        let mut allocate = system_instruction::allocate(stash.key, token_acc_size as u64);
        // avoids UnbalancedInstruction error. Ask Timofey
        allocate
            .accounts
            .push(AccountMeta::new_readonly(*state_acc.key, false));

        invoke(&allocate, accounts)?;

        let assign = system_instruction::assign(stash.key, &spl_token::ID);
        invoke(&assign, accounts)?;

        let initialize = initialize_account2(
            &spl_token::ID,
            stash.key,
            &spl_token::native_mint::ID,
            &authority,
        )?;
        invoke(&initialize, accounts)?;
    }

    let (swap_authority, _) =
        Pubkey::find_program_address(&[state.swap_state.as_ref()], &swap_program::ID);

    // deposit
    let deposit = swap_instruction::deposit_all_token_types(
        &swap_program::ID,
        &spl_token::ID,
        &state.swap_state,
        &swap_authority,
        &authority,
        &vault,
        stash.key,
        swap_wallet_a.key,
        swap_wallet_b.key,
        pool_token_mint.key,
        &owner_lp_wallet,
        swap_instruction::DepositAllTokenTypes {
            pool_token_amount: pool_tokens,
            maximum_token_a_amount: u64::MAX, // we leave it because there is no slippage on chain
            maximum_token_b_amount: u64::MAX,
        },
    )?;
    invoke_signed(&deposit, accounts, &[authority_seeds])?;

    // close temp acc
    let close = close_account(&spl_token::ID, stash.key, state_acc.key, &authority, &[])?;
    invoke_signed(&close, accounts, &[authority_seeds])?;

    Ok(())
}

fn calculate_pool_tokens(
    wsol_amount: u64,
    pool_token_supply: u64,
    swap_token_balance: u64,
) -> Result<u64, ProgramError> {
    let wsol_amount = PreciseNumber::new(wsol_amount as u128).unwrap();
    let pool_token_supply = PreciseNumber::new(pool_token_supply as u128).unwrap();
    let swap_token_balance = PreciseNumber::new(swap_token_balance as u128).unwrap();

    Ok(wsol_amount
        .checked_mul(&pool_token_supply)
        .ok_or(Error::Overflow)?
        .checked_div(&swap_token_balance)
        .ok_or(Error::Overflow)?
        .floor()
        .ok_or(Error::Overflow)?
        .to_imprecise()
        .ok_or(Error::Overflow)?
        .try_into()
        .map_err(|_| Error::Overflow)?)
}

fn process_register_post(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    args: RegisterPostInstruction,
) -> Result<(), ProgramError> {
    let account_info_iter = &mut accounts.iter();

    let (authority, authority_seeds) = authority!(program_id);

    let (state, state_acc) = next_entity::<_, ContractState>(account_info_iter, program_id)?; // 1

    // check priviliged account signed this data
    // next_signer_account(account_info_iter, &state.admin)?;
    let _admin = next_account_info(account_info_iter)?;

    let payer = next_account_info(account_info_iter)?;

    let post_info = next_account_info(account_info_iter)?;

    let (master_post_mint, master_post_seeds) = master_post_mint!(program_id, &args.post_id);

    let master_post_mint_acc = next_expected_account(account_info_iter, &master_post_mint)?;

    let master_post_wallet =
        spl_associated_token_account::get_associated_token_address(&authority, &master_post_mint);
    next_expected_account(account_info_iter, &master_post_wallet)?;

    let (master_post_metadata_pda, _) =
        mpl_token_metadata::pda::find_metadata_account(&master_post_mint);

    next_expected_account(account_info_iter, &master_post_metadata_pda)?;

    let (master_edition_pda, _) =
        mpl_token_metadata::pda::find_master_edition_account(&master_post_mint);
    next_expected_account(account_info_iter, &master_edition_pda)?;

    next_expected_account(account_info_iter, &authority)?;

    let (collection_mint, collection_seeds) = collection_mint!(program_id, &state.token);

    let collection_mint_acc = next_expected_account(account_info_iter, &collection_mint)?;

    let collection_wallet =
        spl_associated_token_account::get_associated_token_address(&authority, &collection_mint);

    next_expected_account(account_info_iter, &collection_wallet)?;

    let (collection_metadata_pda, _) =
        mpl_token_metadata::pda::find_metadata_account(&collection_mint);

    let collection_metadata_acc =
        next_expected_account(account_info_iter, &collection_metadata_pda)?;

    let (collection_edition_pda, _) =
        mpl_token_metadata::pda::find_master_edition_account(&collection_mint);
    next_expected_account(account_info_iter, &collection_edition_pda)?;

    if !master_post_mint_acc.data_is_empty() {
        msg!("master mint already registered");
        return Ok(());
    }

    let creators = vec![
        Creator {
            address: args.royalty_addr,
            share: 100, // receives 100% of royalties
            verified: false,
        },
        Creator {
            // honoroble mention
            address: state.owner,
            share: 0,
            verified: false,
        },
        Creator {
            // for some reason update authority is also required
            address: authority,
            share: 0,
            verified: true,
        },
    ];

    if collection_mint_acc.data_is_empty() {
        // initialize collection
        mint_nft(
            &collection_mint,
            &authority,
            &authority,
            payer.key,
            accounts,
            &[collection_seeds.as_ref(), authority_seeds.as_ref()],
        )?;

        // change to v3 when mainnet finally rolls out
        let create_collection_metadata =
            mpl_token_metadata::instruction::create_metadata_accounts_v2(
                mpl_token_metadata::ID,
                collection_metadata_pda,
                collection_mint,
                authority,
                *payer.key,
                authority,
                args.collection_name,
                args.symbol.clone(),
                args.collection_metadata_uri,
                Some(creators.clone()),
                POST_ROYALTY_COMMISSION_BSP,
                true,
                true,
                None, // not a member of collection, but a collection itself
                None,
            );
        invoke_signed(&create_collection_metadata, accounts, &[authority_seeds])?;

        // create master edititon
        let make_master = mpl_token_metadata::instruction::create_master_edition_v3(
            mpl_token_metadata::ID,
            collection_edition_pda,
            collection_mint,
            authority,
            authority,
            collection_metadata_pda,
            *payer.key,
            Some(0), // collection must be unique nft
        );
        invoke_signed(&make_master, accounts, &[authority_seeds])?;
    }

    mint_nft(
        &master_post_mint,
        &authority,
        &authority,
        payer.key,
        accounts,
        &[master_post_seeds.as_ref(), authority_seeds.as_ref()],
    )?;

    // create metadata
    let create_metadata = mpl_token_metadata::instruction::create_metadata_accounts_v2(
        mpl_token_metadata::ID,
        master_post_metadata_pda,
        master_post_mint,
        authority,
        *payer.key,
        authority,
        args.post_name,
        args.symbol,
        args.post_metadata_uri,
        Some(creators),
        POST_ROYALTY_COMMISSION_BSP,
        true, // sign with update authority
        true, // mutable
        None,
        None, // no uses for this nft, lol
    );
    invoke_signed(&create_metadata, accounts, &[authority_seeds])?;

    // set as already sold
    let update_secondary = mpl_token_metadata::instruction::update_metadata_accounts_v2(
        mpl_token_metadata::ID,
        master_post_metadata_pda,
        authority,
        None,
        None,
        Some(true),
        None,
    );
    invoke_signed(&update_secondary, accounts, &[authority_seeds])?;

    // create master edititon
    let create_master = mpl_token_metadata::instruction::create_master_edition_v3(
        mpl_token_metadata::ID,
        master_edition_pda,
        master_post_mint,
        authority,
        authority,
        master_post_metadata_pda,
        *payer.key,
        None, // no printing limit
    );
    invoke_signed(&create_master, accounts, &[authority_seeds])?;

    // owner is checked inside
    let collection_meta: mpl_token_metadata::state::Metadata =
        mpl_token_metadata::state::Metadata::from_account_info(collection_metadata_acc)?;

    let verify_collection_f =
        if let Some(CollectionDetails::V1 { .. }) = collection_meta.collection_details {
            // we have 1.3.3 sized collection
            mpl_token_metadata::instruction::set_and_verify_sized_collection_item
        } else {
            // they still have this on mainnet
            mpl_token_metadata::instruction::set_and_verify_collection
        };

    let verify_collection = verify_collection_f(
        mpl_token_metadata::ID,
        master_post_metadata_pda,
        authority,
        *payer.key,
        authority,
        collection_mint,
        collection_metadata_pda,
        collection_edition_pda,
        None,
    );
    invoke_signed(&verify_collection, accounts, &[authority_seeds])?;

    // record creation date
    save_post_info(
        program_id,
        payer.key,
        state_acc.key,
        args.post_id,
        args.created_at,
        args.repost_price,
        post_info,
        accounts,
    )?;

    Ok(())
}

fn save_post_info(
    program_id: &Pubkey,
    payer_addr: &Pubkey,
    state_acc: &Pubkey,
    post_id: [u8; 32],
    created_at: i64,
    repost_price: u64,
    post_info: &AccountInfo,
    accounts: &[AccountInfo],
) -> ProgramResult {
    let (derived_info_key, post_info_seeds) = post_info!(program_id, post_id);

    if *post_info.key != derived_info_key {
        return Err(ProgramError::InvalidArgument);
    }

    let info = PostInfo {
        state: *state_acc,
        post_id,
        created_at,
        repost_price: Some(repost_price),
    };

    let rent = Rent::get()?;
    let lamports = rent.minimum_balance(PostInfo::SIZE);
    let create = system_instruction::create_account(
        payer_addr,
        &derived_info_key,
        lamports,
        PostInfo::SIZE as u64,
        program_id,
    );
    invoke_signed(&create, accounts, &[post_info_seeds])?;

    initialize_entity(info, post_info)?;

    Ok(())
}

// mints zero decimals token with supply of 1 to ata of `to_wallet`
fn mint_nft(
    mint: &Pubkey,
    to_wallet: &Pubkey,
    authority: &Pubkey,
    payer: &Pubkey,
    accounts: &[AccountInfo],
    seeds: &[&[&[u8]]],
) -> Result<(), ProgramError> {
    let rent = Rent::get()?;
    let size = spl_token::state::Mint::LEN;

    let create_mint = system_instruction::create_account(
        payer,
        mint,
        rent.minimum_balance(size),
        size as u64,
        &spl_token::ID,
    );
    invoke_signed(&create_mint, accounts, seeds)?;

    let initialize_mint = spl_token::instruction::initialize_mint2(
        &spl_token::ID,
        mint,
        authority,
        Some(authority), // apparently metaplex needs set freeze authority now
        0,               // zero decimals since it's an nft
    )?;
    invoke_signed(&initialize_mint, accounts, seeds)?;

    let atoken_wallet = spl_associated_token_account::get_associated_token_address(to_wallet, mint);

    let create_atoken = spl_associated_token_account::instruction::create_associated_token_account(
        payer,
        to_wallet,
        mint,
        &spl_token::ID,
    );
    invoke(&create_atoken, accounts)?;

    let mint =
        spl_token::instruction::mint_to(&spl_token::ID, mint, &atoken_wallet, authority, &[], 1)?;

    invoke_signed(&mint, accounts, seeds)?;

    Ok(())
}

fn process_repost(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    _args: RepostInstruction,
) -> Result<(), ProgramError> {
    let account_info_iter = &mut accounts.iter();
    let (authority, authority_seeds) = authority!(program_id);

    let (state, state_acc) = next_entity::<_, ContractState>(account_info_iter, program_id)?;

    let master_mint = next_account_info(account_info_iter)?;
    let master_wallet = next_account_info(account_info_iter)?;
    let master_metadata = next_account_info(account_info_iter)?;
    let master_edition = next_account_info(account_info_iter)?;

    let (post_info, _post_info_acc) = next_entity::<_, PostInfo>(account_info_iter, program_id)?;

    let repost_mint = next_account_info(account_info_iter)?;
    let repost_mint_key = repost_mint.key;

    let repost_metadata = next_account_info(account_info_iter)?;
    let repost_edition = next_account_info(account_info_iter)?;
    let _repost_edition_mark = next_account_info(account_info_iter)?;

    let user = next_account_info(account_info_iter)?;

    let _user_nft_wallet = next_account_info(account_info_iter)?;

    let derived_user_wallet = get_associated_token_address(user.key, &state.token);
    let user_wallet = next_expected_account(account_info_iter, &derived_user_wallet)?;

    next_expected_account(account_info_iter, &state.owner)?;
    next_expected_account(account_info_iter, &state.treasury_addr)?;

    let repost_record = next_account_info(account_info_iter)?;

    let authority = next_expected_account(account_info_iter, &authority)?;

    let swap_state_acc = next_expected_account(account_info_iter, &state.swap_state)?;
    let swap_state =
        spl_token_swap::state::SwapVersion::unpack(&swap_state_acc.try_borrow_data()?)?;

    let swap_wallet_token =
        next_expected_token_wallet(account_info_iter, swap_state.token_a_account())?;
    let swap_wallet_wsol =
        next_expected_token_wallet(account_info_iter, swap_state.token_b_account())?;

    // check this is the same post info
    if post_info.state != *state_acc.key {
        msg!("post belongs to a different state");
        return Err(ProgramError::InvalidArgument);
    }

    let (derived_master_mint, _) = master_post_mint!(program_id, post_info.post_id);

    if *master_mint.key != derived_master_mint {
        msg!("post_info id does not match master mint supplied");
        return Err(ProgramError::InvalidArgument);
    }

    let clock = Clock::get()?;

    if !post_info.can_repost(clock.unix_timestamp) {
        msg!("repost window expired");
        return Error::RepostWindowExpired.into();
    }

    let mut repost_price = post_info
        .repost_price
        .unwrap_or(DEFAULT_REPORT_PRICE_LAMPORTS);

    if *user.key == state.owner {
        // almost free repost for owner
        repost_price = 0;
    }

    msg!("repost price: {}", repost_price);

    let split = ContractState::calculate_split_by_lamports(repost_price).ok_or(Error::Overflow)?;

    invoke(
        &system_instruction::transfer(user.key, &state.owner, split.owner_split),
        accounts,
    )?;
    invoke(
        &system_instruction::transfer(user.key, &state.treasury_addr, split.treasury_split),
        accounts,
    )?;
    invoke(
        &system_instruction::transfer(user.key, state_acc.key, split.commission),
        accounts,
    )?;

    // mint fresh repost nft
    mint_nft(
        repost_mint_key,
        user.key,
        authority.key,
        user.key,
        accounts,
        &[authority_seeds],
    )?;

    if *master_edition.owner != mpl_token_metadata::ID {
        return Err(ProgramError::IllegalOwner);
    }

    let (expected_edition, _) =
        mpl_token_metadata::pda::find_master_edition_account(master_mint.key);

    if expected_edition != *master_edition.key {
        return Err(ProgramError::InvalidArgument);
    }

    let edition_data: mpl_token_metadata::state::MasterEditionV2 =
        mpl_token_metadata::state::MasterEditionV2::from_account_info(master_edition)?;

    let edition = edition_data.supply.checked_add(1).ok_or(Error::Overflow)?;

    let copy_from_master =
        mpl_token_metadata::instruction::mint_new_edition_from_master_edition_via_token(
            mpl_token_metadata::ID,
            *repost_metadata.key,
            *repost_edition.key,
            *master_edition.key,
            *repost_mint_key,
            *authority.key,
            *user.key,
            *authority.key,
            *master_wallet.key,
            *authority.key,
            *master_metadata.key,
            *master_mint.key,
            edition,
        );

    invoke_signed(&copy_from_master, accounts, &[authority_seeds])?;

    // set as already sold
    let update_secondary = mpl_token_metadata::instruction::update_metadata_accounts_v2(
        mpl_token_metadata::ID,
        *repost_metadata.key,
        *authority.key,
        None,
        None,
        Some(true),
        None,
    );
    invoke_signed(&update_secondary, accounts, &[authority_seeds])?;

    // fetch swap price
    let amount = calculate_tokens_for_repost_fee(
        repost_price,
        swap_wallet_wsol.amount,
        swap_wallet_token.amount,
    )
    .ok_or(Error::Overflow)?
    .max(1);

    // record repost
    let repost = RepostRecord {
        state: *state_acc.key,
        token: state.token,
        user: *user.key,
        post_id: post_info.post_id,
        reposted_at: clock.unix_timestamp,
        receive_amount: amount,
    };

    save_repost_record(
        program_id,
        user.key,
        repost,
        repost_record,
        repost_mint_key,
        accounts,
    )?;

    if user_wallet.data_is_empty() {
        // also create user a atoken wallet for later distribution

        let create_atoken =
            spl_associated_token_account::instruction::create_associated_token_account(
                user.key,
                user.key,
                &state.token,
                &spl_token::ID,
            );
        invoke(&create_atoken, accounts)?;
    }

    msg!("will-receive {}", amount);

    Ok(())
}

fn calculate_tokens_for_repost_fee(
    amount_in: u64,
    wsol_amount: u64,
    chatlans_amount: u64,
) -> Option<u64> {
    // amountOut := (amountB * (amountA + amountIn) - constProd) / (amountA + amountIn)
    let amount_in = PreciseNumber::new(amount_in as u128)?;

    // multiply both sides of liqudity by some large number for precise calculation
    // (we are only interested in ratio)
    let coeff = PreciseNumber::new(1e9 as u128)?;

    let a_balance = PreciseNumber::new(wsol_amount as u128)?.checked_mul(&coeff)?;
    let b_balance = PreciseNumber::new(chatlans_amount as u128)?.checked_mul(&coeff)?;

    let const_prod = a_balance.checked_mul(&b_balance)?;

    let a = a_balance.checked_add(&amount_in)?;

    let y = b_balance.checked_mul(&a)?.checked_sub(&const_prod)?;

    let amount_out = y.checked_div(&a)?;

    u64::try_from(amount_out.to_imprecise()?).ok()
}

fn save_repost_record(
    program_id: &Pubkey,
    payer_addr: &Pubkey,
    record: RepostRecord,
    record_acc: &AccountInfo,
    repost_mint: &Pubkey,
    accounts: &[AccountInfo],
) -> ProgramResult {
    let (_, repost_record_seeds) = repost_record!(program_id, repost_mint);

    let rent = Rent::get()?;
    let lamports = rent.minimum_balance(RepostRecord::SIZE);
    let create = system_instruction::create_account(
        payer_addr,
        record_acc.key,
        lamports,
        RepostRecord::SIZE as u64,
        program_id,
    );
    invoke_signed(&create, accounts, &[repost_record_seeds])?;

    initialize_entity(record, record_acc)?;

    Ok(())
}

// claim RepostRecord
fn process_redeem_repost(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
) -> Result<(), ProgramError> {
    let account_info_iter = &mut accounts.iter();

    let (state, state_acc) = next_entity::<_, ContractState>(account_info_iter, program_id)?; // 1

    let (record, record_acc) = next_entity::<_, RepostRecord>(account_info_iter, program_id)?; // 2

    let (vault_addr, _) = contract_vault!(program_id, state.token);
    let _vault_wallet = next_expected_token_wallet(account_info_iter, &vault_addr)?; // 3

    let user = next_expected_account(account_info_iter, &record.user)?; // 4
    let (user_wallet_addr, _user_wallet) =
        next_atoken_wallet(account_info_iter, &record.user, &record.token)?; // 5

    let (authority, authority_seeds) = authority!(program_id);
    next_expected_account(account_info_iter, &authority)?; // 6

    if record.state != *state_acc.key {
        msg!("state != record.state");
        return Err(ProgramError::InvalidArgument);
    }

    let clock = Clock::get()?;

    let can_redeem = record.can_redeem(clock.unix_timestamp);
    msg!("can redeem: {}", can_redeem);

    // check if eligible
    if !can_redeem {
        msg!("cant-redeem-now");
        return Ok(());
    }

    let transfer = spl_token::instruction::transfer(
        &spl_token::ID,
        &vault_addr,
        &user_wallet_addr,
        &authority,
        &[],
        record.receive_amount,
    )?;

    invoke_signed(&transfer, accounts, &[authority_seeds])?;

    drop(record);

    // return lamports to the user
    let mut user_lamports = user.try_borrow_mut_lamports()?;

    erase_repost_record(record_acc, &mut user_lamports)?;

    Ok(())
}

fn erase_repost_record(acc: &AccountInfo, payer_lamports: &mut u64) -> Result<(), ProgramError> {
    // withdraw all lamports from state
    *payer_lamports = payer_lamports
        .checked_add(mem::take(*acc.try_borrow_mut_lamports()?))
        .ok_or(Error::Overflow)?;

    let mut data = acc.try_borrow_mut_data()?;
    let l = data.len();
    sol_memset(&mut data, 0, l);

    Ok(())
}

fn process_create_round(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    args: CreateRoundInstruction,
) -> Result<(), ProgramError> {
    let account_info_iter = &mut accounts.iter();

    let (mut state, state_acc) =
        next_entity::<_, ContractState>(account_info_iter, program_id).unwrap(); // 1

    let (vault_addr, _) = contract_vault!(program_id, state.token);
    let _vault_wallet = next_expected_token_wallet(account_info_iter, &vault_addr)?; // 2

    let (authority, authority_seeds) = authority!(program_id);
    next_expected_account(account_info_iter, &authority)?; // 3

    let fanout_acc = next_account_info(account_info_iter)?; // 4
    let payer = next_account_info(account_info_iter)?; // 5

    // passed as is

    let round = next_account_info(account_info_iter)?; // 6
    let offer_wallet = next_account_info(account_info_iter)?; // 7
    let offer_mint = next_account_info(account_info_iter)?; // 8

    let bid_wallet = next_account_info(account_info_iter)?; // 9
    let bid_mint = next_account_info(account_info_iter)?; // 10

    let round_authority = next_account_info(account_info_iter)?; // 11

    //

    let expected_members = vec![
        fanout::state::Member {
            address: state.treasury_addr, // treasury addr
            share: 9650,
        },
        fanout::state::Member {
            address: state.admin, // our fee
            share: 250,
        },
        fanout::state::Member {
            address: *state_acc.key, // LP
            share: 100,
        },
    ];

    if *fanout_acc.owner == fanout::ID {
        let fanout_data = fanout_acc.try_borrow_data()?;
        let fanout = fanout::state::Fanout::try_deserialize(&mut fanout_data.as_ref())?;

        if fanout.members != expected_members {
            msg!("fanout.members != expected_members");
            return Err(ProgramError::InvalidArgument);
        }
    } else {
        let rent = Rent::get()?;

        let size = 8 + 8 + 4 + (32 + 2) * expected_members.len();

        // system create
        let create_ix = system_instruction::create_account(
            payer.key,
            fanout_acc.key,
            rent.minimum_balance(size),
            size as u64,
            &fanout::ID,
        );

        invoke(&create_ix, accounts)?;

        // initalize fanout
        let data = fanout::instruction::Initialize {
            members: expected_members,
        }
        .data();

        let init_ix = solana_program::instruction::Instruction {
            program_id: fanout::ID,
            accounts: vec![AccountMeta::new(*fanout_acc.key, false)],
            data,
        };

        msg!("initializing fanout acc");
        invoke(&init_ix, accounts)?;
    }

    // amount is chosen by the user
    // todo: limits on how much one can offer
    let amount = args.offer_amount;

    // approve this amount to be tranfered from the vault
    let approve_ix = spl_token::instruction::approve(
        &spl_token::ID,
        &vault_addr,
        &authority,
        &authority,
        &[],
        amount,
    )?;
    invoke_signed(&approve_ix, accounts, &[authority_seeds])?;

    let data = round::instruction::CreateRound {
        params: round::CreateRoundParams {
            heir: state.owner,
            recipient: *fanout_acc.key,
            target_bid: args.target_bid,
            bidding_start: args.bidding_start,
            bidding_end: args.bidding_end,
        },
    }
    .data();

    let ix = solana_program::instruction::Instruction {
        program_id: round::ID,
        accounts: vec![
            AccountMeta::new(*round.key, true),
            AccountMeta::new(*offer_wallet.key, false),
            AccountMeta::new_readonly(*offer_mint.key, false),
            AccountMeta::new(vault_addr, false),
            AccountMeta::new_readonly(authority, true),
            AccountMeta::new(*bid_wallet.key, false),
            AccountMeta::new_readonly(*bid_mint.key, false),
            AccountMeta::new_readonly(*round_authority.key, false),
            AccountMeta::new(*payer.key, true),
            AccountMeta::new_readonly(spl_token::ID, false),
            AccountMeta::new_readonly(solana_program::system_program::ID, false),
        ],
        data,
    };
    invoke_signed(&ix, accounts, &[authority_seeds])?;

    state.current_round = Some(*round.key);

    Ok(())
}

fn process_claim_round_vesting(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
) -> Result<(), ProgramError> {
    let account_info_iter = &mut accounts.iter();

    let (mut state, _state_acc) = next_entity::<_, ContractState>(account_info_iter, program_id)?; // 1

    let (vault_addr, _) = contract_vault!(program_id, state.token);
    let vault_wallet = next_expected_token_wallet(account_info_iter, &vault_addr)?; // 2

    let (authority, authority_seeds) = authority!(program_id);
    next_expected_account(account_info_iter, &authority)?; // 3

    let round_acc = next_account_info(account_info_iter)?; // 4

    let (owner_wallet, _) = next_atoken_wallet(account_info_iter, &state.owner, &state.token)?; // 5

    // deserialize round
    let round_data = round_acc.try_borrow_data()?;
    let round = round::state::Round::try_deserialize(&mut round_data.as_ref())?;

    // check round is saved in state
    if state.current_round != Some(*round_acc.key) {
        msg!("state.current_round != round_acc.key");
        return Err(ProgramError::InvalidArgument);
    }

    // check round was accepted
    if round.status != round::state::RoundStatus::Accepted {
        msg!("round.status != RoundStatus::Accepted");
        return Err(ProgramError::InvalidArgument);
    }

    let amount = round
        .total_offer
        .expect("accepted round should always have total_offer set")
        .checked_div(10)
        .unwrap();

    // check
    let amount = amount.min(vault_wallet.amount);

    // tranfer 10% of round offer to owner
    let ix = spl_token::instruction::transfer(
        &spl_token::ID,
        &vault_addr,
        &owner_wallet,
        &authority,
        &[],
        amount,
    )?;

    invoke_signed(&ix, accounts, &[authority_seeds])?;

    state.current_round = None;
    state.completed_rounds_count = state.completed_rounds_count.checked_add(1).unwrap();

    Ok(())
}

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

    #[test]
    fn test_repost_fee() {
        let x = calculate_tokens_for_repost_fee(DEFAULT_REPORT_PRICE_LAMPORTS, 10000, 1).unwrap();
        assert_eq!(x, 1000);
        // ratio maintained
        let x = calculate_tokens_for_repost_fee(DEFAULT_REPORT_PRICE_LAMPORTS, 2000010000, 200001)
            .unwrap();
        assert_eq!(x, 1000);
    }
}