satrush-client 0.1.13

Rust client to interact with SatRush's on-chain program.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
//! Environment-free instruction builders.
//!
//! Thin composition helpers over the generated instruction structs: they derive
//! every PDA and associated token account from the program's fixed seeds, so a
//! caller only supplies the signing authority and the mint addresses. Shared by
//! the LiteSVM test-suite and the `satrush-cli` binary.

use crate::instructions::{
    CancelPublicAutomation, ClaimGrubstakeAirdrop, ClaimUsd, ClaimUsdInstructionArgs, CloseRound, CreateBoard,
    CreateEpochVault, CreateGrubstakeAirdrop, CreateGrubstakeAirdropInstructionArgs, CreateOneBtcVault,
    CreatePublicAutomation, CreatePublicAutomationInstructionArgs, CreateSatrushConfig,
    CreateSatrushConfigInstructionArgs, CreateSatsVault, CreateTreasury, DeployPublic, DeployPublicInstructionArgs,
    DepositGrubstake, DepositGrubstakeInstructionArgs, ExchangeAffiliatePoints, ExchangeAffiliatePointsInstructionArgs,
    ExecutePublicAutomation, ExecutePublicAutomationInstructionArgs, MigrateMiner, ReclaimGrubstakeAirdrop,
    ReclaimGrubstakeAutomation, ReclaimMinerGrubstake, RotateRound, SetAffiliateRate, SetAffiliateRateInstructionArgs,
    SetMinerTag, SetMinerTagInstructionArgs, SettleDeployPublic, SwapRoundStake, SwapRoundStakeInstructionArgs,
    TopUpPublicAutomation, TopUpPublicAutomationInstructionArgs, UpdateBoardRoundDuration,
    UpdateBoardRoundDurationInstructionArgs, UpdateDeployFees, UpdateDeployFeesInstructionArgs,
    UpdateDeploymentSettleGraceDuration, UpdateDeploymentSettleGraceDurationInstructionArgs,
    UpdateEpochVaultIterationDuration, UpdateEpochVaultIterationDurationInstructionArgs, UpdateMinDeployUsdAmount,
    UpdateMinDeployUsdAmountInstructionArgs, UpdateStrikeTriggerModulus, UpdateStrikeTriggerModulusInstructionArgs,
    UpdateUnclaimedHashrateBps, UpdateUnclaimedHashrateBpsInstructionArgs, WithdrawGrubstake,
    WithdrawGrubstakeInstructionArgs,
};
use crate::types::AutomationStrategy;
use crate::{
    get_affiliate_address, get_affiliate_tag_address, get_board_address, get_epoch_vault_address,
    get_epoch_vault_iteration_address, get_event_authority_address, get_miner_address, get_one_btc_vault_address,
    get_one_btc_vault_iteration_address, get_public_automation_address, get_public_deployment_address,
    get_round_address, get_satrush_config_address, get_sats_vault_address, get_treasury_address,
};
use solana_instruction::{AccountMeta, Instruction};
use solana_pubkey::Pubkey;

