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
//! Admin commands module for authenticated configuration operations
//!
//! This module provides admin commands that require JWT authentication.
//! All commands (except `get_version`) require a valid JWT token obtained
//! from the authentication service.

use alloy_sol_types::sol;

// MidribFactory contract for deploying trading instances
sol!(
    #[derive(Debug)]
    #[allow(missing_docs)]
    #[sol(rpc)]
    MidribFactory,
    "artifacts/MidribFactory.json"
);

/// Re-export of the config service protobuf bindings for admin call sites.
pub mod config_pb {
    pub use crate::commands::config::config_pb::*;
}

use config_pb::config_service_client::ConfigServiceClient;
use config_pb::{
    DeleteChainRequest, DeleteChainResponse, DeleteMarketRequest, DeleteMarketResponse,
    DeleteTokenRequest, DeleteTokenResponse, DeleteTradeContractRequest,
    DeleteTradeContractResponse, DeployContractRequest, DeployContractResponse, Empty,
    GetConfigRequest, GetDeployCalldataRequest, GetDeployCalldataResponse, ProbeChainRpcRequest,
    SetChainRequest, SetChainResponse, SetChainRpcsRequest, SetMarketRequest, SetMarketResponse,
    SetOperatorAdminRequest, SetOperatorAdminResponse, SetOperatorFeeRequest,
    SetOperatorFeeResponse, SetTokenRequest, SetTokenResponse, SetTradeContractRequest,
    SetTradeContractResponse, UpdateAdminRequest, UpdateAdminResponse, VersionInfo,
};
// RpcEndpoint / ProbeChainRpcResponse / SetChainRpcsResponse are brought into
// scope via the `pub use config_pb::...` re-exports below (CLI convenience
// surface) — importing them here too would just be a duplicate binding.
use eyre::Result;
use tonic::Request;
use tonic::metadata::MetadataValue;

use crate::grpc::create_channel;

/// Create an authenticated gRPC request with JWT bearer token
fn authenticated_request<T>(jwt: &str, payload: T) -> Request<T> {
    let mut request = Request::new(payload);
    let bearer = format!("Bearer {}", jwt);
    if let Ok(value) = bearer.parse::<MetadataValue<_>>() {
        request.metadata_mut().insert("authorization", value);
    }
    request
}

// ============================================================================
// Admin Management Operations
// ============================================================================

/// Update the admin address (requires auth)
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
/// * `jwt` - Valid JWT token
/// * `admin_address` - New admin Ethereum address
pub async fn update_admin(
    url: String,
    jwt: String,
    admin_address: String,
) -> Result<UpdateAdminResponse> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = authenticated_request(&jwt, UpdateAdminRequest { admin_address });
    let response = client.update_admin(request).await?;

    Ok(response.into_inner())
}

// ============================================================================
// Contract Operations
// ============================================================================

/// Get deploy calldata from the server for deploying a trading instance
///
/// This retrieves the pre-encoded calldata for creating a trading instance,
/// along with the factory address and chain ID needed for signing the transaction.
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
/// * `jwt` - Valid JWT token
/// * `chain_network` - Network name (e.g., "base-sepolia")
/// * `fee_bps` - Fee in basis points (e.g., 100 = 1%)
pub async fn get_deploy_calldata(
    url: String,
    jwt: String,
    chain_network: String,
    fee_bps: u32,
) -> Result<GetDeployCalldataResponse> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = authenticated_request(
        &jwt,
        GetDeployCalldataRequest {
            chain_network,
            fee_bps,
        },
    );
    let response = client.get_deploy_calldata(request).await?;

    Ok(response.into_inner())
}

