Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: send txs to relayer #59

Merged
merged 2 commits into from
Apr 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 78 additions & 43 deletions mpc-recovery/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
use near_jsonrpc_client::{methods, JsonRpcClient, MethodCallResult};
use hyper::{Body, Client, Method, Request};
use near_jsonrpc_client::{methods, JsonRpcClient};
use near_jsonrpc_primitives::types::query::QueryResponseKind;
use near_primitives::delegate_action::SignedDelegateAction;
use near_primitives::hash::CryptoHash;
use near_primitives::transaction::SignedTransaction;
use near_primitives::types::{AccountId, BlockHeight, Finality};
use near_primitives::views::{AccessKeyView, FinalExecutionOutcomeView, QueryRequest};
use near_primitives::views::{AccessKeyView, QueryRequest};
use serde_json::json;

const RELAYER_URI: &str = "http://34.70.226.83:3030";

#[derive(Clone)]
pub struct NearRpcClient {
Expand Down Expand Up @@ -42,36 +46,6 @@ impl NearRpcClient {
}
}

// TODO: delete this function if we will use reqest to communicate with the relayer
async fn _query_broadcast_tx(
&self,
method: &methods::broadcast_tx_commit::RpcBroadcastTxCommitRequest,
) -> MethodCallResult<
FinalExecutionOutcomeView,
near_jsonrpc_primitives::types::transactions::RpcTransactionError,
> {
let result = self.rpc_client.call(method).await;
match &result {
Ok(response) => {
tracing::debug!(
target: "client",
"Submitting transaction with actions {:?} succeeded with status {:?}",
method.signed_transaction.transaction.actions,
response.status
);
}
Err(error) => {
tracing::error!(
target: "client",
"Calling RPC method {:?} resulted in error {:?}",
method,
error
);
}
};
result
}

pub async fn access_key_nonce(
&self,
account_id: AccountId,
Expand All @@ -91,18 +65,79 @@ impl NearRpcClient {
Ok(block_view.header.height)
}

// TODO: delete this function if we will use reqest to communicate with the relayer
pub async fn _send_tx(
#[tracing::instrument(level = "debug", skip_all, fields(account_id))]
pub async fn register_account_with_relayer(&self, account_id: AccountId) -> anyhow::Result<()> {
let json_payload = json!({
"account_id": account_id.to_string(),
"allowance": 20000000000000u64
})
.to_string();

tracing::debug!(
"constructed json payload, {} bytes total",
json_payload.len()
);

let request = Request::builder()
.method(Method::POST)
.uri(format!("{}/register_account", RELAYER_URI))
.header("content-type", "application/json")
.body(Body::from(json_payload))
.unwrap();

tracing::debug!("constructed http request to {RELAYER_URI}");
let client = Client::new();
let response = client.request(request).await?;

if response.status().is_success() {
let response_body = hyper::body::to_bytes(response.into_body()).await?;
tracing::debug!("success: {}", std::str::from_utf8(&response_body)?)
} else {
let response_body = hyper::body::to_bytes(response.into_body()).await?;
anyhow::bail!(
"transaction failed: {}",
std::str::from_utf8(&response_body)?
)
}

Ok(())
}

#[tracing::instrument(level = "debug", skip_all, fields(receiver_id = signed_delegate_action.delegate_action.receiver_id.to_string()))]
pub async fn send_tx_via_relayer(
&self,
signed_transaction: SignedTransaction,
) -> anyhow::Result<FinalExecutionOutcomeView> {
let result = self
._query_broadcast_tx(&methods::broadcast_tx_commit::RpcBroadcastTxCommitRequest {
signed_transaction,
})
.await?;
signed_delegate_action: SignedDelegateAction,
) -> anyhow::Result<()> {
let json_payload = serde_json::to_vec(&signed_delegate_action)?;

tracing::debug!(
"constructed json payload, {} bytes total",
json_payload.len()
);

let request = Request::builder()
.method(Method::POST)
.uri(format!("{}/send_meta_tx", RELAYER_URI))
.header("content-type", "application/json")
.body(Body::from(json_payload))
.unwrap();

Ok(result)
tracing::debug!("constructed http request to {RELAYER_URI}");
let client = Client::new();
let response = client.request(request).await?;

if response.status().is_success() {
let response_body = hyper::body::to_bytes(response.into_body()).await?;
tracing::debug!("success: {}", std::str::from_utf8(&response_body)?)
} else {
let response_body = hyper::body::to_bytes(response.into_body()).await?;
anyhow::bail!(
"transaction failed: {}",
std::str::from_utf8(&response_body)?
)
}

Ok(())
}
}

Expand Down
27 changes: 16 additions & 11 deletions mpc-recovery/src/leader_node/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,19 +118,24 @@ async fn process_new_account(
let delegate_action = get_create_account_delegate_action(
account_creator_id.clone(),
account_creator_pk,
new_user_account_id,
new_user_account_id.clone(),
get_user_recovery_pk(internal_user_id),
crate::transaction::NetworkType::Testnet,
nonce,
block_height + 100,
);
let _signed_delegate_action =
let signed_delegate_action =
get_signed_delegated_action(delegate_action, account_creator_id, account_creator_sk);

// Send the transaction to the relayer
// TODO: currently client doesn't support sending delegated actions to the relayer,
// use request directly or add support to the client
// state.client.send_tx(signed_create_acc_tx).await?;
state
itegulov marked this conversation as resolved.
Show resolved Hide resolved
.client
.register_account_with_relayer(new_user_account_id)
.await?;

state
.client
.send_tx_via_relayer(signed_delegate_action)
.await?;

Ok((StatusCode::OK, Json(NewAccountResponse::Ok)))
}
Expand Down Expand Up @@ -201,16 +206,16 @@ async fn process_add_key(
nonce,
max_block_height,
);
let _signed_delegate_action = get_signed_delegated_action(
let signed_delegate_action = get_signed_delegated_action(
delegate_action,
user_account_id,
get_user_recovery_sk(internal_user_id.clone()),
);

// Send the transaction to the relayer
// TODO: currently client doesn't support sending delegated actions to the relayer,
// use request directly or add support to the client
// state.client.send_tx(signed_add_key_tx).await?;
state
.client
.send_tx_via_relayer(signed_delegate_action)
.await?;

Ok((StatusCode::OK, Json(AddKeyResponse::Ok)))
}
Expand Down