/// SPL Token program.
pub const TOKEN_PROGRAM_ID: Pubkey = Pubkey::from_str_const("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
/// SPL Associated Token Account program.
pub const ASSOCIATED_TOKEN_PROGRAM_ID: Pubkey = Pubkey::from_str_const("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");
/// System program.
pub const SYSTEM_PROGRAM_ID: Pubkey = Pubkey::from_str_const("11111111111111111111111111111111");
/// SlotHashes sysvar.
pub const SLOT_HASHES_ID: Pubkey = Pubkey::from_str_const("SysvarS1otHashes111111111111111111111111111");

/// Derive the canonical associated token account for `wallet` holding `mint`.
pub fn get_associated_token_address(wallet: &Pubkey, mint: &Pubkey) -> Pubkey {
    Pubkey::find_program_address(
        &[wallet.as_ref(), TOKEN_PROGRAM_ID.as_ref(), mint.as_ref()],
        &ASSOCIATED_TOKEN_PROGRAM_ID,
    )
    .0
}

/// `create_satrush_config`: the config PDA holding authorities, mints and fee
/// parameters. `authority` pays and must equal the program's upgrade authority.
pub fn get_create_satrush_config_instruction(
    authority: Pubkey,
    args: CreateSatrushConfigInstructionArgs,
) -> Instruction {
    CreateSatrushConfig {
        authority,
        satrush_config: get_satrush_config_address().0,
        system_program: SYSTEM_PROGRAM_ID,
    }
    .instruction(args)
}

/// `create_board`: the board singleton, its USD/BTC pools and the initial round
/// (id 1). Signed by the config's admin authority.
pub fn get_create_board_instruction(authority: Pubkey, usd_mint: Pubkey, btc_mint: Pubkey) -> Instruction {
    let board = get_board_address().0;
    CreateBoard {
        authority,
        satrush_config: get_satrush_config_address().0,
        board,
        initial_round: get_round_address(1).0,
        usd_mint,
        btc_mint,
        board_usd_ata: get_associated_token_address(&board, &usd_mint),
        board_btc_ata: get_associated_token_address(&board, &btc_mint),
        token_program: TOKEN_PROGRAM_ID,
        associated_token_program: ASSOCIATED_TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
    }
    .instruction()
}

/// `update_board_round_duration`: overwrite the board's `round_duration` (slots).
/// Applies to future round activations only; the active round keeps its window.
/// Signed by the config's admin authority.
pub fn get_update_board_round_duration_instruction(authority: Pubkey, new_round_duration: u32) -> Instruction {
    UpdateBoardRoundDuration {
        authority,
        satrush_config: get_satrush_config_address().0,
        board: get_board_address().0,
    }
    .instruction(UpdateBoardRoundDurationInstructionArgs { new_round_duration })
}

/// `update_min_deploy_usd_amount`: overwrite the config's minimum gross deploy
/// size (USD mint base units). Applies to every subsequent manual deploy,
/// automation creation and automation execution. Signed by the config's admin
/// authority.
pub fn get_update_min_deploy_usd_amount_instruction(authority: Pubkey, new_min_deploy_usd_amount: u64) -> Instruction {
    UpdateMinDeployUsdAmount {
        authority,
        satrush_config: get_satrush_config_address().0,
    }
    .instruction(UpdateMinDeployUsdAmountInstructionArgs {
        new_min_deploy_usd_amount,
    })
}

/// `update_unclaimed_hashrate_bps`: overwrite the config's deferred hashrate
/// bonus ratio (bps of each settled play's reward). Signed by the config's
/// admin authority.
pub fn get_update_unclaimed_hashrate_bps_instruction(
    authority: Pubkey,
    new_unclaimed_hashrate_bps: u32,
) -> Instruction {
    UpdateUnclaimedHashrateBps {
        authority,
        satrush_config: get_satrush_config_address().0,
    }
    .instruction(UpdateUnclaimedHashrateBpsInstructionArgs {
        new_unclaimed_hashrate_bps,
    })
}

/// `update_deploy_fees`: atomically overwrite the five deploy-time fee legs.
/// Each leg must be at least 1 bps and the legs must sum to exactly 600 bps
/// (6%); the split may vary but the total never changes. Signed by the
/// config's admin authority.
pub fn get_update_deploy_fees_instruction(
    authority: Pubkey,
    new_strike_fee_bps: u32,
    new_epoch_fee_bps: u32,
    new_one_btc_fee_bps: u32,
    new_protocol_fee_bps: u32,
    new_buybacks_fee_bps: u32,
) -> Instruction {
    UpdateDeployFees {
        authority,
        satrush_config: get_satrush_config_address().0,
    }
    .instruction(UpdateDeployFeesInstructionArgs {
        new_strike_fee_bps,
        new_epoch_fee_bps,
        new_one_btc_fee_bps,
        new_protocol_fee_bps,
        new_buybacks_fee_bps,
    })
}

/// `update_epoch_vault_iteration_duration`: overwrite the config's epoch vault
/// iteration length (slots). Applies to the currently accumulating iteration
/// immediately. Signed by the config's admin authority.
pub fn get_update_epoch_vault_iteration_duration_instruction(
    authority: Pubkey,
    new_iteration_duration: u64,
) -> Instruction {
    UpdateEpochVaultIterationDuration {
        authority,
        satrush_config: get_satrush_config_address().0,
    }
    .instruction(UpdateEpochVaultIterationDurationInstructionArgs { new_iteration_duration })
}

/// `update_strike_trigger_modulus`: admin retunes the Sat Strike odds (the
/// jackpot fires when `rng % modulus == 0`). Signed by the config's admin
/// authority.
pub fn get_update_strike_trigger_modulus_instruction(authority: Pubkey, new_modulus: u16) -> Instruction {
    UpdateStrikeTriggerModulus {
        authority,
        satrush_config: get_satrush_config_address().0,
    }
    .instruction(UpdateStrikeTriggerModulusInstructionArgs { new_modulus })
}

/// `update_deployment_settle_grace_duration`: admin retunes the settle grace
/// window (slots after a round settles before stale deployments may be
/// force-cleaned; 0 disables cleanup).
pub fn get_update_deployment_settle_grace_duration_instruction(
    authority: Pubkey,
    new_grace_duration: u64,
) -> Instruction {
    UpdateDeploymentSettleGraceDuration {
        authority,
        satrush_config: get_satrush_config_address().0,
    }
    .instruction(UpdateDeploymentSettleGraceDurationInstructionArgs { new_grace_duration })
}

/// `create_epoch_vault`: the epoch vault singleton, its USD/BTC pools and the
/// first iteration (id 1).
pub fn get_create_epoch_vault_instruction(authority: Pubkey, usd_mint: Pubkey, btc_mint: Pubkey) -> Instruction {
    let epoch_vault = get_epoch_vault_address().0;
    CreateEpochVault {
        authority,
        satrush_config: get_satrush_config_address().0,
        epoch_vault,
        epoch_vault_iteration: get_epoch_vault_iteration_address(1).0,
        usd_mint,
        btc_mint,
        epoch_vault_usd_ata: get_associated_token_address(&epoch_vault, &usd_mint),
        epoch_vault_btc_ata: get_associated_token_address(&epoch_vault, &btc_mint),
        token_program: TOKEN_PROGRAM_ID,
        associated_token_program: ASSOCIATED_TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
    }
    .instruction()
}

/// `create_one_btc_vault`: the 1 BTC vault singleton, its USD/BTC pools and the
/// first iteration (id 1).
pub fn get_create_one_btc_vault_instruction(authority: Pubkey, usd_mint: Pubkey, btc_mint: Pubkey) -> Instruction {
    let one_btc_vault = get_one_btc_vault_address().0;
    CreateOneBtcVault {
        authority,
        satrush_config: get_satrush_config_address().0,
        one_btc_vault,
        one_btc_vault_iteration: get_one_btc_vault_iteration_address(1).0,
        usd_mint,
        btc_mint,
        one_btc_vault_usd_ata: get_associated_token_address(&one_btc_vault, &usd_mint),
        one_btc_vault_btc_ata: get_associated_token_address(&one_btc_vault, &btc_mint),
        token_program: TOKEN_PROGRAM_ID,
        associated_token_program: ASSOCIATED_TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
    }
    .instruction()
}

/// `create_treasury`: the treasury singleton and its USD fee pool.
pub fn get_create_treasury_instruction(authority: Pubkey, usd_mint: Pubkey) -> Instruction {
    let treasury = get_treasury_address().0;
    CreateTreasury {
        authority,
        satrush_config: get_satrush_config_address().0,
        treasury,
        usd_mint,
        treasury_usd_ata: get_associated_token_address(&treasury, &usd_mint),
        token_program: TOKEN_PROGRAM_ID,
        associated_token_program: ASSOCIATED_TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
    }
    .instruction()
}

/// `deploy_public`: stake `amount` USD (base units; all fees are deducted from
/// it, so the miner parts with exactly `amount`) on the tiles
/// in `selection_mask` for round `round_id`, as the miner `authority`. The round
/// must be the board's current one and open for deploys; the miner profile and
/// deployment record PDAs are created by the instruction.
pub fn get_deploy_public_instruction(
    authority: Pubkey,
    usd_mint: Pubkey,
    round_id: u32,
    selection_mask: u32,
    amount: u64,
) -> Instruction {
    let funding_usd_ata = get_associated_token_address(&authority, &usd_mint);
    build_deploy_public_instruction(authority, usd_mint, round_id, selection_mask, amount, funding_usd_ata, false, None)
}

/// `deploy_public` carrying the affiliate account of `affiliate_authority`:
/// binds the miner when this deploy creates it, and accrues the affiliate's
/// rate share of the deploy's protocol fee leg
/// (`protocol_fee × rate_bps / 10_000`) as points.
pub fn get_deploy_public_with_affiliate_instruction(
    authority: Pubkey,
    usd_mint: Pubkey,
    round_id: u32,
    selection_mask: u32,
    amount: u64,
    affiliate_authority: Pubkey,
) -> Instruction {
    let funding_usd_ata = get_associated_token_address(&authority, &usd_mint);
    build_deploy_public_instruction(
        authority,
        usd_mint,
        round_id,
        selection_mask,
        amount,
        funding_usd_ata,
        false,
        Some(get_affiliate_address(affiliate_authority).0),
    )
}

/// `deploy_public` funded from the miner's grubstake balance: the stake is
/// pulled from the miner PDA's USD ATA and no hashrate is earned; settled USD
/// winnings return to the grubstake.
pub fn get_deploy_public_grubstake_instruction(
    authority: Pubkey,
    usd_mint: Pubkey,
    round_id: u32,
    selection_mask: u32,
    amount: u64,
) -> Instruction {
    let miner = get_miner_address(authority).0;
    let funding_usd_ata = get_associated_token_address(&miner, &usd_mint);
    build_deploy_public_instruction(authority, usd_mint, round_id, selection_mask, amount, funding_usd_ata, true, None)
}

/// Grubstake-funded `deploy_public` carrying the affiliate account of
/// `affiliate_authority`. The affiliate must match the miner's bound tag;
/// bonus-funded deploys accrue no points.
pub fn get_deploy_public_grubstake_with_affiliate_instruction(
    authority: Pubkey,
    usd_mint: Pubkey,
    round_id: u32,
    selection_mask: u32,
    amount: u64,
    affiliate_authority: Pubkey,
) -> Instruction {
    let miner = get_miner_address(authority).0;
    let funding_usd_ata = get_associated_token_address(&miner, &usd_mint);
    build_deploy_public_instruction(
        authority,
        usd_mint,
        round_id,
        selection_mask,
        amount,
        funding_usd_ata,
        true,
        Some(get_affiliate_address(affiliate_authority).0),
    )
}

#[allow(clippy::too_many_arguments)]
fn build_deploy_public_instruction(
    authority: Pubkey,
    usd_mint: Pubkey,
    round_id: u32,
    selection_mask: u32,
    amount: u64,
    funding_usd_ata: Pubkey,
    is_grubstake_funded: bool,
    affiliate: Option<Pubkey>,
) -> Instruction {
    let board = get_board_address().0;

    DeployPublic {
        authority,
        satrush_config: get_satrush_config_address().0,
        board,
        usd_mint,
        board_usd_ata: get_associated_token_address(&board, &usd_mint),
        authority_usd_ata: funding_usd_ata,
        round: get_round_address(round_id).0,
        public_deployment: get_public_deployment_address(authority, round_id).0,
        miner: get_miner_address(authority).0,
        affiliate,
        token_program: TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
        event_authority: get_event_authority_address().0,
        program: crate::SATRUSH_ID,
    }
    .instruction_with_remaining_accounts(
        DeployPublicInstructionArgs {
            selection_mask,
            amount,
            is_grubstake_funded,
        },
        // Always carried: when this deploy is the round's first entry it arms
        // the round rotor via CPI, and the caller cannot know in advance.
        &crate::rng::get_rng_remaining_accounts(),
    )
}

/// `rotate_round`: reveal `current_round_id`'s winning tile, sweep the round's
/// accumulated fee legs from the board pool to the epoch/1 BTC/treasury pools
/// (plus, on a strike trigger, the strike skim's USD and BTC legs to the epoch
/// vault), and deploy round `current_round_id + 1` as the board's new active
/// round. Signed by the config's round authority; valid once the round's
/// window elapsed.
pub fn get_rotate_round_instruction(
    authority: Pubkey,
    usd_mint: Pubkey,
    btc_mint: Pubkey,
    current_round_id: u32,
) -> Instruction {
    let board = get_board_address().0;
    let epoch_vault = get_epoch_vault_address().0;
    let one_btc_vault = get_one_btc_vault_address().0;
    let treasury = get_treasury_address().0;

    RotateRound {
        authority,
        satrush_config: get_satrush_config_address().0,
        board,
        current_round: get_round_address(current_round_id).0,
        next_round: get_round_address(current_round_id + 1).0,
        usd_mint,
        btc_mint,
        board_usd_ata: get_associated_token_address(&board, &usd_mint),
        board_btc_ata: get_associated_token_address(&board, &btc_mint),
        epoch_vault,
        epoch_vault_usd_ata: get_associated_token_address(&epoch_vault, &usd_mint),
        epoch_vault_btc_ata: get_associated_token_address(&epoch_vault, &btc_mint),
        one_btc_vault,
        one_btc_vault_usd_ata: get_associated_token_address(&one_btc_vault, &usd_mint),
        treasury,
        treasury_usd_ata: get_associated_token_address(&treasury, &usd_mint),
        round_rotor: crate::rng::get_rotor_address(crate::rng::ROUND_ROTOR_TAG).0,
        token_program: TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
        event_authority: get_event_authority_address().0,
        program: crate::SATRUSH_ID,
    }
    .instruction()
}

/// `swap_round_stake`: relay a pre-built aggregator route that converts part of
/// the revealed round's USD into BTC. `swap_data` and `route_accounts` are the
/// route's opaque instruction data and account list; the on-chain handler
/// enforces the economics against observed balance deltas. Signed by the
/// config's round authority.
#[allow(clippy::too_many_arguments)]
pub fn get_swap_round_stake_instruction(
    authority: Pubkey,
    usd_mint: Pubkey,
    btc_mint: Pubkey,
    round_id: u32,
    min_btc_out: u64,
    swap_program: Pubkey,
    swap_data: Vec<u8>,
    route_accounts: &[AccountMeta],
) -> Instruction {
    let board = get_board_address().0;
    SwapRoundStake {
        authority,
        satrush_config: get_satrush_config_address().0,
        board,
        round: get_round_address(round_id).0,
        usd_mint,
        btc_mint,
        board_usd_ata: get_associated_token_address(&board, &usd_mint),
        board_btc_ata: get_associated_token_address(&board, &btc_mint),
        swap_program,
        token_program: TOKEN_PROGRAM_ID,
        event_authority: get_event_authority_address().0,
        program: crate::SATRUSH_ID,
    }
    .instruction_with_remaining_accounts(SwapRoundStakeInstructionArgs { min_btc_out, swap_data }, route_accounts)
}

/// `settle_deploy_public`: settle `deployment_authority`'s deployment in a
/// Settled round. `authority` signs (the owner, or the round authority for
/// automated deployments); `rent_recipient` must be the round authority for
/// automated deployments and the owner for manual ones.
pub fn get_settle_deploy_public_instruction(
    authority: Pubkey,
    deployment_authority: Pubkey,
    rent_recipient: Pubkey,
    usd_mint: Pubkey,
    btc_mint: Pubkey,
    round_id: u32,
) -> Instruction {
    let board = get_board_address().0;
    let sats_vault = get_sats_vault_address().0;
    let public_automation = get_public_automation_address(deployment_authority).0;
    let miner = get_miner_address(deployment_authority).0;
    SettleDeployPublic {
        authority,
        rent_recipient,
        satrush_config: get_satrush_config_address().0,
        round: get_round_address(round_id).0,
        board,
        public_deployment: get_public_deployment_address(deployment_authority, round_id).0,
        miner,
        public_automation,
        automation_usd_ata: get_associated_token_address(&public_automation, &usd_mint),
        miner_usd_ata: get_associated_token_address(&miner, &usd_mint),
        board_usd_ata: get_associated_token_address(&board, &usd_mint),
        sats_vault,
        btc_mint,
        usd_mint,
        board_btc_ata: get_associated_token_address(&board, &btc_mint),
        sats_vault_btc_ata: get_associated_token_address(&sats_vault, &btc_mint),
        token_program: TOKEN_PROGRAM_ID,
        associated_token_program: ASSOCIATED_TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
        event_authority: get_event_authority_address().0,
        program: crate::SATRUSH_ID,
    }
    .instruction()
}

/// `create_public_automation`: escrow `deposit_usd_amount` and configure the
/// crank to deploy `per_round_usd_amount` per round with the given strategy.
/// One automation per authority.
#[allow(clippy::too_many_arguments)]
pub fn get_create_public_automation_instruction(
    authority: Pubkey,
    usd_mint: Pubkey,
    strategy: AutomationStrategy,
    selection_mask: u32,
    per_round_usd_amount: u64,
    reload: bool,
    deposit_usd_amount: u64,
) -> Instruction {
    let funding_usd_ata = get_associated_token_address(&authority, &usd_mint);
    build_create_public_automation_instruction(
        authority,
        usd_mint,
        strategy,
        selection_mask,
        per_round_usd_amount,
        reload,
        deposit_usd_amount,
        funding_usd_ata,
        false,
        None,
    )
}

/// `create_public_automation` carrying the affiliate account of
/// `affiliate_authority`: binds the miner when this creation initializes it.
/// The deposit itself accrues no points — volume accrues at execution.
#[allow(clippy::too_many_arguments)]
pub fn get_create_public_automation_with_affiliate_instruction(
    authority: Pubkey,
    usd_mint: Pubkey,
    strategy: AutomationStrategy,
    selection_mask: u32,
    per_round_usd_amount: u64,
    reload: bool,
    deposit_usd_amount: u64,
    affiliate_authority: Pubkey,
) -> Instruction {
    let funding_usd_ata = get_associated_token_address(&authority, &usd_mint);
    build_create_public_automation_instruction(
        authority,
        usd_mint,
        strategy,
        selection_mask,
        per_round_usd_amount,
        reload,
        deposit_usd_amount,
        funding_usd_ata,
        false,
        Some(get_affiliate_address(affiliate_authority).0),
    )
}

/// `create_public_automation` funded from the miner's grubstake balance: the
/// deposit is pulled from the miner PDA's USD ATA, and every deployment the
/// automation creates plays as grubstake-funded.
#[allow(clippy::too_many_arguments)]
pub fn get_create_public_automation_grubstake_instruction(
    authority: Pubkey,
    usd_mint: Pubkey,
    strategy: AutomationStrategy,
    selection_mask: u32,
    per_round_usd_amount: u64,
    reload: bool,
    deposit_usd_amount: u64,
) -> Instruction {
    let miner = get_miner_address(authority).0;
    let funding_usd_ata = get_associated_token_address(&miner, &usd_mint);
    build_create_public_automation_instruction(
        authority,
        usd_mint,
        strategy,
        selection_mask,
        per_round_usd_amount,
        reload,
        deposit_usd_amount,
        funding_usd_ata,
        true,
        None,
    )
}

#[allow(clippy::too_many_arguments)]
fn build_create_public_automation_instruction(
    authority: Pubkey,
    usd_mint: Pubkey,
    strategy: AutomationStrategy,
    selection_mask: u32,
    per_round_usd_amount: u64,
    reload: bool,
    deposit_usd_amount: u64,
    funding_usd_ata: Pubkey,
    is_grubstake_funded: bool,
    affiliate: Option<Pubkey>,
) -> Instruction {
    let public_automation = get_public_automation_address(authority).0;
    CreatePublicAutomation {
        authority,
        satrush_config: get_satrush_config_address().0,
        public_automation,
        usd_mint,
        authority_usd_ata: funding_usd_ata,
        automation_usd_ata: get_associated_token_address(&public_automation, &usd_mint),
        miner: get_miner_address(authority).0,
        affiliate,
        token_program: TOKEN_PROGRAM_ID,
        associated_token_program: ASSOCIATED_TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
    }
    .instruction(CreatePublicAutomationInstructionArgs {
        strategy,
        selection_mask,
        per_round_usd_amount,
        reload,
        deposit_usd_amount,
        is_grubstake_funded,
    })
}

/// `top_up_public_automation`: move `amount` USD from the authority's account
/// into the automation's escrow. For grubstake automations use
/// `get_top_up_public_automation_grubstake_instruction` — the program only
/// accepts the matching funding source.
pub fn get_top_up_public_automation_instruction(authority: Pubkey, usd_mint: Pubkey, amount: u64) -> Instruction {
    let funding_usd_ata = get_associated_token_address(&authority, &usd_mint);
    build_top_up_public_automation_instruction(authority, usd_mint, amount, funding_usd_ata)
}

/// `top_up_public_automation` for a grubstake automation: `amount` moves from
/// the miner PDA's USD ATA (debiting the grubstake balance) into the escrow.
pub fn get_top_up_public_automation_grubstake_instruction(
    authority: Pubkey,
    usd_mint: Pubkey,
    amount: u64,
) -> Instruction {
    let miner = get_miner_address(authority).0;
    let funding_usd_ata = get_associated_token_address(&miner, &usd_mint);
    build_top_up_public_automation_instruction(authority, usd_mint, amount, funding_usd_ata)
}

fn build_top_up_public_automation_instruction(
    authority: Pubkey,
    usd_mint: Pubkey,
    amount: u64,
    funding_usd_ata: Pubkey,
) -> Instruction {
    let public_automation = get_public_automation_address(authority).0;
    TopUpPublicAutomation {
        authority,
        satrush_config: get_satrush_config_address().0,
        public_automation,
        miner: get_miner_address(authority).0,
        usd_mint,
        authority_usd_ata: funding_usd_ata,
        automation_usd_ata: get_associated_token_address(&public_automation, &usd_mint),
        token_program: TOKEN_PROGRAM_ID,
    }
    .instruction(TopUpPublicAutomationInstructionArgs { amount })
}

/// `cancel_public_automation`: refund the full escrow balance and close the
/// automation and its token account. Unconditional; in-flight deployments
/// settle to the miner profile later. Grubstake escrows refund into the
/// miner's grubstake instead of the wallet.
pub fn get_cancel_public_automation_instruction(authority: Pubkey, usd_mint: Pubkey) -> Instruction {
    let public_automation = get_public_automation_address(authority).0;
    let miner = get_miner_address(authority).0;
    CancelPublicAutomation {
        authority,
        satrush_config: get_satrush_config_address().0,
        public_automation,
        miner,
        usd_mint,
        automation_usd_ata: get_associated_token_address(&public_automation, &usd_mint),
        authority_usd_ata: get_associated_token_address(&authority, &usd_mint),
        miner_usd_ata: get_associated_token_address(&miner, &usd_mint),
        token_program: TOKEN_PROGRAM_ID,
        associated_token_program: ASSOCIATED_TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
    }
    .instruction()
}

/// `execute_public_automation`: crank-signed per-round deploy funded from
/// `automation_authority`'s escrow. `selection_mask` must be `Some` for
/// Discretionary automations and `None` otherwise.
pub fn get_execute_public_automation_instruction(
    crank_authority: Pubkey,
    automation_authority: Pubkey,
    usd_mint: Pubkey,
    round_id: u32,
    selection_mask: Option<u32>,
) -> Instruction {
    let board = get_board_address().0;
    let public_automation = get_public_automation_address(automation_authority).0;

    ExecutePublicAutomation {
        authority: crank_authority,
        satrush_config: get_satrush_config_address().0,
        board,
        round: get_round_address(round_id).0,
        public_automation,
        usd_mint,
        automation_usd_ata: get_associated_token_address(&public_automation, &usd_mint),
        board_usd_ata: get_associated_token_address(&board, &usd_mint),
        public_deployment: get_public_deployment_address(automation_authority, round_id).0,
        miner: get_miner_address(automation_authority).0,
        affiliate: None,
        slot_hashes: SLOT_HASHES_ID,
        token_program: TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
        event_authority: get_event_authority_address().0,
        program: crate::SATRUSH_ID,
    }
    .instruction_with_remaining_accounts(
        ExecutePublicAutomationInstructionArgs { selection_mask },
        // Same first-entry rotor arming as the manual deploy builders.
        &crate::rng::get_rng_remaining_accounts(),
    )
}

/// `execute_public_automation` carrying the affiliate account of
/// `affiliate_authority`, so a bound miner's wallet-funded automation deploy
/// accrues points.
pub fn get_execute_public_automation_with_affiliate_instruction(
    crank_authority: Pubkey,
    automation_authority: Pubkey,
    usd_mint: Pubkey,
    round_id: u32,
    selection_mask: Option<u32>,
    affiliate_authority: Pubkey,
) -> Instruction {
    let board = get_board_address().0;
    let public_automation = get_public_automation_address(automation_authority).0;

    ExecutePublicAutomation {
        authority: crank_authority,
        satrush_config: get_satrush_config_address().0,
        board,
        round: get_round_address(round_id).0,
        public_automation,
        usd_mint,
        automation_usd_ata: get_associated_token_address(&public_automation, &usd_mint),
        board_usd_ata: get_associated_token_address(&board, &usd_mint),
        public_deployment: get_public_deployment_address(automation_authority, round_id).0,
        miner: get_miner_address(automation_authority).0,
        affiliate: Some(get_affiliate_address(affiliate_authority).0),
        slot_hashes: SLOT_HASHES_ID,
        token_program: TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
        event_authority: get_event_authority_address().0,
        program: crate::SATRUSH_ID,
    }
    .instruction_with_remaining_accounts(
        ExecutePublicAutomationInstructionArgs { selection_mask },
        &crate::rng::get_rng_remaining_accounts(),
    )
}

/// `claim_usd`: withdraw `amount` of the miner `authority`'s unclaimed USD
/// winnings from the board's USD pool to the authority's USD account. No exit
/// fee — the full amount transfers.
pub fn get_claim_usd_instruction(authority: Pubkey, usd_mint: Pubkey, amount: u64) -> Instruction {
    let board = get_board_address().0;
    ClaimUsd {
        authority,
        satrush_config: get_satrush_config_address().0,
        board,
        miner: get_miner_address(authority).0,
        usd_mint,
        board_usd_ata: get_associated_token_address(&board, &usd_mint),
        authority_usd_ata: get_associated_token_address(&authority, &usd_mint),
        token_program: TOKEN_PROGRAM_ID,
        associated_token_program: ASSOCIATED_TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
    }
    .instruction(ClaimUsdInstructionArgs { amount })
}

/// `migrate_miner`: extend a 115-byte v1 miner account to the v2 layout
/// (`affiliate` Pubkey + reserved tail, version stamped to 2). Signed by the
/// config's admin authority, who also funds the rent top-up.
pub fn get_migrate_miner_instruction(authority: Pubkey, miner: Pubkey) -> Instruction {
    MigrateMiner {
        authority,
        satrush_config: get_satrush_config_address().0,
        miner,
        system_program: SYSTEM_PROGRAM_ID,
    }
    .instruction()
}

/// `create_sats_vault`: the sats vault singleton and its BTC reserve pool.
pub fn get_create_sats_vault_instruction(authority: Pubkey, btc_mint: Pubkey) -> Instruction {
    let sats_vault = get_sats_vault_address().0;
    CreateSatsVault {
        authority,
        satrush_config: get_satrush_config_address().0,
        sats_vault,
        btc_mint,
        sats_vault_btc_ata: get_associated_token_address(&sats_vault, &btc_mint),
        token_program: TOKEN_PROGRAM_ID,
        associated_token_program: ASSOCIATED_TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
    }
    .instruction()
}

/// `close_round`: tear down a Finished round, sweeping a no-winner round's
/// orphaned pot (USD and BTC) into the treasury. Signed by the config's admin
/// authority, which receives the round account's rent.
pub fn get_close_round_instruction(
    authority: Pubkey,
    usd_mint: Pubkey,
    btc_mint: Pubkey,
    round_id: u32,
) -> Instruction {
    let board = get_board_address().0;
    let treasury = get_treasury_address().0;
    CloseRound {
        authority,
        satrush_config: get_satrush_config_address().0,
        board,
        round: get_round_address(round_id).0,
        treasury,
        usd_mint,
        btc_mint,
        board_usd_ata: get_associated_token_address(&board, &usd_mint),
        board_btc_ata: get_associated_token_address(&board, &btc_mint),
        treasury_usd_ata: get_associated_token_address(&treasury, &usd_mint),
        treasury_btc_ata: get_associated_token_address(&treasury, &btc_mint),
        token_program: TOKEN_PROGRAM_ID,
        associated_token_program: ASSOCIATED_TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
        event_authority: get_event_authority_address().0,
        program: crate::SATRUSH_ID,
    }
    .instruction()
}

/// `set_miner_tag`: claim `tag` for `authority`, creating the wallet's
/// affiliate identity automatically. The affiliate PDA is seeded by the
/// authority, so a wallet can only ever register once; the tag registry PDA
/// is seeded by the tag, so a taken tag fails at creation.
pub fn get_set_miner_tag_instruction(authority: Pubkey, tag: &str) -> Instruction {
    SetMinerTag {
        authority,
        affiliate: get_affiliate_address(authority).0,
        affiliate_tag: get_affiliate_tag_address(tag).0,
        system_program: SYSTEM_PROGRAM_ID,
    }
    .instruction(SetMinerTagInstructionArgs { tag: tag.to_string() })
}

/// `exchange_affiliate_points`: convert `points_amount` of the affiliate's
/// spendable points into a grubstake credit on the affiliate's own miner.
/// Points are USD base units valued at accrual, so the exchange is 1:1.
pub fn get_exchange_affiliate_points_instruction(
    authority: Pubkey,
    usd_mint: Pubkey,
    points_amount: u64,
) -> Instruction {
    let miner = get_miner_address(authority).0;
    let treasury = get_treasury_address().0;
    ExchangeAffiliatePoints {
        authority,
        satrush_config: get_satrush_config_address().0,
        affiliate: get_affiliate_address(authority).0,
        miner,
        treasury,
        usd_mint,
        treasury_usd_ata: get_associated_token_address(&treasury, &usd_mint),
        miner_usd_ata: get_associated_token_address(&miner, &usd_mint),
        token_program: TOKEN_PROGRAM_ID,
        associated_token_program: ASSOCIATED_TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
    }
    .instruction(ExchangeAffiliatePointsInstructionArgs { points_amount })
}

/// `set_affiliate_rate`: set the affiliate's share of the protocol fee leg
/// (bps, admin only). Shapes future accruals; earned points keep their value.
pub fn get_set_affiliate_rate_instruction(
    authority: Pubkey,
    affiliate_authority: Pubkey,
    rate_bps: u16,
) -> Instruction {
    SetAffiliateRate {
        authority,
        satrush_config: get_satrush_config_address().0,
        affiliate: get_affiliate_address(affiliate_authority).0,
    }
    .instruction(SetAffiliateRateInstructionArgs { rate_bps })
}

/// `deposit_grubstake`: fund the treasury's grubstake pool with `usd_amount`
/// from `authority`'s own USD account. Admin authority or fee recipient.
pub fn get_deposit_grubstake_instruction(authority: Pubkey, usd_mint: Pubkey, usd_amount: u64) -> Instruction {
    let treasury = get_treasury_address().0;
    DepositGrubstake {
        authority,
        satrush_config: get_satrush_config_address().0,
        treasury,
        usd_mint,
        authority_usd_ata: get_associated_token_address(&authority, &usd_mint),
        treasury_usd_ata: get_associated_token_address(&treasury, &usd_mint),
        token_program: TOKEN_PROGRAM_ID,
    }
    .instruction(DepositGrubstakeInstructionArgs { usd_amount })
}

/// `withdraw_grubstake`: pull `usd_amount` of unreserved grubstake back out to
/// `fee_recipient`. Only the portion not promised to issued airdrops may leave.
pub fn get_withdraw_grubstake_instruction(
    authority: Pubkey,
    fee_recipient: Pubkey,
    usd_mint: Pubkey,
    usd_amount: u64,
) -> Instruction {
    let treasury = get_treasury_address().0;
    WithdrawGrubstake {
        authority,
        satrush_config: get_satrush_config_address().0,
        treasury,
        usd_mint,
        treasury_usd_ata: get_associated_token_address(&treasury, &usd_mint),
        fee_recipient,
        fee_recipient_usd_ata: get_associated_token_address(&fee_recipient, &usd_mint),
        token_program: TOKEN_PROGRAM_ID,
        associated_token_program: ASSOCIATED_TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
    }
    .instruction(WithdrawGrubstakeInstructionArgs { usd_amount })
}

/// `create_grubstake_airdrop`: reserve `usd_amount` of the pool for
/// `airdrop_authority` to claim before `expiration_timestamp`. `airdrop` is a
/// fresh keypair's pubkey and must also sign the transaction. Fee recipient
/// only.
pub fn get_create_grubstake_airdrop_instruction(
    authority: Pubkey,
    airdrop: Pubkey,
    airdrop_authority: Pubkey,
    usd_amount: u64,
    expiration_timestamp: i64,
) -> Instruction {
    CreateGrubstakeAirdrop {
        authority,
        satrush_config: get_satrush_config_address().0,
        grubstake_airdrop: airdrop,
        treasury: get_treasury_address().0,
        system_program: SYSTEM_PROGRAM_ID,
    }
    .instruction(CreateGrubstakeAirdropInstructionArgs {
        airdrop_authority,
        usd_amount,
        expiration_timestamp,
    })
}

/// `claim_grubstake_airdrop`: claim `airdrop` as `authority`. The payout lands
/// in the miner PDA's USD account and opens the 14-day spend window.
pub fn get_claim_grubstake_airdrop_instruction(
    authority: Pubkey,
    airdrop: Pubkey,
    fee_recipient: Pubkey,
    usd_mint: Pubkey,
) -> Instruction {
    let treasury = get_treasury_address().0;
    let miner = get_miner_address(authority).0;
    ClaimGrubstakeAirdrop {
        authority,
        satrush_config: get_satrush_config_address().0,
        fee_recipient,
        grubstake_airdrop: airdrop,
        miner,
        treasury,
        usd_mint,
        treasury_usd_ata: get_associated_token_address(&treasury, &usd_mint),
        miner_usd_ata: get_associated_token_address(&miner, &usd_mint),
        token_program: TOKEN_PROGRAM_ID,
        associated_token_program: ASSOCIATED_TOKEN_PROGRAM_ID,
        system_program: SYSTEM_PROGRAM_ID,
    }
    .instruction()
}

/// `reclaim_grubstake_airdrop`: release an expired, unclaimed airdrop's
/// reservation back to the pool and close the account. Fee recipient only.
pub fn get_reclaim_grubstake_airdrop_instruction(authority: Pubkey, airdrop: Pubkey) -> Instruction {
    ReclaimGrubstakeAirdrop {
        authority,
        satrush_config: get_satrush_config_address().0,
        grubstake_airdrop: airdrop,
        treasury: get_treasury_address().0,
    }
    .instruction()
}

/// `reclaim_miner_grubstake`: sweep `miner_authority`'s expired grubstake into
/// the treasury's withdrawable protocol fees. Sized from the miner's grubstake
/// counter, so anything on the ATA above it is deliberately left behind. Fee
/// recipient only.
pub fn get_reclaim_miner_grubstake_instruction(
    authority: Pubkey,
    miner_authority: Pubkey,
    usd_mint: Pubkey,
) -> Instruction {
    let treasury = get_treasury_address().0;
    let miner = get_miner_address(miner_authority).0;
    ReclaimMinerGrubstake {
        authority,
        satrush_config: get_satrush_config_address().0,
        miner_authority,
        miner,
        treasury,
        usd_mint,
        miner_usd_ata: get_associated_token_address(&miner, &usd_mint),
        treasury_usd_ata: get_associated_token_address(&treasury, &usd_mint),
        token_program: TOKEN_PROGRAM_ID,
    }
    .instruction()
}

/// `reclaim_grubstake_automation`: sweep a grubstake automation's escrow back
/// to the treasury once its owner's spend window has closed, and close the
/// automation. Fee recipient only.
pub fn get_reclaim_grubstake_automation_instruction(
    authority: Pubkey,
    automation_owner: Pubkey,
    usd_mint: Pubkey,
) -> Instruction {
    let treasury = get_treasury_address().0;
    let automation = get_public_automation_address(automation_owner).0;
    ReclaimGrubstakeAutomation {
        authority,
        satrush_config: get_satrush_config_address().0,
        public_automation: automation,
        miner: get_miner_address(automation_owner).0,
        automation_owner,
        treasury,
        usd_mint,
        automation_usd_ata: get_associated_token_address(&automation, &usd_mint),
        treasury_usd_ata: get_associated_token_address(&treasury, &usd_mint),
        token_program: TOKEN_PROGRAM_ID,
    }
    .instruction()
}