aspens 0.8.0

Aspens crosschain trading SDK
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
// `Display` impls + the inherent CLI-formatting helpers on the proto
// types live next door in `display.rs` so this file can focus on the
// call / signing logic.
mod display;

use super::arborter_pb;
use crate::chain_client::named_chain_for;
use crate::wallet::Wallet;
use alloy::primitives::{Address, U256};
use alloy::providers::{Provider, ProviderBuilder};
use arborter_pb::arborter_service_client::ArborterServiceClient;
use arborter_pb::{Order, SendOrderRequest, SendOrderResponse};
use eyre::Result;
use url::Url;

use crate::commands::config::config_pb::GetConfigResponse;
use crate::evm::rpc::MidribV3;
use crate::grpc::create_channel;

/// The two things the send path derives from one set of inputs: the `Order`
/// that gets signed, and the caller's own copy of the id derived over it.
///
/// They are built together, in [`prepare_order`], because they must agree.
/// The commitment is not transmitted — the arborter derives the id and the
/// budget from the signed `Order` — so agreement is not a courtesy:
/// `order.nonce` is an input to the recipe, and a `PreparedOrder` whose
/// two halves disagree about it is one where the caller tracks an id the venue
/// never issues, with nothing on the wire to reveal the split.
#[cfg_attr(test, derive(Debug))]
pub(crate) struct PreparedOrder {
    /// Exactly the bytes the envelope signature is taken over, once encoded.
    pub order: Order,
    /// The locally derived `order_id`, the budget it was derived over, and the
    /// nonce — which is `order.nonce` above, by construction.
    pub commitment: crate::commands::trading::gasless::OrderCommitment,
}

/// Resolve the order's budget, derive its id, and build the `Order` that
/// carries them — all pure, no I/O, so the whole shape is testable.
#[allow(clippy::too_many_arguments)]
pub(crate) fn prepare_order(
    config: &GetConfigResponse,
    market: &crate::commands::config::config_pb::Market,
    side: i32,
    quantity_raw: String,
    price_raw: Option<String>,
    base_account_address: String,
    quote_account_address: String,
    signing_wallet: &Wallet,
    post_only: bool,
    hidden: bool,
    quote_budget_raw: Option<String>,
    match_order_ids: Vec<[u8; 32]>,
) -> Result<PreparedOrder> {
    // ONE nonce, bound to two uses: hashed into the order id below, and signed
    // as `Order.nonce` further down. The arborter re-derives the id from the
    // order it verified, so these must be the same `u64` — mint it twice and
    // the two ids differ with nothing on the wire to say so.
    let nonce = super::gasless::client_nonce()?;
    // The venue session to sign: the arborter opens a new one every boot and
    // refuses an order for any other, so nothing signed before a restart is
    // placed after it.
    let session = config
        .config
        .as_ref()
        .ok_or_else(|| eyre::eyre!("GetConfig returned no configuration"))?
        .session;

    // The budget the arborter will reserve, and the id derived over it. This
    // is also where a budget on the wrong cell (or a missing one on a market
    // bid) is refused, before anything is signed.
    let commitment = super::gasless::build_order_commitment(
        config,
        market,
        side,
        signing_wallet,
        &quantity_raw,
        price_raw.as_deref(),
        quote_budget_raw.as_deref(),
        nonce,
    )?;

    // The order carries the original pair-decimal values.
    // `post_only=false` is the proto3 default and is wire-skipped on encode,
    // so existing callers' signed envelopes are byte-identical to pre-feature
    // builds; only true post-only orders change the envelope digest (which
    // arborter's signature check transparently honors — same encoded bytes
    // hashed on both sides).
    //
    // `quote_budget` (field 11) is the same story: `None` emits nothing, so
    // every order that isn't a market bid signs the exact bytes it always did.
    // Note the units differ from `quantity`/`price` — it is the QUOTE token's
    // own base units, not pair decimals (see `Order.quote_budget`).
    //
    // `match_order_ids` (field 8) drives `execution_type` (field 7) rather
    // than being independently settable: a dealroom discretionary fill IS
    // "match against these ids and nothing else", so the two travel together
    // by construction instead of by a caller remembering to set both. Empty
    // is wire-skipped on both fields, so every existing (non-dealroom) caller
    // signs the exact bytes it always did.
    let order = Order {
        side,
        quantity: quantity_raw,
        price: price_raw,
        market_id: market.market_id.clone(),
        base_account_address,
        quote_account_address,
        execution_type: if match_order_ids.is_empty() {
            0
        } else {
            arborter_pb::ExecutionType::Discretionary as i32
        },
        matching_order_ids: match_order_ids.iter().map(|id| id.to_vec()).collect(),
        post_only,
        hidden,
        quote_budget: quote_budget_raw,
        // The same `u64` the id was hashed over, three lines up. It is signed
        // here so the arborter can reproduce that hash from the message it
        // verified — which is the whole reason a caller sends no id.
        nonce,
        // Signed, but not part of the id derivation.
        session,
    };

    Ok(PreparedOrder { order, commitment })
}

/// Two spellings of one address, judged by the chain's rules: EVM hex is
/// case-insensitive, base58 is not.
fn same_address(architecture: &str, a: &str, b: &str) -> bool {
    if architecture.eq_ignore_ascii_case(crate::chain_client::ARCH_SOLANA) {
        a == b
    } else {
        a.eq_ignore_ascii_case(b)
    }
}

/// Decide the two `Order` account addresses — the per-chain settlement
/// addresses — from the leg wallets and the caller's optional overrides.
///
/// - No override → the wallet's own address on that leg (the long-standing
///   default; existing callers are byte-identical).
/// - The GIVE leg (bid → quote, ask → base) is the address the arborter
///   verifies the envelope signature against and draws collateral from. An
///   override there may only restate the signing wallet's own address —
///   anything else would fail signature verification at the venue, so it
///   is refused here, before signing, with an explanation instead of a
///   round-trip later.
/// - The RECEIVE leg is where fill proceeds settle, and the venue credits
///   whatever well-formed string the signed order carries. An override
///   there is "settle to a different address": validated for the leg's
///   chain architecture (`crate::orders::validate_settle_address`), and
///   kept byte-verbatim — the caller's spelling is what gets signed.
///
/// What this cannot check: that anyone holds the key to a redirected
/// address. The venue has no address registry, and funds credited there
/// are withdrawable only by that key's holder. Callers presenting this to
/// users should say so.
fn resolve_leg_addresses(
    base_architecture: &str,
    quote_architecture: &str,
    base_wallet: &Wallet,
    quote_wallet: &Wallet,
    side: i32,
    base_override: Option<String>,
    quote_override: Option<String>,
) -> Result<(String, String)> {
    let give_is_quote = side == 1; // Bid gives quote; Ask gives base.
    let resolve = |leg: &str,
                   architecture: &str,
                   wallet: &Wallet,
                   chosen: Option<String>,
                   is_give: bool|
     -> Result<String> {
        let Some(addr) = chosen else {
            return Ok(wallet.address());
        };
        crate::orders::validate_settle_address(architecture, &addr)
            .map_err(|e| eyre::eyre!("{leg} address override rejected: {e}"))?;
        if is_give && !same_address(architecture, &addr, &wallet.address()) {
            return Err(eyre::eyre!(
                "the {leg} leg is what this order GIVES: the venue verifies the envelope \
                 signature against that address and draws collateral from it, so it must be \
                 the signing wallet's own address {} (got '{addr}'). To settle proceeds to a \
                 different address, override the receiving leg instead",
                wallet.address()
            ));
        }
        Ok(addr)
    };
    Ok((
        resolve(
            "base",
            base_architecture,
            base_wallet,
            base_override,
            !give_is_quote,
        )?,
        resolve(
            "quote",
            quote_architecture,
            quote_wallet,
            quote_override,
            give_is_quote,
        )?,
    ))
}

