gmsol-cli 0.9.0

GMX-Solana is an extension of GMX on the Solana blockchain.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
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
use std::{collections::BTreeMap, num::NonZeroUsize, path::PathBuf};

use anchor_spl::associated_token::get_associated_token_address;
use either::Either;
use eyre::OptionExt;
use gmsol_sdk::{
    client::{StoreFilter, DISC_OFFSET},
    core::{
        config::FactorKey,
        market::{MarketConfigFlag, VirtualInventoryFlag},
        oracle::PriceProviderKind,
        token_config::{
            TokenMapAccess, UpdateTokenConfigParams, DEFAULT_HEARTBEAT_DURATION, DEFAULT_PRECISION,
            DEFAULT_TIMESTAMP_ADJUSTMENT,
        },
    },
    ops::{
        token_config::UpdateFeedConfig, ConfigOps, GtOps, MarketOps, OracleOps, StoreOps,
        TokenAccountOps, TokenConfigOps, VirtualInventoryOps,
    },
    pda::find_virtual_inventory_for_swaps_address,
    programs::{
        anchor_lang::prelude::Pubkey,
        bytemuck,
        gmsol_store::accounts::{MarketConfigBuffer, VirtualInventory},
    },
    serde::{
        serde_market::{SerdeMarket, SerdeMarketConfig, SerdeMarketConfigBuffer},
        serde_token_map::SerdeTokenConfig,
        StringPubkey,
    },
    solana_utils::{
        bundle_builder::{BundleBuilder, BundleOptions},
        signer::LocalSignerRef,
        solana_client::rpc_filter::{Memcmp, RpcFilterType},
        solana_sdk::{signature::Keypair, signer::Signer},
    },
    utils::{market::MarketDecimals, zero_copy::ZeroCopy, Amount, Value},
};
use indexmap::{IndexMap, IndexSet};
use rust_decimal::Decimal;

use crate::{
    commands::{exchange::display_options_for_markets, utils::toml_from_file},
    config::DisplayOptions,
};

#[cfg(feature = "chaoslabs-risk-oracle")]
use gmsol_sdk::client::risk_oracle::{
    client::ChaosClient, types::EncodedRecommendation, verify::verify_signature,
};

use super::{
    utils::{KeypairArgs, Side, ToggleValue},
    CommandClient,
};

/// Market management commands.
#[derive(Debug, clap::Args)]
pub struct Market {
    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, clap::Subcommand)]