/// Deploy a trade contract on a chain (requires auth)
///
/// This function is called after broadcasting the transaction locally.
/// It waits for the transaction to be confirmed and extracts the deployed contract address.
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
/// * `jwt` - Valid JWT token
/// * `chain_network` - Network name (e.g., "base-sepolia")
/// * `tx_hash` - Transaction hash (0x-prefixed hex) of the already-broadcast
///   createInstance call. Required for EVM. Pass an empty string for Solana,
///   where the server signs and submits create_instance itself.
/// * `force` - If `true`, overwrite an existing trade_contract registration.
///   Off by default; enabling it orphans any deposits on the previous instance.
/// * `fee_bps` - Trading fee in basis points. Used by the Solana server-side
///   path (which constructs the create_instance ix on the server). Ignored by
///   EVM, where the fee was already encoded into the calldata the admin signed.
pub async fn deploy_contract(
    url: String,
    jwt: String,
    chain_network: String,
    tx_hash: String,
    force: bool,
    fee_bps: u32,
) -> Result<DeployContractResponse> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = authenticated_request(
        &jwt,
        DeployContractRequest {
            chain_network,
            tx_hash,
            force,
            fee_bps,
        },
    );
    let response = client.deploy_contract(request).await?;

    Ok(response.into_inner())
}

/// Parameters for building a createInstance transaction using server-provided calldata
#[derive(Debug, Clone)]
pub struct CreateInstanceParams {
    /// The factory contract address on the target chain (from GetDeployCalldata response)
    pub factory_address: String,
    /// Pre-encoded calldata for createInstance (from GetDeployCalldata response)
    pub calldata: Vec<u8>,
    /// The RPC URL for the target chain
    pub rpc_url: String,
    /// The chain ID (from GetDeployCalldata response)
    pub chain_id: u64,
    /// The private key for signing (hex string without 0x prefix)
    pub privkey: String,
}

/// Build and sign a createInstance transaction for deploying a trading instance
///
/// This creates a signed transaction using pre-encoded calldata from the server.
/// The calldata is obtained from the GetDeployCalldata RPC call.
///
/// # Arguments
/// * `params` - Parameters for building the transaction (includes server-provided calldata)
///
/// # Returns
/// The RLP-encoded signed transaction bytes
pub async fn build_create_instance_tx(params: CreateInstanceParams) -> Result<Vec<u8>> {
    use alloy::consensus::{SignableTransaction, TxEip1559, TxEnvelope};
    use alloy::network::{EthereumWallet, TransactionBuilder, TxSigner};
    use alloy::primitives::{Address, Bytes, TxKind, U256};
    use alloy::providers::{Provider, ProviderBuilder};
    use alloy::rpc::types::TransactionRequest;
    use alloy::signers::local::PrivateKeySigner;
    use url::Url;

    // Parse addresses
    let factory_addr: Address = params.factory_address.parse()?;

    // Set up the signer
    let signer: PrivateKeySigner = params.privkey.parse()?;
    let wallet = EthereumWallet::new(signer.clone());
    let from_address = signer.address();

    // Set up the provider
    let rpc_url = Url::parse(&params.rpc_url)?;
    let provider = ProviderBuilder::new()
        .with_chain_id(params.chain_id)
        .wallet(wallet)
        .connect_http(rpc_url);

    // Get the nonce for the signing address
    let nonce = provider.get_transaction_count(from_address).await?;

    // The calldata is ABI-encoded createInstance(address, uint16)
    let calldata_bytes = Bytes::from(params.calldata.clone());

    // Build a transaction request for gas estimation
    let tx_request = TransactionRequest::default()
        .with_from(from_address)
        .with_to(factory_addr)
        .with_input(calldata_bytes.clone());

    // Estimate gas
    let gas_estimate = provider.estimate_gas(tx_request).await?;

    // Get current gas prices
    let fee_estimate = provider.estimate_eip1559_fees().await?;

    // Build the EIP-1559 transaction
    let mut tx = TxEip1559 {
        chain_id: params.chain_id,
        nonce,
        gas_limit: gas_estimate + (gas_estimate / 10), // Add 10% buffer
        max_fee_per_gas: fee_estimate.max_fee_per_gas,
        max_priority_fee_per_gas: fee_estimate.max_priority_fee_per_gas,
        to: TxKind::Call(factory_addr),
        value: U256::ZERO,
        access_list: Default::default(),
        input: calldata_bytes,
    };

    // Sign the transaction
    let signature = signer.sign_transaction(&mut tx).await?;
    let signed_tx = TxEnvelope::Eip1559(tx.into_signed(signature));

    // Encode the signed transaction to RLP bytes
    use alloy::eips::eip2718::Encodable2718;
    let mut encoded = Vec::new();
    signed_tx.encode_2718(&mut encoded);

    Ok(encoded)
}