// Internal RPC dispatcher: signs the prepared order and sends it.
async fn call_send_order(
    url: String,
    order_for_sending: Order,
    wallet: &Wallet,
) -> Result<SendOrderResponse> {
    // Create a channel to connect to the gRPC server (with TLS support for HTTPS)
    let channel = create_channel(&url).await?;

    // Instantiate the client
    let mut client = ArborterServiceClient::new(channel);

    // Encode + sign the order via the shared helper (the single sign site so
    // the gRPC and FCE paths produce byte-identical envelopes). EVM signatures
    // are 65 bytes (r||s||v); Solana Ed25519 are 64 — the arborter's curve-aware
    // verifier requires exactly those lengths, so send the full curve-native
    // length with no truncation.
    let signature_bytes = super::sign_encoded(&order_for_sending, wallet).await?;

    // Create the request with the original order and signature. That pair is
    // the whole request: the budget and the order id are derived by the
    // arborter from the signed order below, so nothing may accompany it
    // outside the signature.
    let request = SendOrderRequest {
        order: Some(order_for_sending),
        signature_hash: signature_bytes,
    };

    // Create a tonic request
    let request = tonic::Request::new(request);

    // Call the send_order endpoint. A "session changed" refusal means the
    // venue restarted after `config` was fetched: nothing was placed, and a
    // NEW order signed for the new session is the way on — never these bytes.
    let response = client.send_order(request).await.map_err(|s| {
        if s.code() == tonic::Code::FailedPrecondition && s.message().starts_with("session changed")
        {
            eyre::eyre!(
                "{} — the venue restarted since the configuration was fetched; fetch it again \
                 (AspensClient::fetch_config) and send a new order",
                s.message()
            )
        } else {
            eyre::Report::new(s)
        }
    })?;

    // Get the response data
    let response_data = response.into_inner();

    // Print the response from the server
    tracing::info!("Response received: {}", response_data);

    Ok(response_data)
}

/// Query deposited (available) balance for a token on a specific chain
async fn query_deposited_balance(
    rpc_url: &str,
    token_address: &str,
    contract_address: &str,
    user_address: Address,
    chain_id: u32,
) -> Result<U256> {
    let contract_addr: Address = contract_address.parse()?;
    let token_addr: Address = token_address.parse()?;
    let rpc_url = Url::parse(rpc_url)?;

    // Chain metadata only when alloy knows the id; `tradeBalance` is a plain
    // eth_call and needs none, and an id outside alloy's registry (HyperEVM
    // testnet 998, anvil, a new rollup) must not fall back to another chain's
    // provider config.
    let provider = match named_chain_for(chain_id as u64) {
        Some(named) => ProviderBuilder::new()
            .with_chain(named)
            .connect_http(rpc_url)
            .erased(),
        None => ProviderBuilder::new().connect_http(rpc_url).erased(),
    };
    let contract = MidribV3::new(contract_addr, &provider);
    let result = contract
        .tradeBalance(user_address, token_addr)
        .call()
        .await?;
    Ok(result)
}

/// Format a U256 balance with decimals for display
fn format_balance_for_display(balance: U256, decimals: u32) -> String {
    let balance_u128: u128 = balance.try_into().unwrap_or(u128::MAX);
    let divisor = 10_u128.pow(decimals);
    let integer_part = balance_u128 / divisor;
    let fractional_part = balance_u128 % divisor;
    format!(
        "{}.{:0width$}",
        integer_part,
        fractional_part,
        width = decimals as usize
    )
}

/// Convert a human-readable amount (e.g., `"1.001"`) to pair decimals format
/// as a decimal string suitable for the gRPC payload.
///
/// Thin wrapper over [`crate::decimals::parse_decimal_amount`]; kept as
/// a private alias so the existing `String`-returning order-encoding path
/// stays untouched.
pub(crate) fn convert_to_pair_decimals(amount: &str, decimals: u32) -> Result<String> {
    Ok(crate::decimals::parse_decimal_amount(amount, decimals)?.to_string())
}

/// Scale a human-readable quote budget (e.g. `"250.5"`) into the decimal
/// string `Order.quote_budget` carries.
///
/// **Not pair decimals.** `quote_budget` is denominated in the QUOTE TOKEN's
/// own base units, and the arborter converts the wire value back with
/// `market.quote_chain_token_decimals` (`get_market_decimals` →
/// `quote_budget_in_pair_units`). Scaling here with any other number — pair
/// decimals, the base token's decimals — would commit a budget orders of
/// magnitude away from the one the user typed, on every market where those
/// differ. So this reads the same field the arborter does.
pub(crate) fn quote_budget_to_raw(
    market: &crate::commands::config::config_pb::Market,
    budget: &str,
) -> Result<String> {
    let decimals = u32::try_from(market.quote_chain_token_decimals).map_err(|_| {
        eyre::eyre!(
            "market '{}' has a negative quote_chain_token_decimals ({})",
            market.name,
            market.quote_chain_token_decimals
        )
    })?;
    let raw = crate::decimals::parse_decimal_amount(budget, decimals)
        .map_err(|e| eyre::eyre!("Invalid quote budget '{}': {}", budget, e))?;
    Ok(raw.to_string())
}

/// Look up a market from the configuration
///
/// Supports multiple formats:
/// - Shorthand: `base_network/base_symbol::quote_network/quote_symbol`
///   e.g. `flare-coston2/fXRP::flare-coston2-quote/USDT0`
/// - Full market ID: `base_network::token_address::quote_network::token_address`
/// - Market name: e.g. `Base Sepolia USDC - OP Sepolia USDC`
///
/// Returns the market info or an error listing available markets.
pub fn lookup_market<'a>(
    config: &'a GetConfigResponse,
    market_id: &str,
) -> Result<&'a crate::commands::config::config_pb::Market> {
    // Strip surrounding quotes if present (e.g. from shell env vars)
    let market_id = market_id.trim_matches('"').trim_matches('\'');

    // Try shorthand format: base_network/symbol::quote_network/symbol
    if let Some((base, quote)) = market_id.split_once("::")
        && let (Some((base_network, base_symbol)), Some((quote_network, quote_symbol))) =
            (base.split_once('/'), quote.split_once('/'))
        && let Some(market) =
            config.get_market_by_tokens(base_network, base_symbol, quote_network, quote_symbol)
    {
        return Ok(market);
    }

    // Try exact market_id match
    if let Some(market) = config.get_market_by_id(market_id) {
        return Ok(market);
    }

    // Try market name match
    if let Some(market) = config.get_market(market_id) {
        return Ok(market);
    }

    let available_markets = config
        .config
        .as_ref()
        .map(|c| {
            c.markets
                .iter()
                .map(|m| {
                    format!(
                        "{}/{}::{}/{}",
                        m.base_chain_network,
                        m.base_chain_token_symbol,
                        m.quote_chain_network,
                        m.quote_chain_token_symbol
                    )
                })
                .collect::<Vec<_>>()
                .join(", ")
        })
        .unwrap_or_default();
    Err(eyre::eyre!(
        "Market '{}' not found in configuration. Available markets: {}",
        market_id,
        available_markets
    ))
}

/// Resolve the origin chain network for a (market, side) pair — the chain
/// where the user signs their lock instruction.
///
/// Mirrors `gasless::resolve_order`'s side logic. The CLI and REPL
/// `cancel-order` commands call this directly to pick which chain's wallet
/// (and therefore which curve) signs the cancel:
/// - `Side::Bid` (BUY) locks the quote token → origin = quote chain
/// - `Side::Ask` (SELL) locks the base token → origin = base chain
///
/// Returns `Side::Unspecified` as an error since the origin is undefined.
pub fn origin_network_for_side<'a>(
    config: &'a GetConfigResponse,
    market_id: &str,
    side: arborter_pb::Side,
) -> Result<&'a str> {
    let market = lookup_market(config, market_id)?;
    Ok(match side {
        arborter_pb::Side::Bid => &market.quote_chain_network,
        arborter_pb::Side::Ask => &market.base_chain_network,
        arborter_pb::Side::Unspecified => {
            return Err(eyre::eyre!("Side::Unspecified has no origin chain"));
        }
    })
}