enum Command {
    /// Create an oracle buffer.
    CreateOracle {
        #[command(flatten)]
        keypair: KeypairArgs,
        /// Pubkey of the authority for the oracle buffer.
        #[arg(long)]
        authority: Option<Pubkey>,
    },
    /// Display the token configs in the selected token map.
    Tokens {
        #[arg(long)]
        token_map: Option<Pubkey>,
        #[arg(group = "map-input")]
        token: Option<Pubkey>,
        #[arg(long, group = "map-input")]
        header: bool,
    },
    /// Display the content of the given market config buffer.
    Buffer {
        address: Pubkey,
        /// The expected market token to use for this buffer.
        #[arg(long)]
        market_token: Pubkey,
    },
    /// Create a new token map.
    CreateTokenMap {
        #[command(flatten)]
        keypair: KeypairArgs,
    },
    /// Set the selected token map as the authorized one.
    SetTokenMap { token_map: Pubkey },
    /// Insert token configs from file.
    InsertTokenConfigs {
        #[arg(long)]
        token_map: Option<Pubkey>,
        #[arg(long)]
        set_token_map: bool,
        path: PathBuf,
    },
    /// Update feed configs from file.
    UpdateFeedConfig {
        #[arg(long)]
        token_map: Option<Pubkey>,
        path: PathBuf,
    },
    /// Toggle the token config for the given token.
    ToggleTokenConfig {
        #[arg(long)]
        token_map: Option<Pubkey>,
        token: Pubkey,
        #[command(flatten)]
        toggle: ToggleValue,
    },
    /// Toggle the token price adjustment for the given token.
    ToggleTokenPriceAdjustment {
        #[arg(long)]
        token_map: Option<Pubkey>,
        token: Pubkey,
        #[command(flatten)]
        toggle: ToggleValue,
    },
    /// Set expected provider of token.
    SetExpectedProvider {
        #[arg(long)]
        token_map: Option<Pubkey>,
        token: Pubkey,
        provider: PriceProviderKind,
    },
    /// Create a `MarketConfigBuffer` account.
    CreateBuffer {
        #[command(flatten)]
        keypair: KeypairArgs,
        /// The buffer will expire after this duration.
        #[arg(long, default_value = "1d")]
        expire_after: humantime::Duration,
    },
    /// Close a `MarketConfigBuffer` account.
    CloseBuffer {
        /// Buffer account to close.
        buffer: Pubkey,
        /// Address to receive the lamports.
        #[arg(long)]
        receiver: Option<Pubkey>,
    },
    /// Set the authority of the `MarketConfigBuffer` account.
    SetBufferAuthority {
        /// Buffer account of which to set the authority.
        buffer: Pubkey,
        /// New authority.
        #[arg(long)]
        new_authority: Pubkey,
    },
    /// Push to `MarketConfigBuffer` account with configs read from file.
    #[command(
        group = clap::ArgGroup::new("buffer-target")
            .required(true)
            .multiple(false)
            .args(["buffer", "init"]),
        group = clap::ArgGroup::new("source-input")
            .required(true)
            .multiple(false)
            .args(["path", "from_chaos"]),
    )]
    PushToBuffer {
        /// Path to the config file to read from.
        #[arg(group = "source-input")]
        path: Option<PathBuf>,
        /// Buffer account to be pushed to.
        #[arg(long, group = "buffer-target")]
        buffer: Option<Pubkey>,
        /// Whether to create a new buffer account.
        #[arg(long, group = "buffer-target")]
        init: bool,
        /// The expected market token to use for this buffer.
        #[arg(long)]
        market_token: Pubkey,
        /// The number of keys to push in single instruction.
        #[arg(long, default_value = "16")]
        batch: NonZeroUsize,
        /// The buffer will expire after this duration.
        /// Only effective when used with `--init`.
        #[arg(long, default_value = "1d")]
        expire_after: humantime::Duration,
        /// Create from Chaos Labs' Risk Oracle instead of file.
        #[arg(long, default_value_t = false)]
        from_chaos: bool,
        /// Comma-separated Chaos parameter types to request (optional).
        #[arg(long, value_delimiter = ',')]
        types: Option<Vec<String>>,
        /// Skip response signature verification.
        #[arg(long, default_value_t = false)]
        no_verify: bool,
    },
    /// Create Market Vault.
    CreateVault { token: Pubkey },
    /// Create Market.
    CreateMarket {
        #[arg(long)]
        name: String,
        #[arg(long)]
        index_token: Pubkey,
        #[arg(long)]
        long_token: Pubkey,
        #[arg(long)]
        short_token: Pubkey,
        #[arg(long)]
        enable: bool,
    },
    /// Create Markets from file.
    CreateMarkets {
        path: PathBuf,
        #[arg(long)]
        enable: bool,
    },
    /// Toggle market.
    ToggleMarket {
        market_token: Pubkey,
        #[command(flatten)]
        toggle: ToggleValue,
    },
    /// Fund Market.
    FundMarket {
        /// The address of the market token of the Market to fund
        market_token: Pubkey,
        /// The funding side.
        #[arg(long)]
        side: Side,
        /// The funding amount.
        #[arg(long, short)]
        amount: u64,
    },
    /// Update Market Config Flag.
    ToggleConfigFlag {
        /// The market token of the market to update.
        market_token: Pubkey,
        /// The config key to update.
        #[arg(long)]
        key: MarketConfigFlag,
        /// The boolean value that the flag to update to.
        #[command(flatten)]
        toggle: ToggleValue,
    },
    /// Update Market Configs from file.
    UpdateConfigs {
        path: PathBuf,
        /// Receiver for the buffer's lamports.
        #[arg(long)]
        receiver: Option<Pubkey>,
        /// Whether to keep the used market config buffer accounts.
        #[arg(long)]
        keep_buffers: bool,
    },
    /// Toggle GT minting.
    ToggleGtMinting {
        #[arg(required = true, num_args = 1..)]
        market_tokens: Vec<Pubkey>,
        #[command(flatten)]
        toggle: ToggleValue,
    },
    /// Initialize GT.
    InitGt {
        #[arg(long, short, default_value_t = 7)]
        decimals: u8,
        #[arg(long, short = 'c', default_value_t = Value(Decimal::new(1, 2)))]
        initial_minting_cost: Value,
        #[arg(long, default_value_t = Value(Decimal::new(1_021, 3)))]
        grow_factor: Value,
        #[arg(long, default_value_t = Amount(Decimal::new(210_000, 0)))]
        grow_step: Amount,
        #[arg(required = true)]
        ranks: Vec<Amount>,
    },
    /// Set order fee discount factors.
    SetOrderFeeDiscountFactors {
        #[arg(required = true)]
        factors: Vec<Value>,
    },
    /// Set referral reward factors.
    SetReferralRewardFactors {
        #[arg(required = true)]
        factors: Vec<Value>,
    },
    /// Set referred discount.
    SetReferredDiscountFactor { factor: Value },
    /// Create or update token metadata from file.
    UpdateTokenMetadatas { path: PathBuf },
    /// Display virtual inventories.
    VirtualInventories {
        address: Option<Pubkey>,
        /// Displays the market list associated with the given VI.
        #[arg(long, requires = "address")]
        markets: bool,
    },
    /// Create a virtual inventory for swaps.
    CreateVirtualInventoryForSwaps {
        #[arg(long)]
        index: u32,
        #[arg(long, short)]
        long_amount_decimals: u8,
        #[arg(long, short)]
        short_amount_decimals: u8,
    },
    /// Create a virtual inventory for positions.
    CreateVirtualInventoryForPositions { index_token: Pubkey },
    /// Disable virtual inventories.
    DisableVirtualInventories {
        #[arg(required = true, num_args = 1..)]
        addresses: Vec<Pubkey>,
    },
    /// Join the given virtual inventory for swaps.
    JoinVirtualInventoryForSwaps {
        #[arg(required = true, num_args = 1..)]
        market_tokens: Vec<Pubkey>,
        #[arg(long)]
        virtual_inventory: Pubkey,
    },
    /// Join the given virtual inventory for positions.
    JoinVirtualInventoryForPositions {
        #[arg(required = true, num_args = 1..)]
        market_tokens: Vec<Pubkey>,
        #[arg(long)]
        virtual_inventory: Pubkey,
    },
    /// Leave the given virtual inventory.
    LeaveVirtualInventory {
        #[arg(required = true, num_args = 1..)]
        market_tokens: Vec<Pubkey>,
        #[arg(long)]
        virtual_inventory: Pubkey,
    },
    /// Close virtual inventories.
    CloseVirtualInventories {
        #[arg(required = true, num_args = 1..)]
        addresses: Vec<Pubkey>,
    },
    /// Display updatable market config flags and/or factors.
    /// By default, show both. Use --without-flags or --without-factors to hide.
    UpdatableConfig {
        #[arg(long, alias = "no-flags")]
        without_flags: bool,
        #[arg(long, alias = "no-factors")]
        without_factors: bool,
    },
    /// Query if a specific market config flag or factor is updatable.
    IsConfigUpdatable {
        #[arg(long, group = "what")]
        flag: Option<MarketConfigFlag>,
        #[arg(long, group = "what")]
        factor: Option<gmsol_sdk::core::market::MarketConfigKey>,
    },
    /// Enable or disable updates for a set of market config flags and/or factors.
    SetConfigUpdatable {
        /// Flags to set updatable.
        #[arg(long = "flag", required = false, num_args = 1..)]
        flags: Vec<MarketConfigFlag>,
        /// Factors to set updatable.
        #[arg(long = "factor", required = false, num_args = 1..)]
        factors: Vec<gmsol_sdk::core::market::MarketConfigKey>,
        #[command(flatten)]
        toggle: ToggleValue,
    },
}

impl super::Command for Market {
    fn is_client_required(&self) -> bool {
        true
    }