/// Broadcast a signed transaction and return the transaction hash
///
/// # Arguments
/// * `rpc_url` - The RPC URL for the target chain
/// * `signed_tx` - RLP-encoded signed transaction bytes
///
/// # Returns
/// The transaction hash as a 0x-prefixed hex string
pub async fn broadcast_transaction(rpc_url: String, signed_tx: Vec<u8>) -> Result<String> {
    use alloy::providers::{Provider, ProviderBuilder};
    use url::Url;

    let rpc_url_parsed = Url::parse(&rpc_url)?;
    let provider = ProviderBuilder::new().connect_http(rpc_url_parsed);

    // Broadcast the signed transaction
    let pending_tx = provider
        .send_raw_transaction(&signed_tx)
        .await
        .map_err(|e| eyre::eyre!("Failed to broadcast transaction: {}", e))?;

    let tx_hash = pending_tx.tx_hash();

    // Return the tx hash as 0x-prefixed hex string
    Ok(format!("{:?}", tx_hash))
}

/// Set a trade contract on a chain (requires auth)
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
/// * `jwt` - Valid JWT token
/// * `address` - Contract address
/// * `chain_network` - Chain to associate with
pub async fn set_trade_contract(
    url: String,
    jwt: String,
    address: String,
    chain_network: String,
) -> Result<SetTradeContractResponse> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = authenticated_request(
        &jwt,
        SetTradeContractRequest {
            address,
            chain_network,
        },
    );
    let response = client.set_trade_contract(request).await?;

    Ok(response.into_inner())
}

/// Set an instance's operator fee — recipient + bps (requires auth).
///
/// The arborter submits the on-chain `setOperatorFee` with its own signer key,
/// but the contract gates it on the instance's `operator_admin`, which the
/// current contracts (EVM factory + `setOperatorAdmin`, Solana program) never
/// allow to be the arborter signer. Against any instance they minted this call
/// therefore fails on-chain (`UNAUTHORIZED_CALLER` / `Unauthorized`); the
/// operator admin must sign the setter itself. Returns the on-chain tx
/// hash/signature when it does succeed (an older instance whose operator admin
/// is still the arborter signer).
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
/// * `jwt` - Valid JWT token
/// * `chain_network` - Chain whose instance to update
/// * `recipient` - Operator-fee recipient address (0x-hex EVM / base58 Solana)
/// * `bps` - Operator fee in basis points
pub async fn set_operator_fee(
    url: String,
    jwt: String,
    chain_network: String,
    recipient: String,
    bps: u32,
) -> Result<SetOperatorFeeResponse> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = authenticated_request(
        &jwt,
        SetOperatorFeeRequest {
            chain_network,
            recipient,
            bps,
        },
    );
    let response = client.set_operator_fee(request).await?;

    Ok(response.into_inner())
}

/// Rotate an instance's `operator_admin` key (requires auth).
///
/// Submitted by the arborter with its own signer key, so — like
/// [`set_operator_fee`] — it fails on-chain against any instance whose
/// operator admin is not the arborter signer, which the current contracts
/// guarantee for every instance they mint. The program also refuses a
/// `new_admin` equal to the instance signer or the zero address. Returns the
/// on-chain tx hash/signature.
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
/// * `jwt` - Valid JWT token
/// * `chain_network` - Chain whose instance to update
/// * `new_admin` - The new operator_admin address (0x-hex EVM / base58 Solana)
pub async fn set_operator_admin(
    url: String,
    jwt: String,
    chain_network: String,
    new_admin: String,
) -> Result<SetOperatorAdminResponse> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = authenticated_request(
        &jwt,
        SetOperatorAdminRequest {
            chain_network,
            new_admin,
        },
    );
    let response = client.set_operator_admin(request).await?;

    Ok(response.into_inner())
}

/// Delete a trade contract from a chain (requires auth)
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
/// * `jwt` - Valid JWT token
/// * `chain_network` - Chain to remove contract from
pub async fn delete_trade_contract(
    url: String,
    jwt: String,
    chain_network: String,
) -> Result<DeleteTradeContractResponse> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = authenticated_request(&jwt, DeleteTradeContractRequest { chain_network });
    let response = client.delete_trade_contract(request).await?;

    Ok(response.into_inner())
}