/// Parse a string side ("buy"/"bid" or "sell"/"ask", case-insensitive) into
/// the typed enum. Used by binaries that take side as a CLI / REPL arg;
/// useful as a single source of truth for accepted aliases.
pub fn parse_side(s: &str) -> Result<arborter_pb::Side> {
    match s.to_lowercase().as_str() {
        "buy" | "bid" => Ok(arborter_pb::Side::Bid),
        "sell" | "ask" => Ok(arborter_pb::Side::Ask),
        other => Err(eyre::eyre!(
            "invalid side '{}' (expected 'buy'/'bid' or 'sell'/'ask')",
            other
        )),
    }
}

/// Send an order using a curve-agnostic wallet.
///
/// Thin wrapper over [`send_order_with_wallets`] for the common case where
/// both legs of the market live on chains that share the same curve as the
/// supplied wallet (e.g. EVM↔EVM with an EVM wallet). For cross-chain
/// markets that span Secp256k1 + Ed25519 chains, callers must use
/// `send_order_with_wallets` and supply both wallets.
///
/// # Arguments
/// * `url` - The Aspens Market Stack URL
/// * `market_id` - The market identifier
/// * `side` - Order side (1 for BUY, 2 for SELL)
/// * `quantity` - The quantity to trade (human-readable, e.g., "1.5")
/// * `price` - Optional limit price (human-readable, e.g., "100.50")
/// * `wallet` - The user's wallet (EVM or Solana)
/// * `config` - The configuration response from the server
/// * `post_only` - Reject if the order would cross at submission. Limit
///   orders only; ignored semantics-wise for market orders (arborter
///   rejects post-only without a price).
/// * `hidden` - Invisible order: matched normally (normal price-time
///   priority) but excluded from the public orderbook stream and
///   response-embedded books; appears in NO stream, not even your own —
///   track it via `SendOrderResponse.order_id`. Fills print publicly
///   with your side's identity redacted.
/// * `quote_budget` - The maximum QUOTE to spend, human-readable (e.g.
///   "250.5"), scaled here by the market's quote-token decimals.
///   **Required for a market buy** (`side == 1` with no `price`) and
///   rejected on every other order — see [`send_order_with_wallets`].
/// * `match_order_ids` - Dealroom discretionary fill: non-empty sets
///   `Order.execution_type = DISCRETIONARY` and carries these ids as
///   `Order.matching_order_ids` — see [`send_order_with_wallets`].
// Public top-level API — the argument list is the documented entry
// point; introducing a builder/struct here would break every caller
// (CLI, REPL, examples) for no behavioural gain.
#[allow(clippy::too_many_arguments)]
pub async fn send_order_with_wallet(
    url: String,
    market_id: String,
    side: i32,
    quantity: String,
    price: Option<String>,
    wallet: &Wallet,
    config: GetConfigResponse,
    post_only: bool,
    hidden: bool,
    quote_budget: Option<String>,
    match_order_ids: Vec<[u8; 32]>,
    base_address: Option<String>,
    quote_address: Option<String>,
) -> Result<SendOrderResponse> {
    send_order_with_wallets(
        url,
        market_id,
        side,
        quantity,
        price,
        &[wallet],
        config,
        post_only,
        hidden,
        quote_budget,
        match_order_ids,
        base_address,
        quote_address,
    )
    .await
}