    async fn execute(&self, ctx: super::Context<'_>) -> eyre::Result<()> {
        let client = ctx.client()?;
        let store = ctx.store();
        let options = ctx.bundle_options();
        let output = ctx.config().output();

        let bundle = match &self.command {
            Command::CreateOracle { keypair, authority } => {
                let oracle = keypair.to_keypair()?;
                let (rpc, oracle) = client
                    .initialize_oracle(store, &oracle, authority.as_ref())
                    .await?;
                println!("Oracle: {oracle}");
                let bundle = rpc.into_bundle_with_options(options)?;
                client.send_or_serialize(bundle).await?;
                return Ok(());
            }
            Command::Tokens {
                token_map,
                token,
                header,
            } => {
                let token_map_address = token_map_address(client, token_map.as_ref()).await?;
                let token_map = client.token_map(&token_map_address).await?;

                if let Some(token) = token {
                    let config = token_map.get(token).ok_or_eyre("token not found")?;
                    let serialized = SerdeTokenConfig::try_from(config)?;
                    println!(
                        "{}",
                        output.display_keyed_account(
                            token,
                            serialized,
                            DisplayOptions::table_projection([
                                ("name", "Name"),
                                ("pubkey", "Pubkey"),
                                ("is_enabled", "Enabled"),
                                ("is_synthetic", "Synthetic"),
                                ("token_decimals", "Decimals"),
                                ("price_precision", "Price Precision"),
                                ("expected_provider", "Expected Provider"),
                                ("feeds.chainlink_data_streams.feed_id", "Chainlink Feed"),
                                (
                                    "feeds.chainlink_data_streams.timestamp_adjustment",
                                    "Chainlink TS Adj",
                                ),
                                ("feeds.pyth.feed_id", "Pyth Feed"),
                                ("feeds.pyth.timestamp_adjustment", "Pyth TS Adj",),
                                ("feeds.switchboard.feed_id", "Switchboard Feed"),
                                (
                                    "feeds.switchboard.timestamp_adjustment",
                                    "Switchboard TS Adj",
                                ),
                            ])
                        )?
                    );
                } else if *header {
                    let authorized_token_map_address =
                        client.authorized_token_map_address(store).await?;
                    let output = output.display_keyed_account(
                                &token_map_address,
                                serde_json::json!({
                                    "store": StringPubkey(token_map.header().store),
                                    "tokens": token_map.header().tokens.len(),
                                    "is_authorized": authorized_token_map_address == Some(token_map_address),
                                }),
                                DisplayOptions::table_projection([
                                    ("pubkey", "Address"),
                                    ("tokens", "Tokens"),
                                    ("is_authorized", "Authorized"),
                                ]),
                            )?;
                    println!("{output}");
                } else {
                    let mut map = token_map
                        .tokens()
                        .filter_map(|token| {
                            token_map
                                .get(&token)
                                .and_then(|config| SerdeTokenConfig::try_from(config).ok())
                                .map(|config| (token, config))
                        })
                        .collect::<IndexMap<_, _>>();
                    map.sort_by(|_, a, _, b| a.name.cmp(&b.name));
                    map.sort_by(|_, a, _, b| a.is_enabled.cmp(&b.is_enabled).reverse());
                    println!(
                        "{}",
                        output.display_keyed_accounts(
                            map,
                            DisplayOptions::table_projection([
                                ("name", "Name"),
                                ("pubkey", "Pubkey"),
                                ("is_enabled", "Enabled"),
                                ("is_synthetic", "Synthetic"),
                                ("token_decimals", "Decimals"),
                                ("price_precision", "Price Precision"),
                                ("expected_provider", "Expected Provider"),
                            ])
                        )?
                    );
                }

                return Ok(());
            }
            Command::Buffer {
                address,
                market_token,
            } => {
                let buffer = client
                    .account::<MarketConfigBuffer>(address)
                    .await?
                    .ok_or(gmsol_sdk::Error::NotFound)?;
                let token_map = client.authorized_token_map(store).await?;
                let market = client.market_by_token(store, market_token).await?;
                let decimals = MarketDecimals::new(&market.meta.into(), &token_map)?;
                let buffer = SerdeMarketConfigBuffer::from_market_config_buffer(&buffer, decimals)?;
                println!(
                    "{}",
                    output.display_keyed_account(
                        address,
                        &buffer,
                        DisplayOptions::table_projection([
                            ("pubkey", "Address"),
                            ("store", "Store"),
                            ("authority", "Authority"),
                            ("expiry", "Expiry"),
                        ])
                    )?
                );
                return Ok(());
            }
            Command::CreateTokenMap { keypair } => {
                let token_map = keypair.to_keypair()?;
                let (rpc, token_map) = client.initialize_token_map(store, &token_map);
                println!("Token Map: {token_map}");
                let bundle = rpc.into_bundle_with_options(options)?;
                client.send_or_serialize(bundle).await?;
                return Ok(());
            }
            Command::SetTokenMap { token_map } => client
                .set_token_map(store, token_map)
                .into_bundle_with_options(options)?,
            Command::InsertTokenConfigs {
                path,
                token_map,
                set_token_map,
            } => {
                let configs: IndexMap<String, TokenConfig> = toml_from_file(path)?;
                let token_map = token_map_address(client, token_map.as_ref()).await?;
                insert_token_configs(client, &token_map, *set_token_map, &configs, options)?
            }
            Command::UpdateFeedConfig { token_map, path } => {
                let token_map = token_map_address(client, token_map.as_ref()).await?;
                let configs: IndexMap<StringPubkey, IndexMap<PriceProviderKind, UpdateFeedConfig>> =
                    toml_from_file(path)?;
                let mut bundle = client.bundle_with_options(options);
                for (token, feeds) in configs {
                    for (provider, config) in feeds {
                        let rpc = client
                            .update_feed_config(store, &token_map, &token, provider, config)?;
                        bundle.push(rpc)?;
                    }
                }
                bundle
            }
            Command::ToggleTokenConfig {
                token,
                token_map,
                toggle,
            } => {
                let token_map_address = token_map_address(client, token_map.as_ref()).await?;
                client
                    .toggle_token_config(store, &token_map_address, token, toggle.is_enable())
                    .into_bundle_with_options(options)?
            }
            Command::ToggleTokenPriceAdjustment {
                token,
                token_map,
                toggle,
            } => {
                let token_map_address = token_map_address(client, token_map.as_ref()).await?;
                client
                    .toggle_token_price_adjustment(
                        store,
                        &token_map_address,
                        token,
                        toggle.is_enable(),
                    )
                    .into_bundle_with_options(options)?
            }
            Command::SetExpectedProvider {
                token_map,
                token,
                provider,
            } => {
                let token_map_address = token_map_address(client, token_map.as_ref()).await?;
                client
                    .set_expected_provider(store, &token_map_address, token, *provider)
                    .into_bundle_with_options(options)?
            }
            Command::CreateBuffer {
                keypair,
                expire_after,
            } => {
                let buffer_keypair = keypair.to_keypair()?;
                let rpc = client.initialize_market_config_buffer(
                    store,
                    &buffer_keypair,
                    expire_after.as_secs().try_into()?,
                );

                client
                    .send_or_serialize(rpc.into_bundle_with_options(options)?)
                    .await?;
                return Ok(());
            }
            Command::CloseBuffer { buffer, receiver } => client
                .close_marekt_config_buffer(buffer, receiver.as_ref())
                .into_bundle_with_options(options)?,
            Command::SetBufferAuthority {
                buffer,
                new_authority,
            } => client
                .set_market_config_buffer_authority(buffer, new_authority)
                .into_bundle_with_options(options)?,
            Command::PushToBuffer {
                path,
                buffer,
                init,
                market_token,
                batch,
                expire_after,
                from_chaos,
                types,
                no_verify,
            } => {
                assert!(buffer.is_none() == *init, "must hold");
                let keypair = Keypair::new();
                let buffer = match buffer {
                    Some(buffer) => Either::Left(buffer),
                    None => Either::Right(&keypair),
                };

                if *from_chaos {
                    #[cfg(not(feature = "chaoslabs-risk-oracle"))]
                    let _ = (&types, &no_verify);
                    #[cfg(not(feature = "chaoslabs-risk-oracle"))]
                    {
                        eyre::bail!("chaoslabs-risk-oracle feature is not enabled for CLI");
                    }
                    #[cfg(feature = "chaoslabs-risk-oracle")]
                    {
                        let base_url = ctx.config().chaos_base_url();
                        let api_key = ctx.config().chaos_api_key();
                        let chaos = ChaosClient::try_new(&base_url, api_key)?;
                        let update_types: Vec<String> = if let Some(t) = types {
                            t.clone()
                        } else {
                            vec![
                                "oiCaps/maxOpenInterestForLongs/v1".to_string(),
                                "oiCaps/maxOpenInterestForShorts/v1".to_string(),
                                "priceImpact/negativePositionImpactFactor/v1".to_string(),
                                "priceImpact/positionImpactExponentFactor/v1".to_string(),
                                "priceImpact/positivePositionImpactFactor/v1".to_string(),
                            ]
                        };
                        let update_types_ref: Vec<&str> =
                            update_types.iter().map(|s| s.as_str()).collect();
                        let recs: Vec<EncodedRecommendation> = chaos
                            .fetch_latest_recommendations("gmx_solana", &update_types_ref)
                            .await?;

                        if !*no_verify {
                            match ctx.config().chaos_signer_strict()? {
                                Some(expected) => {
                                    for r in &recs {
                                        verify_signature(r, &expected)?;
                                    }
                                }
                                None => {
                                    eyre::bail!(
                                        "verification requested but chaos signer is missing; set RISK_ORACLE_SIGNER env or [chaos].signer in config.toml, or pass --no-verify to skip"
                                    );
                                }
                            }
                        }

                        let market =
                            client
                                .market_by_token(store, market_token)
                                .await
                                .map_err(|e| {
                                    eyre::eyre!(
                                        "failed to get market by token {}: {e}",
                                        market_token
                                    )
                                })?;
                        let token_map = client
                            .authorized_token_map(store)
                            .await
                            .map_err(|e| eyre::eyre!("failed to get authorized token map: {e}"))?;
                        let md = gmsol_sdk::utils::market::MarketDecimals::new(&market.meta.into(), &token_map).map_err(|e| eyre::eyre!("failed to create MarketDecimals (is market's tokens in token_map?): {e}"))?;

                        let mut entries: Vec<(String, u128)> = Vec::new();
                        for rec in &recs {
                            if rec.market_pubkey()? != *market_token {
                                continue;
                            }
                            tracing::info!(%market_token, "adding recommendation: {rec:#?}");
                            for (k, v_api) in &rec.new_values {
                                if let Some(key_enum) =
                                    gmsol_sdk::client::risk_oracle::types::map_key(
                                        k,
                                        &rec.parameter_name,
                                    )
                                {
                                    let dec_api = *rec
                                        .decimals
                                        .get(k)
                                        .ok_or_eyre(format!("missing decimals for {k}"))?;
                                    let dec_target = md.market_config_decimals(key_enum)?;

                                    let amount = Amount::from_u128((*v_api).into(), dec_api)?;
                                    let v_scaled = match key_enum {
                                        gmsol_sdk::core::market::MarketConfigKey::PositionImpactExponent
                                        | gmsol_sdk::core::market::MarketConfigKey::SwapImpactExponent => {
                                            let rounded = Amount(amount.0.round());
                                            rounded.to_u128(dec_target)?
                                        }
                                        _ => amount.to_u128(dec_target)?,
                                    };
                                    let key_str = key_enum.to_string();
                                    entries.push((key_str, v_scaled));
                                }
                            }
                        }

                        if entries.is_empty() {
                            eyre::bail!("no chaos updates for the specified market_token");
                        }

                        let mut bundle = client.bundle_with_options(options);
                        let buffer_pubkey = match buffer {
                            Either::Left(pubkey) => *pubkey,
                            Either::Right(kp) => {
                                bundle.push(client.initialize_market_config_buffer(
                                    store,
                                    kp,
                                    expire_after.as_secs().try_into().unwrap_or(u32::MAX),
                                ))?;
                                kp.pubkey()
                            }
                        };
                        println!("Buffer: {buffer_pubkey}");

                        for batch_entries in entries.chunks(batch.get()) {
                            bundle.push(client.push_to_market_config_buffer(
                                &buffer_pubkey,
                                batch_entries.iter().cloned(),
                            ))?;
                        }

                        client.send_or_serialize(bundle).await?;
                        return Ok(());
                    }
                }

                let path = path
                    .as_ref()
                    .ok_or_eyre("path is required unless --from-chaos")?;
                let configs: MarketConfigs = toml_from_file(path)?;
                let config = configs
                    .configs
                    .get(market_token)
                    .ok_or_eyre(format!("the config for `{market_token}` not found"))?;
                let bundle = push_to_market_config_buffer(
                    client,
                    buffer,
                    market_token,
                    &config.config,
                    expire_after,
                    *batch,
                    options,
                )
                .await?;
                client.send_or_serialize(bundle).await?;
                return Ok(());
            }
            Command::CreateVault { token } => {
                let (rpc, vault) = client.initialize_market_vault(store, token);
                println!("Market Vault: {vault}");
                rpc.into_bundle_with_options(options)?
            }
            Command::CreateMarket {
                name,
                index_token,
                long_token,
                short_token,
                enable,
            } => {
                let (rpc, market_token) = client
                    .create_market(
                        store,
                        name,
                        index_token,
                        long_token,
                        short_token,
                        *enable,
                        None,
                    )
                    .await?;
                println!("Market Token: {market_token}");
                rpc.into_bundle_with_options(options)?
            }
            Command::CreateMarkets { path, enable } => {
                let markets: IndexMap<String, CreateMarket> = toml_from_file(path)?;
                create_markets(client, *enable, &markets, options).await?
            }
            Command::ToggleMarket {
                market_token,
                toggle,
            } => client
                .toggle_market(store, market_token, toggle.is_enable())
                .into_bundle_with_options(options)?,
            Command::FundMarket {
                market_token,
                side,
                amount,
            } => {
                let market = client.market_by_token(store, market_token).await?;
                let token = match side {
                    Side::Long => market.meta.long_token_mint,
                    Side::Short => market.meta.short_token_mint,
                };
                let source_account = get_associated_token_address(&client.payer(), &token);
                client
                    .fund_market(store, market_token, &source_account, *amount, Some(&token))
                    .await?
                    .into_bundle_with_options(options)?
            }
            Command::ToggleConfigFlag {
                market_token,
                key,
                toggle,
            } => client
                .update_market_config_flag_by_key(store, market_token, *key, toggle.is_enable())?
                .into_bundle_with_options(options)?,
            Command::UpdateConfigs {
                path,
                receiver,
                keep_buffers,
            } => {
                let configs: MarketConfigs = toml_from_file(path)?;
                configs
                    .update_market_configs(client, receiver.as_ref(), !*keep_buffers, options)
                    .await?
            }
            Command::ToggleGtMinting {
                market_tokens,
                toggle,
            } => {
                let mut bundle = client.bundle_with_options(options);
                for market_token in market_tokens {
                    let rpc = client.toggle_gt_minting(store, market_token, toggle.is_enable());
                    bundle.push(rpc)?;
                }
                bundle
            }
            Command::SetConfigUpdatable {
                flags,
                factors,
                toggle,
            } => {
                use indexmap::IndexMap;
                if flags.is_empty() && factors.is_empty() {
                    eyre::bail!("at least one --flag or --factor must be provided");
                }
                let value = toggle.is_enable();
                let flags_map: IndexMap<_, _> = flags.iter().cloned().map(|f| (f, value)).collect();
                let factors_map: IndexMap<_, _> = factors
                    .iter()
                    .map(|k| Ok::<_, eyre::Report>((*k).try_into().map(|f| (f, value))?))
                    .collect::<eyre::Result<_>>()?;
                client
                    .set_market_config_updatable(store, flags_map, factors_map)?
                    .into_bundle_with_options(options)?
            }
            Command::InitGt {
                decimals,
                initial_minting_cost,
                grow_factor,
                grow_step,
                ranks,
            } => {
                debug_assert!(!ranks.is_empty());
                let decimals = *decimals;
                let ranks = ranks
                    .iter()
                    .map(|a| Ok(a.to_u64(decimals)?))
                    .collect::<eyre::Result<Vec<_>>>()?;
                if !ranks.is_sorted() {
                    eyre::bail!("ranks must be sorted");
                }
                let initial_minting_cost =
                    initial_minting_cost.to_u128()? / 10u128.pow(decimals.into());
                let grow_factor = grow_factor.to_u128()?;
                let grow_step = grow_step.to_u64(decimals)?;
                client
                    .initialize_gt(
                        store,
                        decimals,
                        initial_minting_cost,
                        grow_factor,
                        grow_step,
                        ranks,
                    )
                    .into_bundle_with_options(options)?
            }
            Command::SetOrderFeeDiscountFactors { factors } => {
                debug_assert!(!factors.is_empty());
                let factors = factors
                    .iter()
                    .map(|v| Ok(v.to_u128()?))
                    .collect::<eyre::Result<Vec<_>>>()?;
                client
                    .gt_set_order_fee_discount_factors(store, factors)
                    .into_bundle_with_options(options)?
            }
            Command::SetReferralRewardFactors { factors } => {
                debug_assert!(!factors.is_empty());
                let factors = factors
                    .iter()
                    .map(|v| Ok(v.to_u128()?))
                    .collect::<eyre::Result<Vec<_>>>()?;
                client
                    .gt_set_referral_reward_factors(store, factors)
                    .into_bundle_with_options(options)?
            }
            Command::SetReferredDiscountFactor { factor } => client
                .insert_global_factor_by_key(
                    store,
                    FactorKey::OrderFeeDiscountForReferredUser,
                    &factor.to_u128()?,
                )
                .into_bundle_with_options(options)?,
            Command::UpdateTokenMetadatas { path } => {
                let config: TokenMetadatas = toml_from_file(path)?;
                let mut bundle = client.bundle_with_options(options);
                for (mint, metadata) in config.0 {
                    let rpc = if metadata.init {
                        let (rpc, token_metadata) = client
                            .create_token_metadata(
                                store,
                                &mint,
                                metadata.name,
                                metadata.symbol,
                                metadata.uri,
                            )
                            .swap_output(());
                        println!("Creating token metadata {token_metadata} for {mint}");
                        rpc
                    } else {
                        client.update_token_metadata_by_mint(
                            store,
                            &mint,
                            metadata.name,
                            metadata.symbol,
                            metadata.uri,
                        )
                    };
                    bundle.push(rpc)?;
                }

                bundle
            }
            Command::VirtualInventories { address, markets } => {
                use gmsol_sdk::programs::gmsol_store::accounts::Market as MarketAccount;

                match address {
                    Some(address) => {
                        let vi = client
                            .account::<ZeroCopy<VirtualInventory>>(address)
                            .await?
                            .ok_or(gmsol_sdk::Error::NotFound)?;
                        let vi = SerdeVirtualInventory::new(address, &vi.0)?;
                        if *markets {
                            let offset = if vi.for_swaps {
                                bytemuck::offset_of!(MarketAccount, virtual_inventory_for_swaps)
                            } else {
                                bytemuck::offset_of!(MarketAccount, virtual_inventory_for_positions)
                            };
                            let token_map = client.authorized_token_map(store).await?;
                            let markets = client
                                .store_accounts::<ZeroCopy<MarketAccount>>(
                                    Some(StoreFilter::new(
                                        store,
                                        bytemuck::offset_of!(MarketAccount, store),
                                    )),
                                    Some(RpcFilterType::Memcmp(Memcmp::new_base58_encoded(
                                        DISC_OFFSET + offset,
                                        address.as_ref(),
                                    ))),
                                )
                                .await?;
                            let mut serde_markets = markets
                                .iter()
                                .map(|(p, m)| {
                                    SerdeMarket::from_market(&m.0, &token_map).map(|m| (p, m))
                                })
                                .collect::<gmsol_sdk::Result<Vec<(_, _)>>>()?;
                            serde_markets.sort_by(|(_, a), (_, b)| a.name.cmp(&b.name));
                            serde_markets.sort_by_key(|(_, m)| m.enabled);
                            println!(
                                "{}",
                                output.display_keyed_accounts(
                                    serde_markets,
                                    display_options_for_markets(),
                                )?
                            );
                        } else {
                            let msg =
                                output.display_keyed_account(address, &vi, Default::default())?;
                            println!("{msg}");
                        }
                    }
                    None => {
                        let vis = client
                            .store_accounts::<ZeroCopy<VirtualInventory>>(
                                Some(StoreFilter::new(
                                    store,
                                    bytemuck::offset_of!(VirtualInventory, store),
                                )),
                                None,
                            )
                            .await?;
                        let vis = vis
                            .iter()
                            .map(|(pubkey, vi)| {
                                Ok((pubkey, SerdeVirtualInventory::new(pubkey, &vi.0)?))
                            })
                            .collect::<gmsol_sdk::Result<BTreeMap<_, _>>>()?;
                        let msg = output.display_keyed_accounts(vis, Default::default())?;
                        println!("{msg}");
                    }
                }
                return Ok(());
            }
            Command::UpdatableConfig {
                without_flags,
                without_factors,
            } => {
                use gmsol_sdk::core::market::{
                    MarketConfigFactor, MarketConfigFlag, MarketConfigKey,
                };
                use gmsol_sdk::programs::gmsol_store::accounts as store_accounts;
                use strum::IntoEnumIterator;

                let store_account: std::sync::Arc<store_accounts::Store> =
                    client.store(store).await?;

                if !*without_flags {
                    let mut rows = Vec::new();
                    for flag in MarketConfigFlag::iter() {
                        let updatable = store_account
                            .market_config_permissions
                            .updatable_market_config_flags
                            .get_flag(flag);
                        rows.push(serde_json::json!({
                            "name": flag.to_string(),
                            "updatable": updatable,
                        }));
                    }
                    let out = output.display_many(
                        rows,
                        DisplayOptions::table_projection([
                            ("name", "Flag"),
                            ("updatable", "Updatable"),
                        ]),
                    )?;
                    println!("{out}");
                }

                if !*without_factors {
                    let mut rows = Vec::new();
                    for key in MarketConfigKey::iter() {
                        if let Ok(factor) = MarketConfigFactor::try_from(key) {
                            let updatable = store_account
                                .market_config_permissions
                                .updatable_market_config_factors
                                .get_flag(factor);
                            rows.push(serde_json::json!({
                                "key": key.to_string(),
                                "updatable": updatable,
                            }));
                        }
                    }
                    let out = output.display_many(
                        rows,
                        DisplayOptions::table_projection([
                            ("key", "Factor"),
                            ("updatable", "Updatable"),
                        ]),
                    )?;
                    println!("{out}");
                }

                return Ok(());
            }
            Command::IsConfigUpdatable { flag, factor } => {
                use gmsol_sdk::core::market::MarketConfigFactor;
                use gmsol_sdk::programs::gmsol_store::accounts as store_accounts;

                let store_account: std::sync::Arc<store_accounts::Store> =
                    client.store(store).await?;
                match (flag, factor) {
                    (Some(flag), None) => {
                        let is_updatable = store_account
                            .market_config_permissions
                            .updatable_market_config_flags
                            .get_flag(*flag);
                        println!("{is_updatable}");
                    }
                    (None, Some(key)) => {
                        let factor = MarketConfigFactor::try_from(*key)?;
                        let is_updatable = store_account
                            .market_config_permissions
                            .updatable_market_config_factors
                            .get_flag(factor);
                        println!("{is_updatable}");
                    }
                    _ => {
                        eyre::bail!("specify exactly one of --flag or --factor");
                    }
                }
                return Ok(());
            }
            Command::CreateVirtualInventoryForSwaps {
                index,
                long_amount_decimals,
                short_amount_decimals,
            } => {
                let (rpc, vi) = client
                    .create_virtual_inventory_for_swaps(
                        store,
                        *index,
                        *long_amount_decimals,
                        *short_amount_decimals,
                    )?
                    .swap_output(());
                println!("{vi}");
                rpc.into_bundle_with_options(options)?
            }
            Command::CreateVirtualInventoryForPositions { index_token } => {
                let (rpc, vi) = client
                    .create_virtual_inventory_for_positions(store, index_token)?
                    .swap_output(());
                println!("{vi}");
                rpc.into_bundle_with_options(options)?
            }
            Command::DisableVirtualInventories { addresses } => {
                let mut bundle = client.bundle_with_options(options);
                for address in addresses {
                    let rpc = client.disable_virtual_inventory(store, address)?;
                    bundle.push(rpc)?;
                }
                bundle
            }
            Command::JoinVirtualInventoryForSwaps {
                market_tokens,
                virtual_inventory,
            } => {
                let mut bundle = client.bundle_with_options(options);
                let token_map = client
                    .authorized_token_map_address(store)
                    .await?
                    .ok_or(gmsol_sdk::Error::NotFound)?;
                for market_token in market_tokens {
                    let market = client.find_market_address(store, market_token);
                    let rpc = client
                        .join_virtual_inventory_for_swaps(
                            store,
                            &market,
                            virtual_inventory,
                            Some(&token_map),
                        )
                        .await?;
                    bundle.push(rpc)?;
                }
                bundle
            }
            Command::JoinVirtualInventoryForPositions {
                market_tokens,
                virtual_inventory,
            } => {
                let mut bundle = client.bundle_with_options(options);
                for market_token in market_tokens {
                    let market = client.find_market_address(store, market_token);
                    let rpc = client.join_virtual_inventory_for_positions(
                        store,
                        &market,
                        virtual_inventory,
                    )?;
                    bundle.push(rpc)?;
                }
                bundle
            }
            Command::LeaveVirtualInventory {
                market_tokens,
                virtual_inventory,
            } => {
                let mut bundle = client.bundle_with_options(options);
                let vi = client
                    .account::<ZeroCopy<VirtualInventory>>(virtual_inventory)
                    .await?
                    .ok_or(gmsol_sdk::Error::NotFound)?
                    .0;
                let markets = market_tokens
                    .iter()
                    .map(|token| client.find_market_address(store, token))
                    .collect::<Vec<_>>();
                if vi.flags.get_flag(VirtualInventoryFlag::Disabled) {
                    for market in &markets {
                        bundle.push(client.leave_disabled_virtual_inventory(
                            store,
                            market,
                            virtual_inventory,
                        )?)?;
                    }
                } else {
                    let first = markets.first().expect("must exist");
                    let market = client.market(first).await?;
                    if market.virtual_inventory_for_swaps == *virtual_inventory {
                        for market in &markets {
                            bundle.push(client.leave_virtual_inventory_for_swaps(
                                store,
                                market,
                                virtual_inventory,
                            )?)?;
                        }
                    } else if market.virtual_inventory_for_positions == *virtual_inventory {
                        for market in &markets {
                            bundle.push(client.leave_virtual_inventory_for_positions(
                                store,
                                market,
                                virtual_inventory,
                            )?)?;
                        }
                    } else {
                        eyre::bail!("the first market has not included this virtual inventory.");
                    }
                }
                bundle
            }
            Command::CloseVirtualInventories { addresses } => {
                let mut bundle = client.bundle_with_options(options);
                for address in addresses {
                    bundle.push(client.close_virtual_inventory_account(store, address)?)?;
                }
                bundle
            }
        };

        client.send_or_serialize(bundle).await?;

        Ok(())
    }
}