// ============================================================================
// Chain Operations
// ============================================================================

/// Set a chain in the configuration (requires auth)
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
/// * `jwt` - Valid JWT token
/// * `chain` - Chain configuration
pub async fn set_chain(url: String, jwt: String, chain: Chain) -> Result<SetChainResponse> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = authenticated_request(&jwt, SetChainRequest { chain: Some(chain) });
    let response = client.set_chain(request).await?;

    Ok(response.into_inner())
}

/// Delete a chain from the configuration (requires auth)
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
/// * `jwt` - Valid JWT token
/// * `chain_network` - Network name to delete (e.g., "base-sepolia")
pub async fn delete_chain(
    url: String,
    jwt: String,
    chain_network: String,
) -> Result<DeleteChainResponse> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = authenticated_request(&jwt, DeleteChainRequest { chain_network });
    let response = client.delete_chain(request).await?;

    Ok(response.into_inner())
}

/// Replace a chain's complete RPC endpoint set (requires auth).
///
/// Full replace, one transaction: `rpcs` becomes the chain's ENTIRE endpoint
/// list, priority-ordered. Applied live on the arborter — providers rebuild
/// and the chain's event listener restarts, no arborter restart needed.
/// Requires at least one enabled endpoint (the server rejects an all-disabled
/// or empty set with `InvalidArgument`); an unknown `network` is `NotFound`.
///
/// Secrets must be the real values — there is no keep-existing sentinel, so
/// an edit that drops a field clears it. The response mirrors what
/// `GetConfig` will now show for this chain: MASKED (`auth_secret` = "***",
/// url query values/userinfo = "***").
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
/// * `jwt` - Valid JWT token
/// * `network` - `chains.network` key, e.g. `"flare-coston2"`
/// * `rpcs` - The chain's complete new endpoint list, priority-ordered
pub async fn set_chain_rpcs(
    url: String,
    jwt: String,
    network: String,
    rpcs: Vec<RpcEndpoint>,
) -> Result<SetChainRpcsResponse> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = authenticated_request(&jwt, SetChainRpcsRequest { network, rpcs });
    let response = client.set_chain_rpcs(request).await?;

    Ok(response.into_inner())
}

/// Probe a candidate RPC endpoint from the arborter's own network position,
/// before committing it via [`set_chain_rpcs`] (requires auth).
///
/// The endpoint is dialed as submitted and never stored. Compares the chain
/// id it reports against `network`'s configured chain id, and checks whether
/// the finalized tag / finalized commitment answers (DEP-1 deposit-finality
/// reads depend on it — a keyless public endpoint often throttles exactly
/// this).
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
/// * `jwt` - Valid JWT token
/// * `network` - `chains.network` key, used only to compare chain ids
/// * `endpoint` - The candidate endpoint to probe
pub async fn probe_chain_rpc(
    url: String,
    jwt: String,
    network: String,
    endpoint: RpcEndpoint,
) -> Result<ProbeChainRpcResponse> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = authenticated_request(
        &jwt,
        ProbeChainRpcRequest {
            network,
            endpoint: Some(endpoint),
        },
    );
    let response = client.probe_chain_rpc(request).await?;

    Ok(response.into_inner())
}

/// Fetch a single chain's current RPC endpoint set via `GetConfig` (no auth
/// required — mirrors the unauthenticated read path in
/// [`crate::commands::config::download_config`]).
///
/// The result is exactly what the server returns: MASKED (`auth_secret` =
/// "***", url query values/userinfo = "***"). Render it as-is — there is no
/// unmask path; a client needing the real values must have set them itself.
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
/// * `network` - `chains.network` key to look up (e.g. `"flare-coston2"`)
///
/// # Errors
/// Returns an error if the network has no matching chain in the
/// configuration (a client-side filter over `GetConfig`, not a wire-level
/// `NotFound` — that status is what `set_chain_rpcs`/`probe_chain_rpc`
/// return for an unknown network).
pub async fn get_chain_rpcs(url: String, network: String) -> Result<Vec<RpcEndpoint>> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = Request::new(GetConfigRequest {});
    let response = client.get_config(request).await?;
    let config = response
        .into_inner()
        .config
        .ok_or_else(|| eyre::eyre!("server returned no configuration"))?;

    config
        .chains
        .into_iter()
        .find(|chain| chain.network == network)
        .map(|chain| chain.rpcs)
        .ok_or_else(|| {
            eyre::eyre!(
                "unknown network '{}': no such chain in the configuration",
                network
            )
        })
}