/// Send an order with one or more wallets, picking the right curve per chain.
///
/// Cross-chain orders need separate user-addresses on the base and quote
/// chains, which may use different curves (e.g. an EVM ↔ Solana market needs
/// both an EVM hex address and a Solana base58 pubkey). Pass all available
/// wallets in `wallets`; the function selects the matching curve for each
/// leg of the market by reading chain architectures from `config`. The
/// origin chain's wallet (the side that commits tokens for this order)
/// signs the outer envelope.
///
/// Errors if a wallet of the right curve is missing for either chain.
///
/// `post_only`: see [`send_order_with_wallet`].
/// `hidden`: see [`send_order_with_wallet`]. No client-side validation —
/// hidden combines legally with market, limit, and post_only orders.
///
/// `quote_budget`: human-readable quote amount, scaled here by the market's
/// `quote_chain_token_decimals` — the SAME field the arborter reads the wire
/// value back with, so the two sides cannot disagree about what "250.5" meant.
/// One rule decides whether it is needed: **an order commits a budget,
/// denominated in the asset it gives.** A market buy gives quote and has no
/// price to size that with, so it must state the budget; a sell gives base
/// (`quantity` IS its budget) and a limit buy derives `quantity x price`, so
/// both reject a stated one. Note the budget bounds the spend — a market buy's
/// `quantity` bounds nothing, though it must still be non-zero and is still
/// signed.
///
/// `match_order_ids`: a dealroom discretionary fill. Non-empty (max 16) sets
/// `Order.execution_type = DISCRETIONARY` and carries the ids as
/// `Order.matching_order_ids` — both inside the signed envelope, so the
/// signature covers exactly which resting orders this one is allowed to
/// touch. The arborter then fills ONLY against those orders, at each maker's
/// own price gated by this order's limit price (required — a discretionary
/// order with no price is rejected), IOC: whatever doesn't fill against the
/// named ids is canceled, never rested. Empty is the normal (non-dealroom)
/// path and is wire-skipped, so existing callers sign byte-identical
/// envelopes. The arborter also rejects a `quote_budget` alongside a
/// non-empty list, `post_only` combined with it, ids on an order that isn't
/// discretionary, and an id that would self-match.
///
/// `base_address` / `quote_address`: optional overrides for the order's two
/// per-chain account addresses — the settlement addresses the venue credits
/// fill proceeds to. `None` (the default for every pre-existing caller)
/// uses each leg wallet's own address. The
/// contract: the GIVE leg may only restate the signing wallet's
/// address, the RECEIVE leg may name any well-formed address on that
/// leg's chain ("settle to a different address"), and nothing can verify
/// that anyone holds the key to a redirected address — funds credited
/// there are withdrawable only by that key's holder.
// Public top-level API — same rationale as `send_order_with_wallet`
// for keeping the argument list flat.
#[allow(clippy::too_many_arguments)]
pub async fn send_order_with_wallets(
    url: String,
    market_id: String,
    side: i32,
    quantity: String,
    price: Option<String>,
    wallets: &[&Wallet],
    config: GetConfigResponse,
    post_only: bool,
    hidden: bool,
    quote_budget: Option<String>,
    match_order_ids: Vec<[u8; 32]>,
    base_address: Option<String>,
    quote_address: Option<String>,
) -> Result<SendOrderResponse> {
    if wallets.is_empty() {
        return Err(eyre::eyre!(
            "send_order_with_wallets requires at least one wallet"
        ));
    }

    // Reject post-only without a price up front — arborter will reject it
    // anyway, but failing here saves a round-trip + signature work and
    // surfaces a clearer error to scripts.
    if post_only && price.is_none() {
        return Err(eyre::eyre!(
            "post_only is incompatible with market orders (no price); \
             pass an explicit limit price or set post_only=false"
        ));
    }

    // Look up market
    let market = lookup_market(&config, &market_id)?;
    let pair_decimals = market.pair_decimals as u32;

    // Convert amounts
    let quantity_raw = convert_to_pair_decimals(&quantity, pair_decimals)
        .map_err(|e| eyre::eyre!("Invalid quantity '{}': {}", quantity, e))?;
    let price_raw = price
        .as_ref()
        .map(|p| convert_to_pair_decimals(p, pair_decimals))
        .transpose()
        .map_err(|e| eyre::eyre!("Invalid price: {}", e))?;
    let quote_budget_raw = quote_budget
        .as_deref()
        .map(|b| quote_budget_to_raw(market, b))
        .transpose()?;

    // Pick the wallet whose curve matches each chain's architecture. The
    // SDK's `chain_curve` helper is the single source of truth for the
    // arch→curve mapping; using it here keeps order routing aligned with
    // deposit / balance / cancel flows.
    let base_chain = config
        .get_chain(&market.base_chain_network)
        .ok_or_else(|| eyre::eyre!("base chain '{}' not in config", market.base_chain_network))?;
    let quote_chain = config
        .get_chain(&market.quote_chain_network)
        .ok_or_else(|| eyre::eyre!("quote chain '{}' not in config", market.quote_chain_network))?;
    let base_curve = crate::wallet::chain_curve(base_chain);
    let quote_curve = crate::wallet::chain_curve(quote_chain);
    let base_wallet = wallets
        .iter()
        .copied()
        .find(|w| w.curve() == base_curve)
        .ok_or_else(|| {
            eyre::eyre!(
                "no wallet of curve {:?} available for base chain '{}'",
                base_curve,
                market.base_chain_network
            )
        })?;
    let quote_wallet = wallets
        .iter()
        .copied()
        .find(|w| w.curve() == quote_curve)
        .ok_or_else(|| {
            eyre::eyre!(
                "no wallet of curve {:?} available for quote chain '{}'",
                quote_curve,
                market.quote_chain_network
            )
        })?;

    // The signing wallet is whichever side locks for this order:
    //   Bid (BUY)  → origin = quote chain  → user locks quote
    //   Ask (SELL) → origin = base  chain  → user locks base
    let signing_wallet = if side == 1 { quote_wallet } else { base_wallet };

    // The two per-chain settlement addresses the signed order carries:
    // each leg wallet's own address unless overridden — see
    // `resolve_leg_addresses` for what an override may and may not do.
    let (base_account_address, quote_account_address) = resolve_leg_addresses(
        &base_chain.architecture,
        &quote_chain.architecture,
        base_wallet,
        quote_wallet,
        side,
        base_address,
        quote_address,
    )?;

    tracing::info!(
        "Sending order: market={}, side={}, quantity={} (raw: {}), price={:?} (raw: {:?}), \
         base_account={}, quote_account={}, signing_curve={:?}",
        market.name,
        if side == 1 { "BUY" } else { "SELL" },
        quantity,
        quantity_raw,
        price,
        price_raw,
        base_account_address,
        quote_account_address,
        signing_wallet.curve()
    );

    // Build what gets signed, plus the caller's own copy of the derived id.
    // Under the optimistic ledger the arborter authenticates via the outer
    // envelope signature alone — there is no per-order on-chain lock
    // signature, and nothing accompanies the order on the wire: the budget
    // and the order id are derived by the arborter from the signed `Order`;
    // the commitment below is kept locally, for tracking.
    let prepared = prepare_order(
        &config,
        market,
        side,
        quantity_raw.clone(),
        price_raw.clone(),
        base_account_address,
        quote_account_address,
        signing_wallet,
        post_only,
        hidden,
        quote_budget_raw,
        match_order_ids,
    )?;

    // The commitment above is this caller's own copy of the id, derived
    // locally; the response below carries the arborter's own derivation of
    // the same 32 bytes, computed from the order signed just after this log
    // line. Logging both is the caller's one link between "what I computed"
    // and "what the venue assigned" until the response returns.
    tracing::info!(
        "Derived order id {} (nonce {}, budget {} in the token it gives)",
        prepared.commitment.order_id,
        prepared.commitment.nonce,
        prepared.commitment.input_amount,
    );

    let result = call_send_order(url, prepared.order, signing_wallet).await;

    // Enhance balance errors with actual balance info (EVM only — Solana balance
    // queries via Alloy don't apply). Use the EVM-side wallet's address since
    // that's the one whose balance the helper actually queries on-chain.
    if let Err(ref e) = result {
        let err_str = e.to_string().to_lowercase();
        if (err_str.contains("insufficient") || err_str.contains("balance"))
            && let Some(evm_wallet) = wallets
                .iter()
                .copied()
                .find(|w| w.curve() == crate::wallet::CurveType::Secp256k1)
        {
            // Re-parse the EVM address for the balance enhancement helper.
            if let Ok(user_address) = evm_wallet.address().parse::<Address>()
                && let Some(enhanced) = enhance_balance_error(
                    &config,
                    market,
                    side,
                    &quantity_raw,
                    price_raw.as_deref(),
                    user_address,
                    pair_decimals,
                )
                .await
            {
                return Err(enhanced);
            }
        }
    }

    result
}