async fn token_map_address(
    client: &CommandClient,
    token_map: Option<&Pubkey>,
) -> eyre::Result<Pubkey> {
    let address = match token_map {
        Some(address) => *address,
        None => client
            .authorized_token_map_address(&client.store)
            .await?
            .ok_or_eyre("no authorized token map")?,
    };
    Ok(address)
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
struct MarketConfig {
    #[serde(default)]
    enable: Option<bool>,
    #[serde(default)]
    buffer: Option<StringPubkey>,
    #[serde(flatten)]
    config: SerdeMarketConfig,
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct MarketConfigs {
    #[serde(flatten)]
    configs: IndexMap<StringPubkey, MarketConfig>,
}

impl MarketConfigs {
    async fn update_market_configs<'a>(
        &self,
        client: &'a CommandClient,
        receiver: Option<&Pubkey>,
        close_buffers: bool,
        options: BundleOptions,
    ) -> eyre::Result<BundleBuilder<'a, LocalSignerRef>> {
        let store = &client.store;
        let token_map = client.authorized_token_map(store).await?;
        let mut bundle = client.bundle_with_options(options);

        let mut buffers_to_close = IndexSet::<Pubkey>::default();

        for (market_token, config) in &self.configs {
            let market = client.market_by_token(store, market_token).await?;
            let decimals = MarketDecimals::new(&market.meta.into(), &token_map)?;
            if let Some(buffer) = &config.buffer {
                let buffer_account = client
                    .account::<MarketConfigBuffer>(buffer)
                    .await?
                    .ok_or(gmsol_sdk::Error::NotFound)?;
                if buffer_account.store != *store {
                    return Err(gmsol_sdk::Error::custom(
                        "The provided buffer account is owned by different store",
                    )
                    .into());
                }
                if buffer_account.authority != client.payer() {
                    return Err(gmsol_sdk::Error::custom(
                        "The authority of the provided buffer account is not the payer",
                    )
                    .into());
                }
                tracing::info!("A buffer account is provided, it will be used first to update the market config. Add instruction to update `{market_token}` with it");
                bundle.push(client.update_market_config_with_buffer(
                    store,
                    market_token,
                    buffer,
                ))?;
                if close_buffers {
                    buffers_to_close.insert(**buffer);
                }
            }
            for (key, value) in &config.config.0 {
                let value = value.to_u128(decimals.market_config_decimals(*key)?)?;
                tracing::info!(%market_token, "Add instruction to update `{key}` to `{value}`");
                bundle.push(client.update_market_config_by_key(
                    store,
                    market_token,
                    *key,
                    &value,
                )?)?;
            }
            if let Some(enable) = config.enable {
                tracing::info!(%market_token,
                    "Add instruction to {} market",
                    if enable { "enable" } else { "disable" },
                );
                bundle.push(client.toggle_market(store, market_token, enable))?;
            }
        }

        // Push close buffer instructions.
        for buffer in buffers_to_close.iter() {
            bundle.push(client.close_marekt_config_buffer(buffer, receiver))?;
        }

        Ok(bundle)
    }
}