// ============================================================================
// Token Operations
// ============================================================================

/// Set a token on a chain (requires auth)
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
/// * `jwt` - Valid JWT token
/// * `chain_network` - Network name (e.g., "base-sepolia")
/// * `token` - Token configuration
pub async fn set_token(
    url: String,
    jwt: String,
    chain_network: String,
    token: Token,
) -> Result<SetTokenResponse> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = authenticated_request(
        &jwt,
        SetTokenRequest {
            chain_network,
            token: Some(token),
        },
    );
    let response = client.set_token(request).await?;

    Ok(response.into_inner())
}

/// Delete a token from a chain (requires auth)
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
/// * `jwt` - Valid JWT token
/// * `chain_network` - Network name (e.g., "base-sepolia")
/// * `token_symbol` - Token symbol to delete (e.g., "USDC")
pub async fn delete_token(
    url: String,
    jwt: String,
    chain_network: String,
    token_symbol: String,
) -> Result<DeleteTokenResponse> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = authenticated_request(
        &jwt,
        DeleteTokenRequest {
            chain_network,
            token_symbol,
        },
    );
    let response = client.delete_token(request).await?;

    Ok(response.into_inner())
}

// ============================================================================
// Market Operations
// ============================================================================

/// Parameters for setting a market
///
/// No token decimals here: a token's decimals belong to the token, their one
/// home is the `tokens` table, and a second copy on the market could disagree
/// with nothing to reconcile it. Register the token first with [`set_token`];
/// the arborter reads the decimals from it.
///
/// The token ADDRESSES are load-bearing: the arborter matches them against the
/// `tokens` row **byte-for-byte,
/// including case**, and rejects the market if they differ. EIP-55 checksummed
/// and lowercase spellings of one address are different byte strings. Nothing
/// on this path normalises case, deliberately — pass the same spelling to
/// [`set_token`] and here.
#[derive(Debug, Clone)]
pub struct SetMarketParams {
    /// Network name of the base-token chain (e.g. `"base-sepolia"`).
    pub base_chain_network: String,
    /// Network name of the quote-token chain.
    pub quote_chain_network: String,
    /// Symbol of the base token (e.g. `"WBTC"`).
    pub base_chain_token_symbol: String,
    /// Symbol of the quote token (e.g. `"USDT"`).
    pub quote_chain_token_symbol: String,
    /// On-chain contract / mint address of the base token.
    pub base_chain_token_address: String,
    /// On-chain contract / mint address of the quote token.
    pub quote_chain_token_address: String,
    /// Pair decimals used for order quantities and prices on this market.
    ///
    /// Not a duplicate of any token's decimals: pair decimals are the
    /// matching engine's scale for this market's quantities and prices, they
    /// belong to the market, and nothing else knows them.
    pub pair_decimals: i32,
}

/// Build the `SetMarketRequest` wire message from [`SetMarketParams`].
///
/// Split out of [`set_market`] so the one property that is easy to break and
/// impossible to see is testable without a server: **every string crosses
/// unchanged**. The arborter compares the token addresses here against the
/// `tokens` row byte-for-byte, so a well-meant `to_lowercase()` or EIP-55
/// re-checksum anywhere on this path turns a correct market into a rejected
/// one — or, worse on a stack that predates the check, into a market keyed to
/// an address nothing else uses.
fn set_market_request(params: SetMarketParams) -> SetMarketRequest {
    SetMarketRequest {
        base_chain_network: params.base_chain_network,
        quote_chain_network: params.quote_chain_network,
        base_chain_token_symbol: params.base_chain_token_symbol,
        quote_chain_token_symbol: params.quote_chain_token_symbol,
        base_chain_token_address: params.base_chain_token_address,
        quote_chain_token_address: params.quote_chain_token_address,
        pair_decimals: params.pair_decimals,
    }
}