/// Try to provide a more helpful error message for balance issues
async fn enhance_balance_error(
    config: &GetConfigResponse,
    market: &crate::commands::config::config_pb::Market,
    side: i32,
    quantity_raw: &str,
    price_raw: Option<&str>,
    user_address: Address,
    pair_decimals: u32,
) -> Option<eyre::Report> {
    // BUY: need quote token, SELL: need base token
    let (chain_network, token_symbol, token_decimals) = if side == 1 {
        (
            &market.quote_chain_network,
            &market.quote_chain_token_symbol,
            market.quote_chain_token_decimals as u32,
        )
    } else {
        (
            &market.base_chain_network,
            &market.base_chain_token_symbol,
            market.base_chain_token_decimals as u32,
        )
    };

    let chain = config.get_chain(chain_network)?;
    let trade_contract = chain.trade_contract.as_ref()?;
    let token = chain.tokens.get(token_symbol)?;

    // The arborter masks rpc_url; this returns Option, so an unresolvable
    // endpoint degrades to "no balance shown" rather than a hard failure.
    let rpc = crate::chain_client::chain_rpc_url(chain).ok()?;
    let deposited_balance = query_deposited_balance(
        &rpc,
        &token.address,
        &trade_contract.address,
        user_address,
        chain.chain_id,
    )
    .await
    .ok()?;

    let deposited_formatted = format_balance_for_display(deposited_balance, token_decimals);

    // The figure has to end up in the TOKEN's native decimals, because that is
    // what `deposited_balance` is in and what `format_balance_for_display` is
    // told below. Handing a PAIR-decimal number straight to a native-decimal
    // comparison is wrong by orders of magnitude on any market where the two
    // differ (the WFLR/USDC shape the rest of this file guards against), which
    // would invent an "insufficient balance" that is not, or hide one that is.
    // This only decorates an error and cannot place a bad order — but a wrong
    // number in an error message is how someone diagnoses the wrong thing for
    // an afternoon.
    //
    // `normalize` is the same conversion the signing path uses, so this figure
    // and the one actually committed agree by construction rather than by two
    // implementations happening to match. The multiply is checked: an
    // unchecked `qty * prc` panics in debug and wraps in release — inside an
    // error handler, which is the worst place to find out.
    let required_amount = if side == 1 {
        // BUY: gives quote, needs quantity x price.
        let p = price_raw?;
        let qty: u128 = quantity_raw.parse().ok()?;
        let prc: u128 = p.parse().ok()?;
        let in_pair2 = qty.checked_mul(prc)?;
        let in_token =
            super::gasless::normalize(in_pair2, pair_decimals * 2, token_decimals).ok()?;
        Some(U256::from(in_token))
    } else {
        // SELL: gives base, needs quantity.
        let qty: u128 = quantity_raw.parse().ok()?;
        let in_token = super::gasless::normalize(qty, pair_decimals, token_decimals).ok()?;
        Some(U256::from(in_token))
    };

    // Only enhance if we can confirm the balance is actually insufficient
    let required = required_amount?;
    if deposited_balance >= required {
        return None;
    }

    let required_str = format_balance_for_display(required, token_decimals);

    Some(eyre::eyre!(
        "Insufficient deposited balance on {}.\n\
         Token: {}\n\
         Required: {} {}\n\
         Available: {} {}\n\n\
         Deposit more {} on {} before placing this order.",
        chain_network,
        token_symbol,
        required_str,
        token_symbol,
        deposited_formatted,
        token_symbol,
        token_symbol,
        chain_network
    ))
}

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

    #[test]
    fn test_send_order_response_order_id() {
        let response = SendOrderResponse {
            order_id: vec![0xaa, 0xbb, 0xcc],
            order_in_book: true,
            order: None,
            trades: vec![],
        };

        assert_eq!(response.order_id, vec![0xaa, 0xbb, 0xcc]);
    }

    #[test]
    fn test_send_order_response_order_id_empty() {
        let response = SendOrderResponse {
            order_id: vec![],
            order_in_book: false,
            order: None,
            trades: vec![],
        };

        assert!(response.order_id.is_empty());
    }

    #[test]
    fn test_send_order_response_order_id_full_32_bytes() {
        let id = vec![0xff; 32];
        let response = SendOrderResponse {
            order_id: id.clone(),
            order_in_book: true,
            order: None,
            trades: vec![],
        };

        assert_eq!(response.order_id, id);
    }

    #[test]
    fn test_send_order_response_display_includes_order_id() {
        let response = SendOrderResponse {
            order_id: vec![0x01, 0x23, 0x45, 0x67],
            order_in_book: true,
            order: None,
            trades: vec![],
        };

        let display_str = format!("{}", response);
        assert!(
            display_str.contains("order_id: 0x01234567"),
            "Display output should contain the hex order_id: {}",
            display_str
        );
    }

    #[test]
    fn test_send_order_response_with_order_and_order_id() {
        let order = Order {
            side: 1,
            quantity: "1000".to_string(),
            price: Some("50000".to_string()),
            market_id: "test_market".to_string(),
            base_account_address: "0x1234".to_string(),
            quote_account_address: "0x5678".to_string(),
            execution_type: 0,
            matching_order_ids: vec![],
            post_only: false,
            hidden: false,
            quote_budget: None,
            nonce: 0,
            session: 0,
        };

        let response = SendOrderResponse {
            order_id: vec![0x2a],
            order_in_book: true,
            order: Some(order),
            trades: vec![],
        };

        assert_eq!(response.order_id, vec![0x2a]);
        assert!(response.order.is_some());
        assert!(response.order_in_book);
    }

    #[test]
    fn test_convert_to_pair_decimals_integer() {
        // 6 decimals (like USDC)
        assert_eq!(convert_to_pair_decimals("1", 6).unwrap(), "1000000");
        assert_eq!(convert_to_pair_decimals("100", 6).unwrap(), "100000000");
        assert_eq!(convert_to_pair_decimals("0", 6).unwrap(), "0");
    }

    #[test]
    fn test_convert_to_pair_decimals_with_fraction() {
        // 6 decimals
        assert_eq!(convert_to_pair_decimals("1.5", 6).unwrap(), "1500000");
        assert_eq!(convert_to_pair_decimals("1.001", 6).unwrap(), "1001000");
        assert_eq!(convert_to_pair_decimals("0.5", 6).unwrap(), "500000");
        assert_eq!(convert_to_pair_decimals("0.000001", 6).unwrap(), "1");
    }

    #[test]
    fn test_convert_to_pair_decimals_truncates_extra_precision() {
        // 6 decimals - extra precision should be truncated
        assert_eq!(convert_to_pair_decimals("1.0000001", 6).unwrap(), "1000000");
        assert_eq!(convert_to_pair_decimals("1.1234567", 6).unwrap(), "1123456");
    }

    #[test]
    fn test_convert_to_pair_decimals_18_decimals() {
        // 18 decimals (like ETH)
        assert_eq!(
            convert_to_pair_decimals("1", 18).unwrap(),
            "1000000000000000000"
        );
        assert_eq!(
            convert_to_pair_decimals("0.1", 18).unwrap(),
            "100000000000000000"
        );
    }

    #[test]
    fn test_convert_to_pair_decimals_whitespace() {
        assert_eq!(convert_to_pair_decimals("  1.5  ", 6).unwrap(), "1500000");
    }

    // ----- quote_budget_to_raw: the scale that must NOT be pair decimals ---

    /// Base 18, quote 6, pair 8 — three different scales, so a budget scaled
    /// by the wrong one lands on a different integer and the assertions below
    /// can actually tell them apart.
    fn market_with_decimals(
        base_dec: i32,
        quote_dec: i32,
        pair_dec: i32,
    ) -> crate::commands::config::config_pb::Market {
        crate::commands::config::config_pb::Market {
            name: "BASE/QUOTE".into(),
            base_chain_network: "base-net".into(),
            quote_chain_network: "quote-net".into(),
            base_chain_token_symbol: "BASE".into(),
            quote_chain_token_symbol: "QUOTE".into(),
            base_chain_token_decimals: base_dec,
            quote_chain_token_decimals: quote_dec,
            pair_decimals: pair_dec,
            market_id: "base-net::0xbase::quote-net::0xquote".into(),
        }
    }

    /// `Order.quote_budget` is in the QUOTE token's own base units. The
    /// arborter reads it back with `market.quote_chain_token_decimals`, so
    /// scaling by pair decimals (10^8 here) or the base token's (10^18) would
    /// commit a budget 100x or 10^12x away from what the user typed — and
    /// nothing would report an error, because every one of those is a
    /// well-formed u128.
    #[test]
    fn quote_budget_scales_by_the_quote_tokens_decimals() {
        let market = market_with_decimals(18, 6, 8);
        assert_eq!(quote_budget_to_raw(&market, "7.5").unwrap(), "7500000");
        assert_eq!(quote_budget_to_raw(&market, "1").unwrap(), "1000000");
        // Pair decimals would have given 750000000; base decimals
        // 7500000000000000000. Neither is this.
        assert_ne!(quote_budget_to_raw(&market, "7.5").unwrap(), "750000000");
    }

    /// Same input, a market whose quote token has different decimals: the
    /// answer must follow the token, not a constant baked in here.
    #[test]
    fn quote_budget_follows_the_market_not_a_constant() {
        let six = market_with_decimals(18, 6, 8);
        let eighteen = market_with_decimals(6, 18, 8);
        assert_eq!(quote_budget_to_raw(&six, "7.5").unwrap(), "7500000");
        assert_eq!(
            quote_budget_to_raw(&eighteen, "7.5").unwrap(),
            "7500000000000000000"
        );
    }

    #[test]
    fn quote_budget_rejects_a_non_numeric_amount() {
        let market = market_with_decimals(18, 6, 8);
        assert!(quote_budget_to_raw(&market, "banana").is_err());
    }

    // ----- prepare_order: the budget must reach BOTH the signed order and
    //       the id derived alongside it -----------------------------------

    /// An anvil dev key — this is a signing-shape fixture, not a secret.
    const TEST_PRIVKEY: &str = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";

    fn prepared(
        side: i32,
        price_raw: Option<&str>,
        quote_budget_raw: Option<&str>,
    ) -> Result<PreparedOrder> {
        // base 18, quote 6, pair 8 — three different scales.
        let (config, market) =
            crate::commands::trading::gasless::tests::config_with_market(18, 6, 8);
        let wallet = Wallet::from_evm_hex(TEST_PRIVKEY).expect("test key parses");
        prepare_order(
            &config,
            &market,
            side,
            "100000000".to_string(), // 1.0 base at pair decimals 8
            price_raw.map(str::to_string),
            "0xbaseaccount".to_string(),
            "0xquoteaccount".to_string(),
            &wallet,
            false,
            false,
            quote_budget_raw.map(str::to_string),
            vec![],
        )
    }

    /// The order is signed for the session the configuration names — the one
    /// the arborter will compare it against.
    #[test]
    fn prepare_order_signs_the_configured_session() {
        let p = prepared(1, Some("2000000000"), None).expect("a limit bid prepares");
        assert_eq!(p.order.session, 4_242);
    }

    /// The budget has to land in TWO places at once: on the `Order` (where
    /// the envelope signature covers it and the arborter reserves against
    /// it) and in the id derived beside it. Dropping either one is silent —
    /// an order the arborter reads differently from the one that was signed.
    #[test]
    fn prepare_market_bid_carries_the_budget_into_order_and_id() {
        let p = prepared(1, None, Some("7500000")).expect("market bid with a budget");
        assert_eq!(p.order.quote_budget.as_deref(), Some("7500000"));
        assert_eq!(p.commitment.input_amount, 7_500_000);
        // And it survives encoding — this is what actually gets signed.
        let mut buf = Vec::new();
        prost::Message::encode(&p.order, &mut buf).unwrap();
        let decoded = <Order as prost::Message>::decode(&*buf).unwrap();
        assert_eq!(decoded.quote_budget.as_deref(), Some("7500000"));
    }

    /// The wire-pinning tests below prove the SHAPE (empty ids -> default
    /// enum + empty repeated field) by building `Order` literals directly.
    /// That never exercises `prepare_order`'s own
    /// `if match_order_ids.is_empty() { 0 } else { .. }` branch — every
    /// caller of `prepare_order` (the real construction path production
    /// code uses) could regress to always emitting `Discretionary`, or to
    /// writing an explicit `0`/`vec![]` in a way prost stops eliding, and a
    /// literal-only test would never notice. Every existing order's derived
    /// id and signature depends on the empty-ids encoding staying
    /// byte-identical to before this feature existed, so this drives the
    /// REAL function and compares its output — copying only the
    /// dynamically-minted `nonce` — against a hand-built `Order` written the
    /// old way (the two hardcoded lines this feature replaced).
    #[test]
    fn prepare_order_with_empty_match_ids_encodes_like_the_pre_feature_shape() {
        // side=Ask, price 3.0 — distinct from every other `prepared()` call
        // in this file, so a copy-paste mistake elsewhere can't make this
        // pass for the wrong reason.
        let p = prepared(2, Some("300000000"), None).expect("limit ask, no match ids");
        assert_eq!(
            p.order.execution_type, 0,
            "prepare_order's real branch must leave execution_type at the proto default"
        );
        assert!(
            p.order.matching_order_ids.is_empty(),
            "prepare_order's real branch must leave matching_order_ids empty"
        );

        let hand_built_pre_feature_shape = Order {
            side: p.order.side,
            quantity: p.order.quantity.clone(),
            price: p.order.price.clone(),
            market_id: p.order.market_id.clone(),
            base_account_address: p.order.base_account_address.clone(),
            quote_account_address: p.order.quote_account_address.clone(),
            execution_type: 0,
            matching_order_ids: vec![],
            post_only: p.order.post_only,
            hidden: p.order.hidden,
            quote_budget: p.order.quote_budget.clone(),
            nonce: p.order.nonce,
            session: p.order.session,
        };

        let mut buf_real = Vec::new();
        prost::Message::encode(&p.order, &mut buf_real).unwrap();
        let mut buf_hand_built = Vec::new();
        prost::Message::encode(&hand_built_pre_feature_shape, &mut buf_hand_built).unwrap();
        assert_eq!(
            buf_real, buf_hand_built,
            "prepare_order(match_order_ids: vec![]) must encode identically to the \
             pre-feature hand-built shape — any divergence changes the signed bytes, \
             and therefore the derived id and signature, of every existing (non-dealroom) order"
        );
    }

    /// Every other order sets no budget, so its encoding — and therefore its
    /// signature — is byte-for-byte what it was before the field existed.
    #[test]
    fn prepare_limit_order_sets_no_budget() {
        let p = prepared(1, Some("200000000"), None).expect("limit bid");
        assert_eq!(p.order.quote_budget, None);
        // Decoding back to `None` is exact proof no field-11 record was
        // written: an emitted-but-empty field would decode as `Some("")`.
        let mut buf = Vec::new();
        prost::Message::encode(&p.order, &mut buf).unwrap();
        let decoded = <Order as prost::Message>::decode(&*buf).unwrap();
        assert_eq!(decoded.quote_budget, None);
        // 1.0 base x 2.0 price = 2.0 quote, at the quote token's 6 decimals.
        assert_eq!(p.commitment.input_amount, 2_000_000);
    }

    /// The nonce has to land in the same two places, and this is the one
    /// function that puts it there. The arborter re-derives the id from the
    /// signed `Order`, so `order.nonce` and the nonce the commitment hashed
    /// must be one value: mint it twice and the client tracks an id the venue
    /// never issued, on an order the venue accepts without complaint.
    #[test]
    fn prepare_binds_one_nonce_to_the_order_and_the_id() {
        let p = prepared(1, Some("200000000"), None).expect("limit bid");
        assert_eq!(
            p.order.nonce, p.commitment.nonce,
            "the signed nonce and the hashed nonce must be the same u64"
        );
        // A real nonce, not a default left over from the proto — the SDK's is
        // millis since epoch, so anything plausible is far past this.
        assert!(
            p.order.nonce > 1_600_000_000_000,
            "expected millis-since-epoch, got {}",
            p.order.nonce
        );
        // And it survives encoding — this is what actually gets signed, and
        // what the arborter reads the nonce back off.
        let mut buf = Vec::new();
        prost::Message::encode(&p.order, &mut buf).unwrap();
        let decoded = <Order as prost::Message>::decode(&*buf).unwrap();
        assert_eq!(decoded.nonce, p.commitment.nonce);
    }

    /// Two calls must not share a nonce, or a wallet's repeated orders
    /// collide on one derived id and the second is refused as a replay. The
    /// millisecond clock is what separates them, so this also fails if the
    /// nonce is ever hardcoded.
    #[test]
    fn prepare_does_not_reuse_a_nonce_across_orders() {
        let first = prepared(1, Some("200000000"), None).expect("limit bid");
        // The clock has millisecond resolution; spin until it ticks rather
        // than sleeping, so the test neither flakes nor stalls.
        let start = std::time::Instant::now();
        let second = loop {
            let p = prepared(1, Some("200000000"), None).expect("limit bid");
            if p.order.nonce != first.order.nonce {
                break p;
            }
            assert!(
                start.elapsed() < std::time::Duration::from_secs(2),
                "nonce never advanced in 2s — it is not reading the clock"
            );
        };
        assert_ne!(first.commitment.order_id, second.commitment.order_id);
    }

    /// The refusals are enforced on the path that actually signs, not only in
    /// the resolver: a budget on a limit order, and a market bid with none.
    #[test]
    fn prepare_enforces_the_budget_rule() {
        let err = prepared(1, Some("200000000"), Some("7500000")).unwrap_err();
        assert!(err.to_string().contains("only for a MARKET bid"), "{err}");
        let err = prepared(1, None, None).unwrap_err();
        assert!(
            err.to_string().contains("must set Order.quote_budget"),
            "{err}"
        );
    }
}