async fn push_to_market_config_buffer<'a>(
    client: &'a CommandClient,
    buffer: Either<&Pubkey, &'a Keypair>,
    market_token: &Pubkey,
    config: &SerdeMarketConfig,
    expire_after: &humantime::Duration,
    batch: NonZeroUsize,
    options: BundleOptions,
) -> eyre::Result<BundleBuilder<'a, LocalSignerRef>> {
    let store = &client.store;
    let market = client.market_by_token(store, market_token).await?;
    let token_map = client.authorized_token_map(store).await?;
    let decimals = MarketDecimals::new(&market.meta.into(), &token_map)?;

    let mut bundle = client.bundle_with_options(options);

    let buffer = match buffer {
        Either::Left(pubkey) => *pubkey,
        Either::Right(keypair) => {
            bundle.push(client.initialize_market_config_buffer(
                store,
                keypair,
                expire_after.as_secs().try_into().unwrap_or(u32::MAX),
            ))?;
            keypair.pubkey()
        }
    };

    println!("Buffer: {buffer}");

    let configs = config
        .0
        .iter()
        .map(|(k, v)| Ok((k, v.to_u128(decimals.market_config_decimals(*k)?)?)))
        .collect::<eyre::Result<Vec<_>>>()?;
    for batch in configs.chunks(batch.get()) {
        bundle.push(client.push_to_market_config_buffer(
            &buffer,
            batch.iter().map(|(key, value)| (key, *value)),
        ))?;
    }

    Ok(bundle)
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct TokenConfig {
    address: StringPubkey,
    #[serde(default)]
    synthetic: Option<u8>,
    enable: bool,
    expected_provider: PriceProviderKind,
    feeds: Feeds,
    #[serde(default = "default_precision")]
    precision: u8,
    #[serde(default = "default_heartbeat_duration")]
    heartbeat_duration: u32,
    #[serde(default)]
    update: bool,
}

