Skip to content

Commit e662e6b

Browse files
authored
Accounting contract and binance client traits (#3435)
* accounting contract trait * BinanceClient trait
1 parent b7b5a5a commit e662e6b

File tree

10 files changed

+100
-55
lines changed

10 files changed

+100
-55
lines changed

tee-worker/omni-executor/Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tee-worker/omni-executor/accounting-contract-client/src/lib.rs

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use alloy::{
44
sol,
55
sol_types::{SolInterface, SolValue},
66
};
7+
use async_trait::async_trait;
78
use ethereum_rpc::RpcProvider;
89
use AccountingContract::AccountingContractCalls;
910

@@ -14,17 +15,37 @@ sol!(
1415
"./abi/AccountingContract.json"
1516
);
1617

17-
pub struct AccountingContractClient<P: RpcProvider<Transaction = TransactionRequest>> {
18+
#[async_trait]
19+
pub trait AccountingContractApi: Send + Sync {
20+
async fn execute_pay_out_request(
21+
&self,
22+
beneficiary: Address,
23+
nonce: U256,
24+
amount: U256,
25+
) -> Result<(), ()>;
26+
27+
async fn get_nonce(&self, user: Address) -> Result<U256, ()>;
28+
29+
async fn get_balance(&self) -> Result<U256, ()>;
30+
}
31+
32+
pub struct AccountingContractClient<P: RpcProvider<Transaction = TransactionRequest> + Send + Sync>
33+
{
1834
pub provider: P,
1935
pub contract_address: Address,
2036
}
2137

22-
impl<P: RpcProvider<Transaction = TransactionRequest>> AccountingContractClient<P> {
38+
impl<P: RpcProvider<Transaction = TransactionRequest> + Send + Sync> AccountingContractClient<P> {
2339
pub fn new(provider: P, contract_address: Address) -> Self {
2440
Self { provider, contract_address }
2541
}
42+
}
2643

27-
pub async fn execute_pay_out_request(
44+
#[async_trait]
45+
impl<P: RpcProvider<Transaction = TransactionRequest> + Send + Sync> AccountingContractApi
46+
for AccountingContractClient<P>
47+
{
48+
async fn execute_pay_out_request(
2849
&self,
2950
beneficiary: Address,
3051
nonce: U256,
@@ -43,7 +64,7 @@ impl<P: RpcProvider<Transaction = TransactionRequest>> AccountingContractClient<
4364
self.provider.send_transaction(tx).await
4465
}
4566

46-
pub async fn get_nonce(&self, user: Address) -> Result<U256, ()> {
67+
async fn get_nonce(&self, user: Address) -> Result<U256, ()> {
4768
let call = AccountingContractCalls::getNonce(AccountingContract::getNonceCall { user })
4869
.abi_encode();
4970
let tx = TransactionRequest {
@@ -57,7 +78,7 @@ impl<P: RpcProvider<Transaction = TransactionRequest>> AccountingContractClient<
5778
})
5879
}
5980

60-
pub async fn get_balance(&self) -> Result<U256, ()> {
81+
async fn get_balance(&self) -> Result<U256, ()> {
6182
let call =
6283
AccountingContractCalls::getBalance(AccountingContract::getBalanceCall {}).abi_encode();
6384
let tx = TransactionRequest {

tee-worker/omni-executor/binance-api/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ authors = ['Trust Computing GmbH <info@litentry.com>']
55
edition.workspace = true
66

77
[dependencies]
8+
async-trait = { workspace = true }
89
chrono = { workspace = true }
910
hex = { workspace = true }
1011
hmac = { workspace = true }

tee-worker/omni-executor/binance-api/src/convert_api/mod.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
mod types;
22

3-
use crate::{error::Error, traits::TryIntoParams, types::AssetSymbol, BinanceApi, Method};
3+
use crate::BinanceApi;
4+
use crate::{error::Error, traits::TryIntoParams, types::AssetSymbol, BinanceApiClient, Method};
45
use log::error;
56
use std::collections::HashMap;
67
use types::{
@@ -14,11 +15,11 @@ const CONVERT_API: &str = "/sapi/v1/convert";
1415
const MAX_LIMIT: u16 = 1000;
1516

1617
pub struct ConvertApi<'a> {
17-
base_api: &'a BinanceApi,
18+
base_api: &'a BinanceApiClient,
1819
}
1920

2021
impl<'a> ConvertApi<'a> {
21-
pub fn new(binance_api: &BinanceApi) -> ConvertApi {
22+
pub fn new(binance_api: &BinanceApiClient) -> ConvertApi {
2223
ConvertApi { base_api: binance_api }
2324
}
2425

tee-worker/omni-executor/binance-api/src/lib.rs

Lines changed: 41 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ mod traits;
55
mod types;
66
mod wallet_api;
77

8+
use async_trait::async_trait;
89
use convert_api::ConvertApi;
910
use error::Error;
1011
use hmac::{Hmac, Mac};
@@ -21,8 +22,34 @@ use wallet_api::WalletApi;
2122

2223
const MAX_RECV_WINDOW: u32 = 60000;
2324

25+
#[async_trait]
26+
pub trait BinanceApi: Send + Sync {
27+
fn convert(&self) -> ConvertApi;
28+
fn spot_trading(&self) -> SpotTradingApi;
29+
fn wallet(&self) -> WalletApi;
30+
31+
fn sign_request(&self, query_string: &str) -> String;
32+
async fn make_public_get_request<T>(
33+
&self,
34+
endpoint: &str,
35+
parameters: Option<HashMap<String, String>>,
36+
) -> Result<T, Error>
37+
where
38+
T: serde::de::DeserializeOwned;
39+
40+
async fn make_signed_request<T>(
41+
&self,
42+
endpoint: &str,
43+
method: Method,
44+
parameters: Option<HashMap<String, String>>,
45+
recv_window: Option<u32>,
46+
) -> Result<T, Error>
47+
where
48+
T: serde::de::DeserializeOwned;
49+
}
50+
2451
#[derive(Debug, Clone)]
25-
pub struct BinanceApi {
52+
pub struct BinanceApiClient {
2653
client: Client,
2754
base_url: Url,
2855
api_key: String,
@@ -36,33 +63,36 @@ pub enum BinanceApiResponse<T> {
3663
Error { code: i32, msg: String },
3764
}
3865

39-
impl BinanceApi {
40-
pub fn new(api_key: String, api_secret: String, base_url: Option<String>) -> BinanceApi {
66+
impl BinanceApiClient {
67+
pub fn new(api_key: String, api_secret: String, base_url: Option<String>) -> BinanceApiClient {
4168
let base_url = match base_url {
4269
Some(url) => Url::parse(&url).expect("Invalid base URL"),
4370
None => Url::parse("https://api.binance.com").unwrap(),
4471
};
4572
let client = Client::new();
46-
BinanceApi { client, base_url, api_key, api_secret }
73+
BinanceApiClient { client, base_url, api_key, api_secret }
4774
}
75+
}
4876

77+
#[async_trait]
78+
impl BinanceApi for BinanceApiClient {
4979
/// Create a new ConvertApi instance
50-
pub fn convert(&self) -> ConvertApi {
80+
fn convert(&self) -> ConvertApi {
5181
ConvertApi::new(self)
5282
}
5383

5484
/// Create a new SpotTradingApi instance
55-
pub fn spot_trading(&self) -> SpotTradingApi {
85+
fn spot_trading(&self) -> SpotTradingApi {
5686
SpotTradingApi::new(self)
5787
}
5888

5989
/// Create a new WalletApi instance
60-
pub fn wallet(&self) -> WalletApi {
90+
fn wallet(&self) -> WalletApi {
6191
WalletApi::new(self)
6292
}
6393

6494
/// Create HMAC SHA256 signature for request parameters
65-
pub fn sign_request(&self, query_string: &str) -> String {
95+
fn sign_request(&self, query_string: &str) -> String {
6696
let mut mac = Hmac::<Sha256>::new_from_slice(self.api_secret.as_bytes())
6797
.expect("HMAC can take key of any size");
6898
mac.update(query_string.as_bytes());
@@ -72,7 +102,7 @@ impl BinanceApi {
72102
}
73103

74104
/// Helper for making public API requests
75-
pub async fn make_public_get_request<T>(
105+
async fn make_public_get_request<T>(
76106
&self,
77107
endpoint: &str,
78108
parameters: Option<HashMap<String, String>>,
@@ -109,7 +139,7 @@ impl BinanceApi {
109139
}
110140

111141
/// Helper for making signed API requests
112-
pub async fn make_signed_request<T>(
142+
async fn make_signed_request<T>(
113143
&self,
114144
endpoint: &str,
115145
method: Method,
@@ -200,7 +230,7 @@ mod tests {
200230
let api_secret =
201231
"NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j".to_string();
202232
let query_string = "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559".to_string();
203-
let binance_api = BinanceApi::new(api_key, api_secret, None);
233+
let binance_api = BinanceApiClient::new(api_key, api_secret, None);
204234
let signature = binance_api.sign_request(&query_string);
205235

206236
assert_eq!(signature, "c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71");

tee-worker/omni-executor/binance-api/src/spot_trading_api/mod.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
pub mod types;
22

3-
use crate::{error::Error, traits::TryIntoParams, BinanceApi, Method};
3+
use crate::BinanceApi;
4+
use crate::{error::Error, traits::TryIntoParams, BinanceApiClient, Method};
45
use std::collections::HashMap;
56
use types::{
67
AccountInfo, CancelOrderRestrictions, CreateOrderParams, EmptyResponse, ExchangeInfo,
@@ -11,11 +12,11 @@ use types::{
1112
const SPOT_TRADING_API: &str = "/api/v3";
1213

1314
pub struct SpotTradingApi<'a> {
14-
base_api: &'a BinanceApi,
15+
base_api: &'a BinanceApiClient,
1516
}
1617

1718
impl<'a> SpotTradingApi<'a> {
18-
pub fn new(binance_api: &BinanceApi) -> SpotTradingApi {
19+
pub fn new(binance_api: &BinanceApiClient) -> SpotTradingApi {
1920
SpotTradingApi { base_api: binance_api }
2021
}
2122

tee-worker/omni-executor/binance-api/src/wallet_api/mod.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,19 @@ mod types;
22

33
use types::{CoinInfo, Deposit, DepositAddress, WithdrawOrder};
44

5-
use crate::{error::Error, BinanceApi, Method};
5+
use crate::BinanceApi;
6+
use crate::{error::Error, BinanceApiClient, Method};
67
use std::collections::HashMap;
78

89
/// https://developers.binance.com/docs/wallet/Introduction
910
const WALLET_API: &str = "/sapi/v1";
1011

1112
pub struct WalletApi<'a> {
12-
base_api: &'a BinanceApi,
13+
base_api: &'a BinanceApiClient,
1314
}
1415

1516
impl<'a> WalletApi<'a> {
16-
pub fn new(binance_api: &BinanceApi) -> WalletApi {
17+
pub fn new(binance_api: &BinanceApiClient) -> WalletApi {
1718
WalletApi { base_api: binance_api }
1819
}
1920

tee-worker/omni-executor/ethereum-rpc/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ impl RpcProviderFactory for AlloyRpcProviderFactory {
4444
}
4545

4646
#[async_trait]
47-
pub trait RpcProvider {
47+
pub trait RpcProvider: Send + Sync {
4848
type Addr;
4949
type Transaction;
5050

tee-worker/omni-executor/executor-worker/src/main.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use crate::cli::Cli;
1818
use accounting_contract_client::AccountingContractClient;
1919
use alloy::network::EthereumWallet;
2020
use alloy::signers::local::PrivateKeySigner;
21-
use binance_api::BinanceApi;
21+
use binance_api::BinanceApiClient;
2222
use clap::Parser;
2323
use cli::*;
2424
use cross_chain_intent_executor::{Chain, CrossChainIntentExecutor, RpcEndpointRegistry};
@@ -199,7 +199,7 @@ async fn main() -> Result<(), ()> {
199199
let binance_api_key = env::var("OE_BINANCE_API_KEY").unwrap_or("".to_string());
200200
let binance_api_secret = env::var("OE_BINANCE_API_SECRET").unwrap_or("".to_string());
201201
let binance_api_base_url = env::var("OE_BINANCE_API_BASE_URL").ok();
202-
let binance_api = Arc::new(BinanceApi::new(
202+
let binance_api = Arc::new(BinanceApiClient::new(
203203
binance_api_key,
204204
binance_api_secret,
205205
binance_api_base_url,
@@ -229,7 +229,7 @@ async fn main() -> Result<(), ()> {
229229
storage_db.clone(),
230230
binance_api,
231231
solana_client,
232-
Arc::new(accounting_contract_client),
232+
Arc::new(Box::new(accounting_contract_client)),
233233
)?;
234234

235235
let task_handler_context = TaskHandlerContext::new(

tee-worker/omni-executor/intent/executors/cross-chain/src/lib.rs

Lines changed: 15 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -14,21 +14,13 @@
1414
// You should have received a copy of the GNU General Public License
1515
// along with Litentry. If not, see <https://www.gnu.org/licenses/>.
1616

17-
use accounting_contract_client::AccountingContractClient;
18-
use alloy::{
19-
primitives::{Address, U256},
20-
rpc::types::TransactionRequest,
21-
};
17+
use alloy::primitives::{Address, U256};
2218
use async_trait::async_trait;
2319
use base58::ToBase58;
24-
use binance_api::{
25-
spot_trading_api::types::{
26-
CreateOrderParams as BinanceCreateOrderParams, OrderSide as BinanceOrderSide,
27-
OrderStatus as BinanceOrderStatus, OrderType as BinanceOrderType,
28-
},
29-
BinanceApi,
20+
use binance_api::spot_trading_api::types::{
21+
CreateOrderParams as BinanceCreateOrderParams, OrderSide as BinanceOrderSide,
22+
OrderStatus as BinanceOrderStatus, OrderType as BinanceOrderType,
3023
};
31-
use ethereum_rpc::RpcProvider as EthereumRpcProvider;
3224
use executor_core::intent_executor::{IntentExecutionResult, IntentExecutor};
3325
use executor_primitives::Intent;
3426
use executor_primitives::IntentId;
@@ -66,6 +58,8 @@ use pumpx::{pubkey_to_evm_address, pubkey_to_solana_address};
6658
use std::collections::HashMap;
6759
use std::sync::Arc;
6860

61+
use accounting_contract_client::AccountingContractApi;
62+
use binance_api::BinanceApi;
6963
use executor_primitives::AccountId;
7064
use executor_primitives::ChainAsset;
7165
use parentchain_rpc_client::metadata::Metadata;
@@ -101,30 +95,27 @@ const SOLANA_USDC_MINT_ADDRESS: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyT
10195
const SOLANA_USDT_MINT_ADDRESS: &str = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB";
10296

10397
// TODO: should we rename this to something like MultiChainIntentExecutor?
104-
pub struct CrossChainIntentExecutor<Provider: EthereumRpcProvider<Transaction = TransactionRequest>>
105-
{
98+
pub struct CrossChainIntentExecutor<BinanceClient: BinanceApi> {
10699
// account_asset_lock: AccountAssetLocks<AlwaysUnlockedAssetsLock>,
107100
// rpc_endpoint_registry: RpcEndpointRegistry,
108101
pumpx_signer_client: Arc<Box<dyn SignerClient>>,
109102
pumpx_api: Arc<Box<dyn PumpxApi>>,
110103
storage_db: Arc<StorageDB>,
111-
binance_api: Arc<BinanceApi>,
104+
binance_api: Arc<BinanceClient>,
112105
solana_client: Arc<Box<dyn SolanaClient>>,
113-
accounting_contract_client: Arc<AccountingContractClient<Provider>>,
106+
accounting_contract_client: Arc<Box<dyn AccountingContractApi>>,
114107
}
115108

116-
impl<Provider: EthereumRpcProvider<Transaction = TransactionRequest>>
117-
CrossChainIntentExecutor<Provider>
118-
{
109+
impl<BinanceClient: BinanceApi> CrossChainIntentExecutor<BinanceClient> {
119110
#[allow(clippy::too_many_arguments)]
120111
pub fn new(
121112
_rpc_endpoint_registry: RpcEndpointRegistry,
122113
pumpx_signer_client: Arc<Box<dyn SignerClient>>,
123114
pumpx_api: Arc<Box<dyn PumpxApi>>,
124115
storage_db: Arc<StorageDB>,
125-
binance_api: Arc<BinanceApi>,
116+
binance_api: Arc<BinanceClient>,
126117
solana_client: Arc<Box<dyn SolanaClient>>,
127-
accounting_contract_client: Arc<AccountingContractClient<Provider>>,
118+
accounting_contract_client: Arc<Box<dyn AccountingContractApi>>,
128119
) -> Result<Self, ()> {
129120
// there is no need for account/assets locks if we guarantee the dest-chain payout happens after the source chain finalisation
130121
// let account_asset_lock = AccountAssetLocks::<AlwaysUnlockedAssetsLock>::empty();
@@ -142,9 +133,7 @@ impl<Provider: EthereumRpcProvider<Transaction = TransactionRequest>>
142133
}
143134

144135
#[async_trait]
145-
impl<Provider: EthereumRpcProvider<Transaction = TransactionRequest> + Send + Sync> IntentExecutor
146-
for CrossChainIntentExecutor<Provider>
147-
{
136+
impl<BinanceClient: BinanceApi> IntentExecutor for CrossChainIntentExecutor<BinanceClient> {
148137
#[allow(unused_assignments)]
149138
async fn execute(
150139
&self,
@@ -1127,8 +1116,8 @@ mod tests {
11271116
}
11281117
}
11291118

1130-
async fn estimate_bnb_amount(
1131-
binance_api: &Arc<BinanceApi>,
1119+
async fn estimate_bnb_amount<BinanceClient: BinanceApi>(
1120+
binance_api: &Arc<BinanceClient>,
11321121
trade_symbol: &str,
11331122
binance_coin_name: &str,
11341123
from_amount_decimal: Decimal,

0 commit comments

Comments
 (0)