-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathsend.rs
More file actions
652 lines (588 loc) · 26 KB
/
send.rs
File metadata and controls
652 lines (588 loc) · 26 KB
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
use std::fmt;
use std::sync::Arc;
use near_openapi_client::types::{
ErrorWrapperForRpcTransactionError, FinalExecutionOutcomeView, JsonRpcRequestForSendTx,
JsonRpcResponseForRpcTransactionResponseAndRpcTransactionError, RpcSendTransactionRequest,
RpcTransactionError, RpcTransactionResponse,
};
use near_api_types::{
BlockHeight, CryptoHash, Nonce, PublicKey, TxExecutionStatus,
transaction::{
PrepopulateTransaction, SignedTransaction,
delegate_action::{SignedDelegateAction, SignedDelegateActionAsBase64},
result::{ExecutionFinalResult, TransactionResult},
},
};
use reqwest::Response;
use tracing::{debug, info};
use crate::{
common::utils::{is_critical_transaction_error, to_retry_error},
config::{NetworkConfig, RetryResponse, retry},
errors::{
ArgumentValidationError, ExecuteMetaTransactionsError, ExecuteTransactionError,
MetaSignError, SendRequestError, SignerError, ValidationError,
},
signer::Signer,
};
use super::META_TRANSACTION_VALID_FOR_DEFAULT;
const TX_EXECUTOR_TARGET: &str = "near_api::tx::executor";
const META_EXECUTOR_TARGET: &str = "near_api::meta::executor";
/// Internal enum to distinguish between a full RPC response and a minimal pending response.
enum SendImplResponse {
Full(Box<RpcTransactionResponse>),
Pending(TxExecutionStatus),
}
impl fmt::Debug for SendImplResponse {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Full(_) => write!(f, "Full(...)"),
Self::Pending(status) => write!(f, "Pending({status:?})"),
}
}
}
/// Minimal JSON-RPC response returned when `wait_until` is `NONE` or `INCLUDED`.
///
/// The RPC returns only `{"jsonrpc":"2.0","result":{"final_execution_status":"..."},"id":"0"}`
/// which doesn't match the full `RpcTransactionResponse` schema.
#[derive(serde::Deserialize)]
struct MinimalTransactionResponse {
result: MinimalTransactionResult,
}
#[derive(serde::Deserialize)]
struct MinimalTransactionResult {
final_execution_status: TxExecutionStatus,
}
#[async_trait::async_trait]
pub trait Transactionable: Send + Sync {
fn prepopulated(&self) -> Result<PrepopulateTransaction, ArgumentValidationError>;
/// Validate the transaction before sending it to the network
async fn validate_with_network(&self, network: &NetworkConfig) -> Result<(), ValidationError>;
/// Edit the transaction before sending it to the network.
/// This is useful for example to add storage deposit to the transaction
/// if it's needed.
/// Though, it won't be called if the user has presigned the transaction.
async fn edit_with_network(&mut self, _network: &NetworkConfig) -> Result<(), ValidationError> {
Ok(())
}
}
pub enum TransactionableOrSigned<Signed> {
/// A transaction that is not signed.
Transactionable(Box<dyn Transactionable + 'static>),
/// A transaction that is signed and ready to be sent to the network.
Signed((Signed, Box<dyn Transactionable + 'static>)),
}
impl<Signed> TransactionableOrSigned<Signed> {
pub fn signed(self) -> Option<Signed> {
match self {
Self::Signed((signed, _)) => Some(signed),
Self::Transactionable(_) => None,
}
}
}
impl<S> TransactionableOrSigned<S> {
pub fn transactionable(self) -> Box<dyn Transactionable> {
match self {
Self::Transactionable(transaction) => transaction,
Self::Signed((_, transaction)) => transaction,
}
}
}
/// The handler for signing and sending transaction to the network.
///
/// This is the main entry point for the transaction sending functionality.
pub struct ExecuteSignedTransaction {
/// The transaction that is either not signed yet or already signed.
pub transaction: TransactionableOrSigned<SignedTransaction>,
/// The signer that will be used to sign the transaction.
pub signer: Arc<Signer>,
pub wait_until: TxExecutionStatus,
}
impl ExecuteSignedTransaction {
pub fn new<T: Transactionable + 'static>(transaction: T, signer: Arc<Signer>) -> Self {
Self {
transaction: TransactionableOrSigned::Transactionable(Box::new(transaction)),
signer,
wait_until: TxExecutionStatus::Final,
}
}
/// Changes the transaction to a [meta transaction](https://docs.near.org/concepts/abstraction/meta-transactions), allowing some 3rd party entity to execute it and
/// pay for the gas.
///
/// Please note, that if you already presigned the transaction, it would require you to sign it again as a meta transaction
/// is a different type of transaction.
pub fn meta(self) -> ExecuteMetaTransaction {
ExecuteMetaTransaction::from_box(self.transaction.transactionable(), self.signer)
}
pub const fn wait_until(mut self, wait_until: TxExecutionStatus) -> Self {
self.wait_until = wait_until;
self
}
/// Signs the transaction offline without fetching the nonce or block hash from the network.
///
/// The transaction won't be broadcasted to the network and just stored signed in the [Self::transaction] struct variable.
///
/// This is useful if you already have the nonce and block hash, or if you want to sign the transaction
/// offline. Please note that incorrect nonce will lead to transaction failure.
pub async fn presign_offline(
mut self,
public_key: PublicKey,
block_hash: CryptoHash,
nonce: Nonce,
) -> Result<Self, ExecuteTransactionError> {
let transaction = match &self.transaction {
TransactionableOrSigned::Transactionable(transaction) => transaction,
TransactionableOrSigned::Signed(_) => return Ok(self),
};
let transaction = transaction.prepopulated()?;
let signed_tr = self
.signer
.sign(transaction, public_key, nonce, block_hash)
.await?;
self.transaction =
TransactionableOrSigned::Signed((signed_tr, self.transaction.transactionable()));
Ok(self)
}
/// Signs the transaction with the custom network configuration but doesn't broadcast it.
///
/// Signed transaction is stored in the [Self::transaction] struct variable.
///
/// This is useful if you want to sign with non-default network configuration (e.g, custom RPC URL, sandbox).
/// The provided call will fetch the nonce and block hash from the given network.
pub async fn presign_with(
self,
network: &NetworkConfig,
) -> Result<Self, ExecuteTransactionError> {
let transaction = match &self.transaction {
TransactionableOrSigned::Transactionable(transaction) => transaction,
TransactionableOrSigned::Signed(_) => return Ok(self),
};
let transaction = transaction.prepopulated()?;
let signer_key = self
.signer
.get_public_key()
.await
.map_err(SignerError::from)?;
let (nonce, hash, _) = self
.signer
.fetch_tx_nonce(transaction.signer_id.clone(), signer_key, network)
.await
.map_err(MetaSignError::from)?;
self.presign_offline(signer_key, hash, nonce).await
}
/// Signs the transaction with the default mainnet configuration. Does not broadcast it.
///
/// Signed transaction is stored in the [Self::transaction] struct variable.
///
/// The provided call will fetch the nonce and block hash from the network.
pub async fn presign_with_mainnet(self) -> Result<Self, ExecuteTransactionError> {
let network = NetworkConfig::mainnet();
self.presign_with(&network).await
}
/// Signs the transaction with the default testnet configuration. Does not broadcast it.
///
/// Signed transaction is stored in the [Self::transaction] struct variable.
///
/// The provided call will fetch the nonce and block hash from the network.
pub async fn presign_with_testnet(self) -> Result<Self, ExecuteTransactionError> {
let network = NetworkConfig::testnet();
self.presign_with(&network).await
}
/// Sends the transaction to the custom provided network.
///
/// This is useful if you want to send the transaction to a non-default network configuration (e.g, custom RPC URL, sandbox).
/// Please note that if the transaction is not presigned, it will be signed with the network's nonce and block hash.
///
/// Returns a [`TransactionResult`] which is either:
/// - [`TransactionResult::Pending`] if `wait_until` is `None` or `Included` (no execution data available yet)
/// - [`TransactionResult::Full`] for higher finality levels with full execution results
pub async fn send_to(
mut self,
network: &NetworkConfig,
) -> Result<TransactionResult, ExecuteTransactionError> {
let (signed, transactionable) = match &mut self.transaction {
TransactionableOrSigned::Transactionable(transaction) => {
debug!(target: TX_EXECUTOR_TARGET, "Preparing unsigned transaction");
(None, transaction)
}
TransactionableOrSigned::Signed((s, transaction)) => {
debug!(target: TX_EXECUTOR_TARGET, "Using pre-signed transaction");
(Some(s.clone()), transaction)
}
};
let wait_until = self.wait_until;
if signed.is_none() {
debug!(target: TX_EXECUTOR_TARGET, "Editing transaction with network config");
transactionable.edit_with_network(network).await?;
} else {
debug!(target: TX_EXECUTOR_TARGET, "Validating pre-signed transaction with network config");
transactionable.validate_with_network(network).await?;
}
let signed = match signed {
Some(s) => s,
None => {
debug!(target: TX_EXECUTOR_TARGET, "Signing transaction");
self.presign_with(network)
.await?
.transaction
.signed()
.expect("Expect to have it signed")
}
};
info!(
target: TX_EXECUTOR_TARGET,
"Broadcasting signed transaction. Hash: {:?}, Signer: {:?}, Receiver: {:?}, Nonce: {}",
signed.get_hash(),
signed.transaction.signer_id(),
signed.transaction.receiver_id(),
signed.transaction.nonce(),
);
Self::send_impl(network, signed, wait_until).await
}
/// Sends the transaction to the default mainnet configuration.
///
/// Please note that this will sign the transaction with the mainnet's nonce and block hash if it's not presigned yet.
pub async fn send_to_mainnet(self) -> Result<TransactionResult, ExecuteTransactionError> {
let network = NetworkConfig::mainnet();
self.send_to(&network).await
}
/// Sends the transaction to the default testnet configuration.
///
/// Please note that this will sign the transaction with the testnet's nonce and block hash if it's not presigned yet.
pub async fn send_to_testnet(self) -> Result<TransactionResult, ExecuteTransactionError> {
let network = NetworkConfig::testnet();
self.send_to(&network).await
}
async fn send_impl(
network: &NetworkConfig,
signed_tr: SignedTransaction,
wait_until: TxExecutionStatus,
) -> Result<TransactionResult, ExecuteTransactionError> {
let hash = signed_tr.get_hash();
let signed_tx_base64: near_openapi_client::types::SignedTransaction = signed_tr.into();
let result = retry(network.clone(), |client| {
let signed_tx_base64 = signed_tx_base64.clone();
async move {
let result = match client
.send_tx(&JsonRpcRequestForSendTx {
id: "0".to_string(),
jsonrpc: "2.0".to_string(),
method: near_openapi_client::types::JsonRpcRequestForSendTxMethod::SendTx,
params: RpcSendTransactionRequest {
signed_tx_base64,
wait_until,
},
})
.await
.map(|r| r.into_inner())
.map_err(SendRequestError::from)
{
Ok(
JsonRpcResponseForRpcTransactionResponseAndRpcTransactionError::Variant0 {
result,
..
},
) => RetryResponse::Ok(SendImplResponse::Full(Box::new(result))),
Ok(
JsonRpcResponseForRpcTransactionResponseAndRpcTransactionError::Variant1 {
error,
..
},
) => {
let error: SendRequestError<RpcTransactionError> =
SendRequestError::from(error);
to_retry_error(error, is_critical_transaction_error)
}
Err(err) => {
// When wait_until is NONE or INCLUDED, the RPC returns a minimal
// response with only `final_execution_status`. The openapi client
// fails to deserialize this into RpcTransactionResponse (which
// expects full execution data) and returns InvalidResponsePayload.
// We intercept this case and parse the minimal response ourselves.
//
// We only attempt this fallback when we explicitly requested a
// minimal response, so unexpected/buggy RPC responses for higher
// finality levels don't get silently treated as Pending.
if matches!(
wait_until,
TxExecutionStatus::None | TxExecutionStatus::Included
) {
if let SendRequestError::TransportError(
near_openapi_client::Error::InvalidResponsePayload(ref bytes, _),
) = err
{
if let Ok(minimal) =
serde_json::from_slice::<MinimalTransactionResponse>(bytes)
{
return RetryResponse::Ok(SendImplResponse::Pending(
minimal.result.final_execution_status,
));
}
}
}
to_retry_error(err, is_critical_transaction_error)
}
};
tracing::debug!(
target: TX_EXECUTOR_TARGET,
"Broadcasting transaction {} resulted in {:?}",
hash,
result
);
result
}
})
.await
.map_err(ExecuteTransactionError::TransactionError)?;
match result {
SendImplResponse::Pending(status) => Ok(TransactionResult::Pending { status }),
SendImplResponse::Full(rpc_response) => {
let final_execution_outcome_view = match *rpc_response {
// We don't use `experimental_tx`, so we can ignore that, but just to be safe
RpcTransactionResponse::Variant0 {
final_execution_status: _,
receipts: _,
receipts_outcome,
status,
transaction,
transaction_outcome,
} => FinalExecutionOutcomeView {
receipts_outcome,
status,
transaction,
transaction_outcome,
},
RpcTransactionResponse::Variant1 {
final_execution_status: _,
receipts_outcome,
status,
transaction,
transaction_outcome,
} => FinalExecutionOutcomeView {
receipts_outcome,
status,
transaction,
transaction_outcome,
},
};
Ok(TransactionResult::Full(Box::new(
ExecutionFinalResult::try_from(final_execution_outcome_view)?,
)))
}
}
}
}
pub struct ExecuteMetaTransaction {
pub transaction: TransactionableOrSigned<SignedDelegateAction>,
pub signer: Arc<Signer>,
pub tx_live_for: Option<BlockHeight>,
}
impl ExecuteMetaTransaction {
pub fn new<T: Transactionable + 'static>(transaction: T, signer: Arc<Signer>) -> Self {
Self {
transaction: TransactionableOrSigned::Transactionable(Box::new(transaction)),
signer,
tx_live_for: None,
}
}
pub fn from_box(transaction: Box<dyn Transactionable + 'static>, signer: Arc<Signer>) -> Self {
Self {
transaction: TransactionableOrSigned::Transactionable(transaction),
signer,
tx_live_for: None,
}
}
/// Sets the transaction live for the given block amount.
///
/// This is useful if you want to set the transaction to be valid for a specific amount of blocks.\
/// The default amount is 1000 blocks.
pub const fn tx_live_for(mut self, tx_live_for: BlockHeight) -> Self {
self.tx_live_for = Some(tx_live_for);
self
}
/// Signs the transaction offline without fetching the nonce or block hash from the network. Does not broadcast it.
///
/// Signed transaction is stored in the [Self::transaction] struct variable.
///
/// This is useful if you already have the nonce and block hash, or if you want to sign the transaction
/// offline. Please note that incorrect nonce will lead to transaction failure and incorrect block height
/// will lead to incorrectly populated transaction live value.
pub async fn presign_offline(
mut self,
signer_key: PublicKey,
block_hash: CryptoHash,
nonce: Nonce,
block_height: BlockHeight,
) -> Result<Self, ExecuteMetaTransactionsError> {
let transaction = match &self.transaction {
TransactionableOrSigned::Transactionable(transaction) => transaction,
TransactionableOrSigned::Signed(_) => return Ok(self),
};
let transaction = transaction.prepopulated()?;
let max_block_height = block_height
+ self
.tx_live_for
.unwrap_or(META_TRANSACTION_VALID_FOR_DEFAULT);
let signed_tr = self
.signer
.sign_meta(transaction, signer_key, nonce, block_hash, max_block_height)
.await?;
self.transaction =
TransactionableOrSigned::Signed((signed_tr, self.transaction.transactionable()));
Ok(self)
}
/// Signs the transaction with the custom network configuration but doesn't broadcast it.
///
/// Signed transaction is stored in the [Self::transaction] struct variable.
///
/// This is useful if you want to sign with non-default network configuration (e.g, custom RPC URL, sandbox).
pub async fn presign_with(
self,
network: &NetworkConfig,
) -> Result<Self, ExecuteMetaTransactionsError> {
let transaction = match &self.transaction {
TransactionableOrSigned::Transactionable(transaction) => transaction,
TransactionableOrSigned::Signed(_) => return Ok(self),
};
let transaction = transaction.prepopulated()?;
let signer_key = self
.signer
.get_public_key()
.await
.map_err(SignerError::from)
.map_err(MetaSignError::from)?;
let (nonce, block_hash, block_height) = self
.signer
.fetch_tx_nonce(transaction.signer_id.clone(), signer_key, network)
.await
.map_err(MetaSignError::from)?;
self.presign_offline(signer_key, block_hash, nonce, block_height)
.await
}
/// Signs the transaction with the default mainnet configuration but doesn't broadcast it.
///
/// Signed transaction is stored in the [Self::transaction] struct variable.
///
/// The provided call will fetch the nonce and block hash, block height from the network.
pub async fn presign_with_mainnet(self) -> Result<Self, ExecuteMetaTransactionsError> {
let network = NetworkConfig::mainnet();
self.presign_with(&network).await
}
/// Signs the transaction with the default testnet configuration but doesn't broadcast it.
///
/// Signed transaction is stored in the [Self::transaction] struct variable.
///
/// The provided call will fetch the nonce and block hash, block height from the network.
pub async fn presign_with_testnet(self) -> Result<Self, ExecuteMetaTransactionsError> {
let network = NetworkConfig::testnet();
self.presign_with(&network).await
}
/// Sends the transaction to the custom provided network.
///
/// This is useful if you want to send the transaction to a non-default network configuration (e.g, custom RPC URL, sandbox).
/// Please note that if the transaction is not presigned, it will be sign with the network's nonce and block hash.
pub async fn send_to(
mut self,
network: &NetworkConfig,
) -> Result<Response, ExecuteMetaTransactionsError> {
let (signed, transactionable) = match &mut self.transaction {
TransactionableOrSigned::Transactionable(transaction) => {
debug!(target: META_EXECUTOR_TARGET, "Preparing unsigned meta transaction");
(None, transaction)
}
TransactionableOrSigned::Signed((s, transaction)) => {
debug!(target: META_EXECUTOR_TARGET, "Using pre-signed meta transaction");
(Some(s.clone()), transaction)
}
};
if signed.is_none() {
debug!(target: META_EXECUTOR_TARGET, "Editing meta transaction with network config");
transactionable.edit_with_network(network).await?;
} else {
debug!(target: META_EXECUTOR_TARGET, "Validating pre-signed meta transaction with network config");
transactionable.validate_with_network(network).await?;
}
let signed = match signed {
Some(s) => s,
None => {
debug!(target: META_EXECUTOR_TARGET, "Signing meta transaction");
self.presign_with(network)
.await?
.transaction
.signed()
.expect("Expect to have it signed")
}
};
info!(
target: META_EXECUTOR_TARGET,
"Broadcasting signed meta transaction. Signer: {:?}, Receiver: {:?}, Nonce: {}, Valid until: {}",
signed.delegate_action.sender_id,
signed.delegate_action.receiver_id,
signed.delegate_action.nonce,
signed.delegate_action.max_block_height
);
Self::send_impl(network, signed).await
}
/// Sends the transaction to the default mainnet configuration.
///
/// Please note that this will sign the transaction with the mainnet's nonce and block hash if it's not presigned yet.
pub async fn send_to_mainnet(self) -> Result<reqwest::Response, ExecuteMetaTransactionsError> {
let network = NetworkConfig::mainnet();
self.send_to(&network).await
}
/// Sends the transaction to the default testnet configuration.
///
/// Please note that this will sign the transaction with the testnet's nonce and block hash if it's not presigned yet.
pub async fn send_to_testnet(self) -> Result<reqwest::Response, ExecuteMetaTransactionsError> {
let network = NetworkConfig::testnet();
self.send_to(&network).await
}
async fn send_impl(
network: &NetworkConfig,
transaction: SignedDelegateAction,
) -> Result<reqwest::Response, ExecuteMetaTransactionsError> {
let client = reqwest::Client::new();
let json_payload = serde_json::json!({
"signed_delegate_action": SignedDelegateActionAsBase64::from(
transaction.clone()
).to_string(),
});
debug!(
target: META_EXECUTOR_TARGET,
"Sending meta transaction to relayer. Payload: {:?}",
json_payload
);
let resp = client
.post(
network
.meta_transaction_relayer_url
.clone()
.ok_or(ExecuteMetaTransactionsError::RelayerIsNotDefined)?,
)
.json(&json_payload)
.send()
.await?;
info!(
target: META_EXECUTOR_TARGET,
"Meta transaction sent to relayer. Status: {}, Signer: {:?}, Receiver: {:?}",
resp.status(),
transaction.delegate_action.sender_id,
transaction.delegate_action.receiver_id
);
Ok(resp)
}
}
impl From<ErrorWrapperForRpcTransactionError> for SendRequestError<RpcTransactionError> {
fn from(err: ErrorWrapperForRpcTransactionError) -> Self {
match err {
ErrorWrapperForRpcTransactionError::InternalError(internal_error) => {
Self::InternalError(internal_error)
}
ErrorWrapperForRpcTransactionError::RequestValidationError(
rpc_request_validation_error_kind,
) => Self::RequestValidationError(rpc_request_validation_error_kind),
ErrorWrapperForRpcTransactionError::HandlerError(server_error) => {
Self::ServerError(server_error)
}
}
}
}