fn default_heartbeat_duration() -> u32 {
    DEFAULT_HEARTBEAT_DURATION
}

fn default_precision() -> u8 {
    DEFAULT_PRECISION
}

impl<'a> TryFrom<&'a TokenConfig> for UpdateTokenConfigParams {
    type Error = eyre::Error;

    fn try_from(config: &'a TokenConfig) -> Result<Self, Self::Error> {
        let mut builder = Self::default()
            .with_expected_provider(config.expected_provider)
            .with_heartbeat_duration(config.heartbeat_duration)
            .with_precision(config.precision);
        if let Some(feed_id) = config.feeds.switchboard_feed_id()? {
            builder = builder.update_price_feed(
                &PriceProviderKind::Switchboard,
                feed_id,
                Some(config.feeds.switchboard_feed_timestamp_adjustment),
            )?;
        }
        if let Some(pyth_feed_id) = config.feeds.pyth_feed_id()? {
            builder = builder.update_price_feed(
                &PriceProviderKind::Pyth,
                pyth_feed_id,
                Some(config.feeds.pyth_feed_timestamp_adjustment),
            )?;
        }
        if let Some(feed_id) = config.feeds.chainlink_data_streams_feed_id()? {
            builder = builder.update_price_feed(
                &PriceProviderKind::ChainlinkDataStreams,
                feed_id,
                Some(
                    config
                        .feeds
                        .chainlink_data_streams_feed_timestamp_adjustment,
                ),
            )?;
        }
        Ok(builder)
    }
}

