Skip to content

Commit 601a50d

Browse files
authored
feat: add fund_payment_service and get_balance_in_payment_sevice on sdk (#1142)
1 parent ed05207 commit 601a50d

File tree

3 files changed

+122
-90
lines changed

3 files changed

+122
-90
lines changed

batcher/aligned-sdk/src/core/errors.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,3 +306,16 @@ impl fmt::Display for VerifySignatureError {
306306
}
307307
}
308308
}
309+
310+
#[derive(Debug)]
311+
pub enum PaymentError {
312+
SendError(String),
313+
SubmitError(String),
314+
PaymentFailed,
315+
}
316+
317+
#[derive(Debug)]
318+
pub enum BalanceError {
319+
EthereumProviderError(String),
320+
EthereumCallError(String),
321+
}

batcher/aligned-sdk/src/sdk.rs

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,11 @@ use crate::{
2222
};
2323

2424
use ethers::{
25+
core::types::TransactionRequest,
26+
middleware::SignerMiddleware,
2527
prelude::k256::ecdsa::SigningKey,
2628
providers::{Http, Middleware, Provider},
27-
signers::Wallet,
29+
signers::{LocalWallet, Wallet},
2830
types::{Address, H160, U256},
2931
};
3032
use sha3::{Digest, Keccak256};
@@ -582,6 +584,77 @@ pub async fn get_chain_id(eth_rpc_url: &str) -> Result<u64, errors::ChainIdError
582584
Ok(chain_id.as_u64())
583585
}
584586