#[cfg(test)]
mod order_flag_wire_pinning_tests {
    //! Wire-encoding pinning tests for the boolean `Order` flags
    //! (`post_only` = field 9, `hidden` = field 10).
    //!
    //! The envelope signature in `call_send_order` is computed over the
    //! prost-encoded Order proto, so two invariants must hold for every
    //! flag or signed orders silently fail arborter's verifier:
    //!
    //!   1. **flag = false is wire-skipped** (proto3 default scalars are
    //!      omitted), so pre-feature SDK users keep byte-for-byte the
    //!      same envelope digest they always had.
    //!   2. **flag = true actually reaches the wire** — if a build-script
    //!      regression dropped the field we'd silently send `false`
    //!      always, with no error.
    //!
    //! `assert_bool_flag_wire_pinned` proves both at once with a single
    //! exact-bytes comparison; add one call per future flag.

    use super::*;
    use prost::Message;

    /// All scalar/enum fields default; both flags false. A flag under
    /// test must be the highest-numbered non-default field so that its
    /// varint appends at the end of the encoding (prost emits fields in
    /// tag order).
    fn sample_order() -> Order {
        Order {
            side: 1,
            quantity: "1000".to_string(),
            price: Some("50000".to_string()),
            market_id: "base::0xaa::quote::0xbb".to_string(),
            base_account_address: "0xb".to_string(),
            quote_account_address: "0xq".to_string(),
            execution_type: 0,
            matching_order_ids: vec![],
            post_only: false,
            hidden: false,
            quote_budget: None,
            nonce: 0,
            session: 0,
        }
    }