#[derive(Debug, clap::Args, serde::Serialize, serde::Deserialize)]
#[group(required = true, multiple = true)]
struct Feeds {
    /// Switchboard feed id.
    #[arg(long)]
    switchboard_feed_id: Option<String>,
    /// Switchboard feed timestamp adjustment.
    #[arg(long, default_value_t = DEFAULT_TIMESTAMP_ADJUSTMENT)]
    #[serde(default = "default_timestamp_adjustment")]
    switchboard_feed_timestamp_adjustment: u32,
    /// Pyth feed id.
    #[arg(long)]
    pyth_feed_id: Option<String>,
    /// Pyth feed timestamp adjustment.
    #[arg(long, default_value_t = DEFAULT_TIMESTAMP_ADJUSTMENT)]
    #[serde(default = "default_timestamp_adjustment")]
    pyth_feed_timestamp_adjustment: u32,
    /// Chainlink Data Streams feed id.
    #[arg(long)]
    chainlink_data_streams_feed_id: Option<String>,
    #[arg(long, default_value_t = DEFAULT_TIMESTAMP_ADJUSTMENT)]
    #[serde(default = "default_timestamp_adjustment")]
    chainlink_data_streams_feed_timestamp_adjustment: u32,
}

fn default_timestamp_adjustment() -> u32 {
    DEFAULT_TIMESTAMP_ADJUSTMENT
}