587+
/// Funds the batcher payment service in name of the signer
588+
/// # Arguments
589+
/// * `amount` - The amount to be paid.
590+
/// * `signer` - The signer middleware of the payer.
591+
/// * `network` - The network on which the payment will be done.
592+
/// # Returns
593+
/// * The receipt of the payment transaction.
594+
/// # Errors
595+
/// * `SendError` if there is an error sending the transaction.
596+
/// * `SubmitError` if there is an error submitting the transaction.
597+
/// * `PaymentFailed` if the payment failed.
598+
pub async fn deposit_to_aligned(
599+
amount: U256,
600+
signer: SignerMiddleware<Provider<Http>, LocalWallet>,
601+
network: Network,
602+
) -> Result<ethers::types::TransactionReceipt, errors::PaymentError> {
603+
let payment_service_address = get_payment_service_address(network);
604+
let from = signer.address();
605+
606+
let tx = TransactionRequest::new()
607+
.from(from)
608+
.to(payment_service_address)
609+
.value(amount);
610+
611+
match signer
612+
.send_transaction(tx, None)
613+
.await
614+
.map_err(|e| errors::PaymentError::SendError(e.to_string()))?
615+
.await
616+
.map_err(|e| errors::PaymentError::SubmitError(e.to_string()))?
617+
{
618+
Some(receipt) => Ok(receipt),
619+
None => Err(errors::PaymentError::PaymentFailed),
620+
}
621+
}
622+
623+
/// Returns the balance of a user in the payment service.
624+
/// # Arguments
625+
/// * `user` - The address of the user.
626+
/// * `eth_rpc_url` - The URL of the Ethereum RPC node.
627+
/// * `network` - The network on which the balance will be checked.
628+
/// # Returns
629+
/// * The balance of the user in the payment service.
630+
/// # Errors
631+
/// * `EthereumProviderError` if there is an error in the connection with the RPC provider.
632+
/// * `EthereumCallError` if there is an error in the Ethereum call.
633+
pub async fn get_balance_in_aligned(
634+
user: Address,
635+
eth_rpc_url: &str,
636+
network: Network,
637+
) -> Result<U256, errors::BalanceError> {
638+
let eth_rpc_provider = Provider::<Http>::try_from(eth_rpc_url)
639+
.map_err(|e| errors::BalanceError::EthereumProviderError(e.to_string()))?;
640+
641+
let payment_service_address = get_payment_service_address(network);
642+
643+
match batcher_payment_service(eth_rpc_provider, payment_service_address).await {
644+
Ok(batcher_payment_service) => {
645+
let call = batcher_payment_service.user_balances(user);
646+
647+
let result = call
648+
.call()
649+
.await
650+
.map_err(|e| errors::BalanceError::EthereumCallError(e.to_string()))?;
651+
652+
Ok(result)
653+
}
654+
Err(e) => Err(errors::BalanceError::EthereumCallError(e.to_string())),
655+
}
656+
}
657+
585658
#[cfg(test)]
586659
mod test {
587660
//Public constants for convenience

batcher/aligned/src/main.rs

Lines changed: 35 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use aligned_sdk::core::{
1414
};
1515
use aligned_sdk::sdk::get_chain_id;
1616
use aligned_sdk::sdk::get_next_nonce;
17-
use aligned_sdk::sdk::get_payment_service_address;
17+
use aligned_sdk::sdk::{deposit_to_aligned, get_balance_in_aligned};
1818
use aligned_sdk::sdk::{get_vk_commitment, is_proof_verified, submit_multiple};
1919
use clap::Parser;
2020
use clap::Subcommand;
@@ -418,6 +418,10 @@ async fn main() -> Result<(), AlignedError> {
418418

419419
let amount = deposit_to_batcher_args.amount.replace("ether", "");
420420

421+
let amount_ether = parse_ether(&amount).map_err(|e| {
422+
SubmitError::EthereumProviderError(format!("Error while parsing amount: {}", e))
423+
})?;
424+
421425
let eth_rpc_url = deposit_to_batcher_args.eth_rpc_url;
422426

423427
let eth_rpc_provider =
@@ -445,99 +449,41 @@ async fn main() -> Result<(), AlignedError> {
445449

446450
let client = SignerMiddleware::new(eth_rpc_provider.clone(), wallet.clone());
447451

448-
let balance = client
449-
.get_balance(wallet.address(), None)
452+
match deposit_to_aligned(amount_ether, client, deposit_to_batcher_args.network.into())
450453
.await
451-
.map_err(|e| {
452-
SubmitError::EthereumProviderError(format!(
453-
"Error while getting balance: {}",
454-
e
455-
))
456-
})?;
457-
458-
let amount_ether = parse_ether(&amount).map_err(|e| {
459-
SubmitError::EthereumProviderError(format!("Error while parsing amount: {}", e))
460-
})?;
461-
462-
if amount_ether <= U256::from(0) {
463-
error!("Amount should be greater than 0");
464-
return Ok(());
465-
}
466-
467-
if balance < amount_ether {
468-
error!("Insufficient funds to pay to the batcher. Please deposit some Ether in your wallet.");
469-
return Ok(());
470-
}
471-
472-
let batcher_addr = get_payment_service_address(deposit_to_batcher_args.network.into());
473-
474-
let tx = TransactionRequest::new()
475-
.to(batcher_addr)
476-
.value(amount_ether)
477-
.from(wallet.address());
478-
479-
info!("Sending {} ether to the batcher", amount);
480-
481-
let tx = client
482-
.send_transaction(tx, None)
483-
.await
484-
.map_err(|e| {
485-
SubmitError::EthereumProviderError(format!(
486-
"Error while sending transaction: {}",
487-
e
488-
))
489-
})?
490-
.await
491-
.map_err(|e| {
492-
SubmitError::EthereumProviderError(format!(
493-
"Error while sending transaction: {}",
494-
e
495-
))
496-
})?;
497-
498-
if let Some(tx) = tx {
499-
info!(
500-
"Payment sent to the batcher successfully. Tx: 0x{:x}",
501-
tx.transaction_hash
502-
);
503-
} else {
504-
error!("Transaction failed");
454+
{
455+
Ok(receipt) => {
456+
info!(
457+
"Payment sent to the batcher successfully. Tx: 0x{:x}",
458+
receipt.transaction_hash
459+
);
460+
}
461+
Err(e) => {
462+
error!("Transaction failed: {:?}", e);
463+
}
505464
}
506465
}
507466
GetUserBalance(get_user_balance_args) => {
508-
let eth_rpc_url = get_user_balance_args.eth_rpc_url;
509-
510-
let eth_rpc_provider = Provider::<Http>::try_from(eth_rpc_url).map_err(|e| {
511-
SubmitError::EthereumProviderError(format!(
512-
"Error while connecting to Ethereum: {}",
513-
e
514-
))
515-
})?;
516-
517-
let user_address =
518-
Address::from_str(&get_user_balance_args.user_address).map_err(|e| {
519-
SubmitError::HexDecodingError(format!(
520-
"Error while parsing user address: {}",
521-
e
522-
))
523-
})?;
524-
525-
let batcher_addr = get_payment_service_address(get_user_balance_args.network.into());
526-
527-
let balance = get_user_balance(eth_rpc_provider, batcher_addr, user_address)
528-
.await
529-
.map_err(|e| {
530-
SubmitError::EthereumProviderError(format!(
531-
"Error while getting user balance: {}",
532-
e
533-
))
534-
})?;
535-
536-
info!(
537-
"User {} has {} ether in the batcher",
467+
let user_address = H160::from_str(&get_user_balance_args.user_address).unwrap();
468+
match get_balance_in_aligned(
538469
user_address,
539-
format_ether(balance)
540-
);
470+
&get_user_balance_args.eth_rpc_url,
471+
get_user_balance_args.network.into(),
472+
)
473+
.await
474+
{
475+
Ok(balance) => {
476+
info!(
477+
"User {} has {} ether in the batcher",
478+
user_address,
479+
format_ether(balance)
480+
);
481+
}
482+
Err(e) => {
483+
error!("Error while getting user balance: {:?}", e);
484+
return Ok(());
485+
}
486+
}
541487
}
542488
}
543489

0 commit comments

Comments
 (0)