    /// Pin a bool flag's wire behavior: encoding with the flag set must
    /// equal the plain encoding plus an appended `[tag, 1]` varint.
    /// That single equality proves both invariants — the tag byte cannot
    /// occur in the plain encoding (a `flag=false` field on the wire
    /// would make the buffers differ in place, not by a 2-byte append),
    /// and the flag genuinely reaches the wire when true.
    fn assert_bool_flag_wire_pinned(field_number: u32, set: impl Fn(&mut Order, bool)) {
        let mut plain = sample_order();
        set(&mut plain, false);
        let mut flagged = sample_order();
        set(&mut flagged, true);

        let mut buf_plain = Vec::new();
        plain.encode(&mut buf_plain).unwrap();
        let mut buf_flagged = Vec::new();
        flagged.encode(&mut buf_flagged).unwrap();

        // Varint wire type = 0, so the tag byte is (field_number << 3).
        let tag = u8::try_from(field_number << 3).expect("tag must fit one byte");
        let mut expected = buf_plain.clone();
        expected.extend_from_slice(&[tag, 1]);
        assert_eq!(
            buf_flagged, expected,
            "flag=true must encode as the plain bytes + appended [0x{tag:02x}, 0x01]"
        );

        // Round-trips preserve the flag in both states.
        assert_eq!(Order::decode(&*buf_plain).unwrap(), plain);
        assert_eq!(Order::decode(&*buf_flagged).unwrap(), flagged);
    }

    #[test]
    fn post_only_wire_pinned() {
        assert_bool_flag_wire_pinned(9, |o, v| o.post_only = v);
    }

    #[test]
    fn hidden_wire_pinned() {
        assert_bool_flag_wire_pinned(10, |o, v| o.hidden = v);
    }

    /// A dealroom order signs what it names: non-empty match ids must flip
    /// execution_type to DISCRETIONARY and ride field 8 — and the encoded bytes
    /// must differ from the same order without them (the signature covers both).
    ///
    /// The two fixture ids are full 32 bytes, deliberately NOT sharing a byte
    /// pattern (one built from an ascending run, the other descending), so a
    /// bug that only copied a prefix or a single byte would still show up as
    /// a mismatch below rather than an accidental pass.
    #[test]
    fn match_order_ids_set_discretionary_and_change_the_signed_bytes() {
        let id_a: [u8; 32] = std::array::from_fn(|i| i as u8);
        let id_b: [u8; 32] = std::array::from_fn(|i| 255 - i as u8);

        let plain = sample_order();
        assert_eq!(
            plain.execution_type, 0,
            "fixture must start from the default"
        );
        assert!(
            plain.matching_order_ids.is_empty(),
            "fixture must start from the default"
        );

        let mut discretionary = sample_order();
        discretionary.execution_type = arborter_pb::ExecutionType::Discretionary as i32;
        discretionary.matching_order_ids = vec![id_a.to_vec(), id_b.to_vec()];

        let mut buf_plain = Vec::new();
        plain.encode(&mut buf_plain).unwrap();
        let mut buf_discretionary = Vec::new();
        discretionary.encode(&mut buf_discretionary).unwrap();

        // The whole point: these two orders must NOT encode to the same
        // bytes, or the envelope signature would cover nothing about which
        // resting orders this one is allowed to touch.
        assert_ne!(
            buf_plain, buf_discretionary,
            "matching_order_ids and execution_type must reach the wire — an \
             unchanged encoding means the signature does not cover them"
        );

        // Round-trips preserve both fields exactly, in both states.
        let decoded_plain = Order::decode(&*buf_plain).unwrap();
        assert_eq!(decoded_plain.execution_type, 0);
        assert!(decoded_plain.matching_order_ids.is_empty());

        let decoded_discretionary = Order::decode(&*buf_discretionary).unwrap();
        assert_eq!(
            decoded_discretionary.execution_type,
            arborter_pb::ExecutionType::Discretionary as i32
        );
        assert_eq!(
            decoded_discretionary.matching_order_ids,
            vec![id_a.to_vec(), id_b.to_vec()]
        );
    }

    /// `Order.nonce` (field 12), the same two invariants as the bool flags —
    /// but it matters more here, because two transports disagree about it.
    ///
    ///   1. **nonce = 0 is wire-skipped.** The FCE direct-action wire has no
    ///      nonce field, so the adapter rebuilds `Order` with the default and
    ///      the arborter verifies THOSE bytes. `fce_actions::FCE_ORDER_NONCE`
    ///      is zero for exactly this reason, and it only works while a zero
    ///      nonce encodes to nothing.
    ///   2. **a non-zero nonce reaches the wire.** The arborter re-derives the
    ///      order id from this field; drop it on encode and the client's id and
    ///      the venue's diverge with no error anywhere.
    #[test]
    fn nonce_wire_pinned() {
        let plain = sample_order(); // nonce = 0
        assert_eq!(plain.nonce, 0, "fixture must start from the default");
        let mut nonced = sample_order();
        // 300 needs a two-byte varint (0xac 0x02), so a truncating or
        // single-byte encode fails here rather than passing on a small value.
        nonced.nonce = 300;

        let mut buf_plain = Vec::new();
        plain.encode(&mut buf_plain).unwrap();
        let mut buf_nonced = Vec::new();
        nonced.encode(&mut buf_nonced).unwrap();

        // Field 12, varint wire type 0 → tag byte 12 << 3 = 0x60.
        let mut expected = buf_plain.clone();
        expected.extend_from_slice(&[0x60, 0xac, 0x02]);
        assert_eq!(
            buf_nonced, expected,
            "nonce=300 must encode as the plain bytes + appended [0x60, 0xac, 0x02]"
        );

        assert_eq!(Order::decode(&*buf_plain).unwrap(), plain);
        assert_eq!(Order::decode(&*buf_nonced).unwrap(), nonced);
    }

    /// The concrete claim `FCE_ORDER_NONCE` rests on: an order carrying the
    /// FCE nonce encodes to the same bytes as one built without the field at
    /// all — which is what the adapter, whose vendored `Order` has no nonce,
    /// hands the arborter to verify.
    #[test]
    #[cfg(feature = "fce")]
    fn fce_nonce_encodes_to_the_adapters_rebuild() {
        use crate::commands::trading::fce_actions::FCE_ORDER_NONCE;

        let mut signed_here = sample_order();
        signed_here.nonce = FCE_ORDER_NONCE;
        // The adapter's vendored `Order` has no nonce field, so whatever it
        // builds leaves this at the proto default — pin that, don't inherit it
        // from the fixture.
        let mut rebuilt_there = sample_order();
        rebuilt_there.nonce = 0;

        let mut a = Vec::new();
        signed_here.encode(&mut a).unwrap();
        let mut b = Vec::new();
        rebuilt_there.encode(&mut b).unwrap();
        assert_eq!(
            a, b,
            "FCE_ORDER_NONCE must be the value that vanishes on encode, or every \
             order sent over FCE fails the arborter's signature check"
        );
    }
}

