aspens 0.4.0

Aspens crosschain trading SDK
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
//! 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"
);

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,
    GetDeployCalldataRequest, GetDeployCalldataResponse, SetChainRequest, SetChainResponse,
    SetMarketRequest, SetMarketResponse, SetTokenRequest, SetTokenResponse,
    SetTradeContractRequest, SetTradeContractResponse, UpdateAdminRequest, UpdateAdminResponse,
    VersionInfo,
};
use eyre::Result;
use tonic::metadata::MetadataValue;
use tonic::Request;

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
pub async fn deploy_contract(
    url: String,
    jwt: String,
    chain_network: String,
    tx_hash: String,
) -> Result<DeployContractResponse> {
    let channel = create_channel(&url).await?;
    let mut client = ConfigServiceClient::new(channel);

    let request = authenticated_request(
        &jwt,
        DeployContractRequest {
            chain_network,
            tx_hash,
        },
    );
    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())
}

/// 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())
}

// ============================================================================
// 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
#[derive(Debug, Clone)]
pub struct SetMarketParams {
    pub base_chain_network: String,
    pub quote_chain_network: String,
    pub base_chain_token_symbol: String,
    pub quote_chain_token_symbol: String,
    pub base_chain_token_address: String,
    pub quote_chain_token_address: String,
    pub base_chain_token_decimals: i32,
    pub quote_chain_token_decimals: i32,
    pub pair_decimals: i32,
}

/// Set a market (requires auth)
///
/// # 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,
        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,
            base_chain_token_decimals: params.base_chain_token_decimals,
            quote_chain_token_decimals: params.quote_chain_token_decimals,
            pair_decimals: params.pair_decimals,
        },
    );
    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::Token;
pub use config_pb::TradeContract;