/// Set a market (requires auth)
///
/// Register both tokens with [`set_token`] first — the market takes its
/// decimals from them, and its addresses must match theirs exactly.
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
/// * `jwt` - Valid JWT token
/// * `params` - Market parameters
pub async fn set_market(
    url: String,
    jwt: String,
    params: SetMarketParams,
) -> Result<SetMarketResponse> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = authenticated_request(&jwt, set_market_request(params));
    let response = client.set_market(request).await?;

    Ok(response.into_inner())
}

/// Delete a market (requires auth)
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
/// * `jwt` - Valid JWT token
/// * `market_id` - Market ID to delete
pub async fn delete_market(
    url: String,
    jwt: String,
    market_id: String,
) -> Result<DeleteMarketResponse> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = authenticated_request(&jwt, DeleteMarketRequest { market_id });
    let response = client.delete_market(request).await?;

    Ok(response.into_inner())
}

// ============================================================================
// Read-Only Operations (no auth required)
// ============================================================================

/// Get server version information (no auth required)
///
/// # Arguments
/// * `url` - The Aspens stack gRPC URL
pub async fn get_version(url: String) -> Result<VersionInfo> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = Request::new(Empty {});
    let response = client.get_version(request).await?;

    Ok(response.into_inner())
}

// ============================================================================
// Re-exports for convenience
// ============================================================================

// Re-export types needed by CLI
pub use config_pb::Chain;
pub use config_pb::ProbeChainRpcResponse;
pub use config_pb::RpcAuthScheme;
pub use config_pb::RpcEndpoint;
pub use config_pb::SetChainRpcsResponse;
pub use config_pb::Token;
pub use config_pb::TradeContract;

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

    /// An EIP-55 checksummed address and its lowercase form: the same account,
    /// two different byte strings. `set-token` stores whichever spelling it was
    /// given, and the arborter now compares a market's addresses against that
    /// row byte-for-byte — so the SDK must transmit exactly what it was handed.
    const CHECKSUMMED: &str = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
    /// Deliberately a DIFFERENT address, not the same one re-cased: two fields
    /// that happened to be equal would let a mutant swapping base for quote
    /// produce identical output.
    const LOWERCASE_OTHER: &str = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48";

    fn params() -> SetMarketParams {
        SetMarketParams {
            base_chain_network: "base-net".into(),
            quote_chain_network: "quote-net".into(),
            base_chain_token_symbol: "WETH".into(),
            quote_chain_token_symbol: "USDC".into(),
            base_chain_token_address: CHECKSUMMED.into(),
            quote_chain_token_address: LOWERCASE_OTHER.into(),
            pair_decimals: 12,
        }
    }

    /// Case is preserved on BOTH legs, in both directions — a checksummed
    /// address stays checksummed and a lowercase one stays lowercase. A
    /// normaliser on either leg fails one of these whichever way it normalises.
    #[test]
    fn set_market_transmits_token_addresses_byte_for_byte() {
        let req = set_market_request(params());
        assert_eq!(req.base_chain_token_address, CHECKSUMMED);
        assert_eq!(req.quote_chain_token_address, LOWERCASE_OTHER);
        // Stated as the property, not just the values: no case folding at all.
        assert_ne!(
            req.base_chain_token_address,
            CHECKSUMMED.to_lowercase(),
            "the checksummed base address must not be lower-cased in transit"
        );
    }

    /// The two legs must not be crossed. The addresses above are distinct
    /// accounts, and the symbols and networks differ too, so a swap is visible
    /// rather than absorbed.
    #[test]
    fn set_market_does_not_cross_the_base_and_quote_legs() {
        let req = set_market_request(params());
        assert_eq!(req.base_chain_network, "base-net");
        assert_eq!(req.quote_chain_network, "quote-net");
        assert_eq!(req.base_chain_token_symbol, "WETH");
        assert_eq!(req.quote_chain_token_symbol, "USDC");
        assert_eq!(req.pair_decimals, 12);
    }
}