impl Feeds {
    fn pyth_feed_id(&self) -> eyre::Result<Option<Pubkey>> {
        let Some(pyth_feed_id) = self.pyth_feed_id.as_ref() else {
            return Ok(None);
        };
        let feed_id_as_key = Pubkey::new_from_array(parse_hex_encoded_feed_id(pyth_feed_id)?);
        Ok(Some(feed_id_as_key))
    }

    fn chainlink_data_streams_feed_id(&self) -> eyre::Result<Option<Pubkey>> {
        let Some(feed_id) = self.chainlink_data_streams_feed_id.as_ref() else {
            return Ok(None);
        };

        let feed_id_as_key = Pubkey::new_from_array(parse_hex_encoded_feed_id(feed_id)?);
        Ok(Some(feed_id_as_key))
    }

    fn switchboard_feed_id(&self) -> eyre::Result<Option<Pubkey>> {
        let Some(feed_id) = self.switchboard_feed_id.as_ref() else {
            return Ok(None);
        };
        let feed_id_as_key = feed_id.parse()?;
        Ok(Some(feed_id_as_key))
    }
}

fn insert_token_configs<'a>(
    client: &'a CommandClient,
    token_map: &Pubkey,
    set_token_map: bool,
    configs: &IndexMap<String, TokenConfig>,
    options: BundleOptions,
) -> eyre::Result<BundleBuilder<'a, LocalSignerRef>> {
    let store = &client.store;
    let mut bundle = client.bundle_with_options(options);

    if set_token_map {
        bundle.push(client.set_token_map(store, token_map))?;
    }

    for (name, config) in configs {
        let token = &config.address;
        if let Some(decimals) = config.synthetic {
            bundle.push(client.insert_synthetic_token_config(
                store,
                token_map,
                name,
                token,
                decimals,
                config.try_into()?,
                config.enable,
                !config.update,
            ))?;
        } else {
            bundle.push(client.insert_token_config(
                store,
                token_map,
                name,
                token,
                config.try_into()?,
                config.enable,
                !config.update,
            ))?;
        }
    }

    Ok(bundle)
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct CreateMarket {
    index_token: StringPubkey,
    long_token: StringPubkey,
    short_token: StringPubkey,
}

async fn create_markets<'a>(
    client: &'a CommandClient,
    enable: bool,
    markets: &IndexMap<String, CreateMarket>,
    options: BundleOptions,
) -> eyre::Result<BundleBuilder<'a, LocalSignerRef>> {
    let store = &client.store;
    let mut bundle = client.bundle_with_options(options);
    let token_map = token_map_address(client, None).await?;
    let mut tokens = IndexMap::with_capacity(markets.len());
    for (name, market) in markets {
        let (rpc, token) = client
            .create_market(
                store,
                name,
                &market.index_token,
                &market.long_token,
                &market.short_token,
                enable,
                Some(&token_map),
            )
            .await?;
        tracing::info!("Adding instruction to create market `{name}` with token={token}");
        tokens.insert(name, token);
        bundle.push(rpc)?;
    }

    for (name, token) in tokens {
        println!("{name}: {token}");
    }

    Ok(bundle)
}

fn parse_hex_encoded_feed_id(feed_id: &str) -> eyre::Result<[u8; 32]> {
    let feed_id = feed_id.strip_prefix("0x").unwrap_or(feed_id);

    let mut bytes = [0; 32];
    hex::decode_to_slice(feed_id, &mut bytes)?;

    Ok(bytes)
}

#[derive(Debug, serde::Deserialize)]
struct TokenMetadatas(IndexMap<StringPubkey, TokenMetadata>);

#[derive(Debug, serde::Deserialize)]
struct TokenMetadata {
    name: String,
    symbol: String,
    uri: String,
    #[serde(default)]
    init: bool,
}

#[derive(Debug, serde::Serialize)]
struct SerdeVirtualInventory {
    index: u32,
    long_amount: Amount,
    short_amount: Amount,
    is_enabled: bool,
    ref_count: u32,
    long_decimals: u8,
    short_decimals: u8,
    for_swaps: bool,
}

impl SerdeVirtualInventory {
    fn new(address: &Pubkey, vi: &VirtualInventory) -> gmsol_sdk::Result<Self> {
        use gmsol_sdk::programs::gmsol_store::ID;

        let pool = &vi.pool.pool;
        let for_swaps =
            find_virtual_inventory_for_swaps_address(&vi.store, vi.index, &ID).0 == *address;
        let is_enabled = !vi.flags.get_flag(VirtualInventoryFlag::Disabled);
        Ok(Self {
            index: vi.index,
            long_amount: Amount::from_u128(pool.long_token_amount, vi.long_amount_decimals)?,
            short_amount: Amount::from_u128(pool.short_token_amount, vi.short_amount_decimals)?,
            is_enabled,
            ref_count: vi.ref_count,
            long_decimals: vi.long_amount_decimals,
            short_decimals: vi.short_amount_decimals,
            for_swaps,
        })
    }
}