#[cfg(test)]
mod leg_address_tests {
    //! `resolve_leg_addresses` decides the two `Order` account addresses —
    //! the per-chain settlement addresses — from the wallets and the
    //! caller's optional overrides.
    //!
    //! The contract under test:
    //! - No override → the wallet's own address on that leg (the behavior
    //!   every existing caller relies on).
    //! - The GIVE leg (bid → quote, ask → base) is the address the arborter
    //!   verifies the envelope signature against and draws collateral from,
    //!   so an override there may only restate the signing wallet's own
    //!   address; anything else is refused before signing rather than
    //!   bounced by the venue one round-trip later.
    //! - The RECEIVE leg is where proceeds settle. An override there is the
    //!   "settle to a different address" feature, and is validated for the
    //!   leg's chain architecture — the venue credits the string verbatim,
    //!   and a typo is stranded funds.

    use super::*;

    /// An anvil dev key — a signing-shape fixture, not a secret.
    const TEST_PRIVKEY: &str = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";

    fn evm_wallet() -> Wallet {
        Wallet::from_evm_hex(TEST_PRIVKEY).expect("test key parses")
    }

    /// A second, distinct EVM address in valid EIP-55 casing (computed, so
    /// the fixture can't carry a hand-typed bad checksum).
    fn other_evm() -> String {
        "0x00000000000000000000000000000000feedbeef"
            .parse::<alloy::primitives::Address>()
            .unwrap()
            .to_checksum(None)
    }

    const BID: i32 = 1;
    const ASK: i32 = 2;

    #[test]
    fn defaults_to_the_wallets_addresses() {
        let w = evm_wallet();
        for side in [BID, ASK] {
            let (b, q) = resolve_leg_addresses("evm", "evm", &w, &w, side, None, None)
                .expect("no overrides is the pre-feature path");
            assert_eq!(b, w.address());
            assert_eq!(q, w.address());
        }
    }

    #[test]
    fn receive_leg_override_redirects_settlement() {
        let w = evm_wallet();
        // An ASK gives base and receives quote: the quote address is free.
        let (b, q) =
            resolve_leg_addresses("evm", "evm", &w, &w, ASK, None, Some(other_evm())).unwrap();
        assert_eq!(b, w.address());
        assert_eq!(q, other_evm());
        // A BID gives quote and receives base: the base address is free.
        let (b, q) =
            resolve_leg_addresses("evm", "evm", &w, &w, BID, Some(other_evm()), None).unwrap();
        assert_eq!(b, other_evm());
        assert_eq!(q, w.address());
    }

    #[test]
    fn give_leg_override_must_restate_the_signer() {
        let w = evm_wallet();
        let err = resolve_leg_addresses("evm", "evm", &w, &w, ASK, Some(other_evm()), None)
            .expect_err("an ASK's base leg is the signer");
        assert!(err.to_string().contains("sign"), "{err}");
        let err = resolve_leg_addresses("evm", "evm", &w, &w, BID, None, Some(other_evm()))
            .expect_err("a BID's quote leg is the signer");
        assert!(err.to_string().contains("sign"), "{err}");
    }

    /// EVM addresses are case-insensitive, so restating the signer in a
    /// different casing is the same address — and the caller's own spelling
    /// is kept (the field is byte-verbatim inside the signed order).
    #[test]
    fn give_leg_override_matches_the_signer_case_insensitively() {
        let w = evm_wallet();
        let lower = w.address().to_ascii_lowercase();
        let (b, _q) =
            resolve_leg_addresses("evm", "evm", &w, &w, ASK, Some(lower.clone()), None).unwrap();
        assert_eq!(b, lower);
    }

    #[test]
    fn a_malformed_receive_leg_override_is_refused() {
        let w = evm_wallet();
        for bad in ["abc", "00000000000000000000000000000000feedbeef", ""] {
            assert!(
                resolve_leg_addresses("evm", "evm", &w, &w, ASK, None, Some(bad.into())).is_err(),
                "{bad:?} must be refused on an EVM leg"
            );
        }
    }

    #[cfg(feature = "solana")]
    mod cross_architecture {
        use super::*;

        fn sol_wallet() -> Wallet {
            Wallet::Solana(Box::new(solana_keypair::Keypair::new()))
        }

        /// EVM base / Solana quote. A BID gives quote (Solana signer); its
        /// base (EVM) receive leg may redirect — to an EVM address only.
        #[test]
        fn receive_leg_is_validated_for_its_own_architecture() {
            let (ew, sw) = (evm_wallet(), sol_wallet());
            let (b, q) =
                resolve_leg_addresses("evm", "solana", &ew, &sw, BID, Some(other_evm()), None)
                    .unwrap();
            assert_eq!(b, other_evm());
            assert_eq!(q, sw.address());

            // A base58 pubkey on the EVM leg is the wrong architecture.
            let base58 = bs58::encode([7u8; 32]).into_string();
            assert!(
                resolve_leg_addresses("evm", "solana", &ew, &sw, BID, Some(base58), None).is_err()
            );
        }

        /// The mirror: an ASK on the same market receives Solana-side, and
        /// that override must be a 32-byte base58 pubkey.
        #[test]
        fn solana_receive_leg_takes_a_pubkey_only() {
            let (ew, sw) = (evm_wallet(), sol_wallet());
            let pk = bs58::encode([9u8; 32]).into_string();
            let (b, q) =
                resolve_leg_addresses("evm", "solana", &ew, &sw, ASK, None, Some(pk.clone()))
                    .unwrap();
            assert_eq!(b, ew.address());
            assert_eq!(q, pk);

            assert!(
                resolve_leg_addresses("evm", "solana", &ew, &sw, ASK, None, Some(other_evm()))
                    .is_err(),
                "an EVM address cannot receive on a Solana leg"
            );
        }

        /// Solana give-leg equality is exact: base58 is case-sensitive.
        #[test]
        fn solana_give_leg_equality_is_exact() {
            let (ew, sw) = (evm_wallet(), sol_wallet());
            let (b, q) =
                resolve_leg_addresses("evm", "solana", &ew, &sw, BID, None, Some(sw.address()))
                    .unwrap();
            assert_eq!(b, ew.address());
            assert_eq!(q, sw.address());

            // Mangle by swapping the case of ONE character — but only a
            // swap whose result is still inside the base58 alphabet AND
            // still passes address validation, so the refusal below can
            // only come from the give-leg equality check. (Wholesale
            // lowercasing was ~50% vacuous: any 'L' in the random pubkey
            // became 'l', which is outside the alphabet, and validation
            // rejected the string before equality was ever consulted.)
            let addr = sw.address();
            let mangled = addr
                .char_indices()
                .filter(|(_, c)| c.is_ascii_alphabetic())
                .map(|(i, c)| {
                    let swapped = if c.is_ascii_uppercase() {
                        c.to_ascii_lowercase()
                    } else {
                        c.to_ascii_uppercase()
                    };
                    let mut s = addr.clone();
                    s.replace_range(i..i + 1, &swapped.to_string());
                    s
                })
                .find(|s| crate::orders::validate_settle_address("solana", s).is_ok() && *s != addr)
                .expect("a 43/44-char base58 pubkey has at least one case-swappable char");

            let err = resolve_leg_addresses("evm", "solana", &ew, &sw, BID, None, Some(mangled))
                .expect_err("a case-mangled base58 pubkey is a DIFFERENT address");
            assert!(
                err.to_string().contains("sign"),
                "the refusal must come from the give-leg signer check, not \
                 from validation: {err}"
            );
        }
    }
}