/
transactions.rs
1574 lines (1482 loc) · 64.5 KB
/
transactions.rs
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright © Aptos Foundation
// Parts of the project are originally copyright © Meta Platforms, Inc.
// SPDX-License-Identifier: Apache-2.0
use crate::{
accept_type::AcceptType,
accounts::Account,
bcs_payload::Bcs,
context::{api_spawn_blocking, Context, FunctionStats},
failpoint::fail_point_poem,
generate_error_response, generate_success_response, metrics,
metrics::WAIT_TRANSACTION_GAUGE,
page::Page,
response::{
api_disabled, api_forbidden, transaction_not_found_by_hash,
transaction_not_found_by_version, version_pruned, BadRequestError, BasicError,
BasicErrorWith404, BasicResponse, BasicResponseStatus, BasicResult, BasicResultWith404,
ForbiddenError, InsufficientStorageError, InternalError,
},
ApiTags,
};
use anyhow::Context as AnyhowContext;
use aptos_api_types::{
verify_function_identifier, verify_module_identifier, Address, AptosError, AptosErrorCode,
AsConverter, EncodeSubmissionRequest, GasEstimation, GasEstimationBcs, HashValue,
HexEncodedBytes, LedgerInfo, MoveType, PendingTransaction, SubmitTransactionRequest,
Transaction, TransactionData, TransactionOnChainData, TransactionsBatchSingleSubmissionFailure,
TransactionsBatchSubmissionResult, UserTransaction, VerifyInput, VerifyInputWithRecursion,
MAX_RECURSIVE_TYPES_ALLOWED, U64,
};
use aptos_crypto::{hash::CryptoHash, signing_message};
use aptos_types::{
account_address::AccountAddress,
mempool_status::MempoolStatusCode,
transaction::{
EntryFunction, ExecutionStatus, MultisigTransactionPayload, RawTransaction,
RawTransactionWithData, SignedTransaction, TransactionPayload, TransactionStatus,
},
vm_status::StatusCode,
APTOS_COIN_TYPE,
};
use aptos_vm::{data_cache::AsMoveResolver, AptosSimulationVM, AptosVM};
use move_core_types::{ident_str, language_storage::ModuleId, vm_status::VMStatus};
use poem_openapi::{
param::{Path, Query},
payload::Json,
ApiRequest, OpenApi,
};
use std::{sync::Arc, time::Duration};
generate_success_response!(SubmitTransactionResponse, (202, Accepted));
generate_error_response!(
SubmitTransactionError,
(400, BadRequest),
(403, Forbidden),
(404, NotFound),
(413, PayloadTooLarge),
(500, Internal),
(503, ServiceUnavailable),
(507, InsufficientStorage)
);
type SubmitTransactionResult<T> =
poem::Result<SubmitTransactionResponse<T>, SubmitTransactionError>;
generate_success_response!(
SubmitTransactionsBatchResponse,
(202, Accepted),
(206, AcceptedPartial)
);
type SubmitTransactionsBatchResult<T> =
poem::Result<SubmitTransactionsBatchResponse<T>, SubmitTransactionError>;
type SimulateTransactionResult<T> = poem::Result<BasicResponse<T>, SubmitTransactionError>;
// TODO: Consider making both content types accept either
// SubmitTransactionRequest or SignedTransaction, the way
// it is now is quite confusing.
// We need a custom type here because we use different types for each of the
// content types possible for the POST data.
#[derive(ApiRequest, Debug)]
pub enum SubmitTransactionPost {
#[oai(content_type = "application/json")]
Json(Json<SubmitTransactionRequest>),
// TODO: Since I don't want to impl all the Poem derives on SignedTransaction,
// find a way to at least indicate in the spec that it expects a SignedTransaction.
// TODO: https://github.com/aptos-labs/aptos-core/issues/2275
#[oai(content_type = "application/x.aptos.signed_transaction+bcs")]
Bcs(Bcs),
}
impl VerifyInput for SubmitTransactionPost {
fn verify(&self) -> anyhow::Result<()> {
match self {
SubmitTransactionPost::Json(inner) => inner.0.verify(),
SubmitTransactionPost::Bcs(_) => Ok(()),
}
}
}
// We need a custom type here because we use different types for each of the
// content types possible for the POST data.
#[derive(ApiRequest, Debug)]
pub enum SubmitTransactionsBatchPost {
#[oai(content_type = "application/json")]
Json(Json<Vec<SubmitTransactionRequest>>),
// TODO: Since I don't want to impl all the Poem derives on SignedTransaction,
// find a way to at least indicate in the spec that it expects a SignedTransaction.
// TODO: https://github.com/aptos-labs/aptos-core/issues/2275
#[oai(content_type = "application/x.aptos.signed_transaction+bcs")]
Bcs(Bcs),
}
impl VerifyInput for SubmitTransactionsBatchPost {
fn verify(&self) -> anyhow::Result<()> {
match self {
SubmitTransactionsBatchPost::Json(inner) => {
for request in inner.0.iter() {
request.verify()?;
}
},
SubmitTransactionsBatchPost::Bcs(_) => {},
}
Ok(())
}
}
/// API for interacting with transactions
#[derive(Clone)]
pub struct TransactionsApi {
pub context: Arc<Context>,
}
#[OpenApi]
impl TransactionsApi {
/// Get transactions
///
/// Retrieve on-chain committed transactions. The page size and start ledger version
/// can be provided to get a specific sequence of transactions.
///
/// If the version has been pruned, then a 410 will be returned.
///
/// To retrieve a pending transaction, use /transactions/by_hash.
#[oai(
path = "/transactions",
method = "get",
operation_id = "get_transactions",
tag = "ApiTags::Transactions"
)]
async fn get_transactions(
&self,
accept_type: AcceptType,
/// Ledger version to start list of transactions
///
/// If not provided, defaults to showing the latest transactions
start: Query<Option<U64>>,
/// Max number of transactions to retrieve.
///
/// If not provided, defaults to default page size
limit: Query<Option<u16>>,
) -> BasicResultWith404<Vec<Transaction>> {
fail_point_poem("endpoint_get_transactions")?;
self.context
.check_api_output_enabled("Get transactions", &accept_type)?;
let page = Page::new(
start.0.map(|v| v.0),
limit.0,
self.context.max_transactions_page_size(),
);
let api = self.clone();
api_spawn_blocking(move || api.list(&accept_type, page)).await
}
/// Get transaction by hash
///
/// Look up a transaction by its hash. This is the same hash that is returned
/// by the API when submitting a transaction (see PendingTransaction).
///
/// When given a transaction hash, the server first looks for the transaction
/// in storage (on-chain, committed). If no on-chain transaction is found, it
/// looks the transaction up by hash in the mempool (pending, not yet committed).
///
/// To create a transaction hash by yourself, do the following:
/// 1. Hash message bytes: "RawTransaction" bytes + BCS bytes of [Transaction](https://aptos-labs.github.io/aptos-core/aptos_types/transaction/enum.Transaction.html).
/// 2. Apply hash algorithm `SHA3-256` to the hash message bytes.
/// 3. Hex-encode the hash bytes with `0x` prefix.
// TODO: Include a link to an example of how to do this ^
#[oai(
path = "/transactions/by_hash/:txn_hash",
method = "get",
operation_id = "get_transaction_by_hash",
tag = "ApiTags::Transactions"
)]
async fn get_transaction_by_hash(
&self,
accept_type: AcceptType,
/// Hash of transaction to retrieve
txn_hash: Path<HashValue>,
// TODO: Use a new request type that can't return 507.
) -> BasicResultWith404<Transaction> {
fail_point_poem("endpoint_transaction_by_hash")?;
self.context
.check_api_output_enabled("Get transactions by hash", &accept_type)?;
self.get_transaction_by_hash_inner(&accept_type, txn_hash.0)
.await
}
/// Wait for transaction by hash
///
/// Same as /transactions/by_hash, but will wait for a pending transaction to be committed. To be used as a long
/// poll optimization by clients, to reduce latency caused by polling. The "long" poll is generally a second or
/// less but dictated by the server; the client must deal with the result as if the request was a normal
/// /transactions/by_hash request, e.g., by retrying if the transaction is pending.
#[oai(
path = "/transactions/wait_by_hash/:txn_hash",
method = "get",
operation_id = "wait_transaction_by_hash",
tag = "ApiTags::Transactions"
)]
async fn wait_transaction_by_hash(
&self,
accept_type: AcceptType,
/// Hash of transaction to retrieve
txn_hash: Path<HashValue>,
// TODO: Use a new request type that can't return 507.
) -> BasicResultWith404<Transaction> {
fail_point_poem("endpoint_wait_transaction_by_hash")?;
self.context
.check_api_output_enabled("Get transactions by hash", &accept_type)?;
// Short poll if the active connections are too high
if self
.context
.wait_for_hash_active_connections
.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
>= self
.context
.node_config
.api
.wait_by_hash_max_active_connections
{
self.context
.wait_for_hash_active_connections
.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
metrics::WAIT_TRANSACTION_POLL_TIME
.with_label_values(&["short"])
.observe(0.0);
return self
.get_transaction_by_hash_inner(&accept_type, txn_hash.0)
.await;
}
let start_time = std::time::Instant::now();
WAIT_TRANSACTION_GAUGE.inc();
let result = self
.wait_transaction_by_hash_inner(
&accept_type,
txn_hash.0,
self.context.node_config.api.wait_by_hash_timeout_ms,
self.context.node_config.api.wait_by_hash_poll_interval_ms,
)
.await;
WAIT_TRANSACTION_GAUGE.dec();
self.context
.wait_for_hash_active_connections
.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
metrics::WAIT_TRANSACTION_POLL_TIME
.with_label_values(&["long"])
.observe(start_time.elapsed().as_secs_f64());
result
}
/// Get transaction by version
///
/// Retrieves a transaction by a given version. If the version has been
/// pruned, a 410 will be returned.
#[oai(
path = "/transactions/by_version/:txn_version",
method = "get",
operation_id = "get_transaction_by_version",
tag = "ApiTags::Transactions"
)]
async fn get_transaction_by_version(
&self,
accept_type: AcceptType,
/// Version of transaction to retrieve
txn_version: Path<U64>,
) -> BasicResultWith404<Transaction> {
fail_point_poem("endpoint_transaction_by_version")?;
self.context
.check_api_output_enabled("Get transactions by version", &accept_type)?;
let api = self.clone();
api_spawn_blocking(move || {
api.get_transaction_by_version_inner(&accept_type, txn_version.0)
})
.await
}
/// Get account transactions
///
/// Retrieves on-chain committed transactions from an account. If the start
/// version is too far in the past, a 410 will be returned.
///
/// If no start version is given, it will start at version 0.
///
/// To retrieve a pending transaction, use /transactions/by_hash.
#[oai(
path = "/accounts/:address/transactions",
method = "get",
operation_id = "get_account_transactions",
tag = "ApiTags::Transactions"
)]
async fn get_accounts_transactions(
&self,
accept_type: AcceptType,
/// Address of account with or without a `0x` prefix
address: Path<Address>,
/// Account sequence number to start list of transactions
///
/// If not provided, defaults to showing the latest transactions
start: Query<Option<U64>>,
/// Max number of transactions to retrieve.
///
/// If not provided, defaults to default page size
limit: Query<Option<u16>>,
) -> BasicResultWith404<Vec<Transaction>> {
fail_point_poem("endpoint_get_accounts_transactions")?;
self.context
.check_api_output_enabled("Get account transactions", &accept_type)?;
let page = Page::new(
start.0.map(|v| v.0),
limit.0,
self.context.max_transactions_page_size(),
);
let api = self.clone();
api_spawn_blocking(move || api.list_by_account(&accept_type, page, address.0)).await
}
/// Submit transaction
///
/// This endpoint accepts transaction submissions in two formats.
///
/// To submit a transaction as JSON, you must submit a SubmitTransactionRequest.
/// To build this request, do the following:
///
/// 1. Encode the transaction as BCS. If you are using a language that has
/// native BCS support, make sure of that library. If not, you may take
/// advantage of /transactions/encode_submission. When using this
/// endpoint, make sure you trust the node you're talking to, as it is
/// possible they could manipulate your request.
/// 2. Sign the encoded transaction and use it to create a TransactionSignature.
/// 3. Submit the request. Make sure to use the "application/json" Content-Type.
///
/// To submit a transaction as BCS, you must submit a SignedTransaction
/// encoded as BCS. See SignedTransaction in types/src/transaction/mod.rs.
/// Make sure to use the `application/x.aptos.signed_transaction+bcs` Content-Type.
// TODO: Point to examples of both of these flows, in multiple languages.
#[oai(
path = "/transactions",
method = "post",
operation_id = "submit_transaction",
tag = "ApiTags::Transactions"
)]
async fn submit_transaction(
&self,
accept_type: AcceptType,
data: SubmitTransactionPost,
) -> SubmitTransactionResult<PendingTransaction> {
data.verify()
.context("Submitted transaction invalid'")
.map_err(|err| {
SubmitTransactionError::bad_request_with_code_no_info(
err,
AptosErrorCode::InvalidInput,
)
})?;
fail_point_poem("endpoint_submit_transaction")?;
if !self.context.node_config.api.transaction_submission_enabled {
return Err(api_disabled("Submit transaction"));
}
self.context
.check_api_output_enabled("Submit transaction", &accept_type)?;
let ledger_info = self.context.get_latest_ledger_info()?;
let signed_transaction = self.get_signed_transaction(&ledger_info, data)?;
self.create(&accept_type, &ledger_info, signed_transaction)
.await
}
/// Submit batch transactions
///
/// This allows you to submit multiple transactions. The response has three outcomes:
///
/// 1. All transactions succeed, and it will return a 202
/// 2. Some transactions succeed, and it will return the failed transactions and a 206
/// 3. No transactions succeed, and it will also return the failed transactions and a 206
///
/// To submit a transaction as JSON, you must submit a SubmitTransactionRequest.
/// To build this request, do the following:
///
/// 1. Encode the transaction as BCS. If you are using a language that has
/// native BCS support, make sure to use that library. If not, you may take
/// advantage of /transactions/encode_submission. When using this
/// endpoint, make sure you trust the node you're talking to, as it is
/// possible they could manipulate your request.
/// 2. Sign the encoded transaction and use it to create a TransactionSignature.
/// 3. Submit the request. Make sure to use the "application/json" Content-Type.
///
/// To submit a transaction as BCS, you must submit a SignedTransaction
/// encoded as BCS. See SignedTransaction in types/src/transaction/mod.rs.
/// Make sure to use the `application/x.aptos.signed_transaction+bcs` Content-Type.
#[oai(
path = "/transactions/batch",
method = "post",
operation_id = "submit_batch_transactions",
tag = "ApiTags::Transactions"
)]
async fn submit_transactions_batch(
&self,
accept_type: AcceptType,
data: SubmitTransactionsBatchPost,
) -> SubmitTransactionsBatchResult<TransactionsBatchSubmissionResult> {
data.verify()
.context("Submitted transactions invalid")
.map_err(|err| {
SubmitTransactionError::bad_request_with_code_no_info(
err,
AptosErrorCode::InvalidInput,
)
})?;
fail_point_poem("endpoint_submit_batch_transactions")?;
if !self.context.node_config.api.transaction_submission_enabled {
return Err(api_disabled("Submit batch transaction"));
}
self.context
.check_api_output_enabled("Submit batch transactions", &accept_type)?;
let ledger_info = self.context.get_latest_ledger_info()?;
let signed_transactions_batch = self.get_signed_transactions_batch(&ledger_info, data)?;
if self.context.max_submit_transaction_batch_size() < signed_transactions_batch.len() {
return Err(SubmitTransactionError::bad_request_with_code(
format!(
"Submitted too many transactions: {}, while limit is {}",
signed_transactions_batch.len(),
self.context.max_submit_transaction_batch_size(),
),
AptosErrorCode::InvalidInput,
&ledger_info,
));
}
self.create_batch(&accept_type, &ledger_info, signed_transactions_batch)
.await
}
/// Simulate transaction
///
/// The output of the transaction will have the exact transaction outputs and events that running
/// an actual signed transaction would have. However, it will not have the associated state
/// hashes, as they are not updated in storage. This can be used to estimate the maximum gas
/// units for a submitted transaction.
///
/// To use this, you must:
/// - Create a SignedTransaction with a zero-padded signature.
/// - Submit a SubmitTransactionRequest containing a UserTransactionRequest containing that signature.
///
/// To use this endpoint with BCS, you must submit a SignedTransaction
/// encoded as BCS. See SignedTransaction in types/src/transaction/mod.rs.
#[oai(
path = "/transactions/simulate",
method = "post",
operation_id = "simulate_transaction",
tag = "ApiTags::Transactions"
)]
async fn simulate_transaction(
&self,
accept_type: AcceptType,
/// If set to true, the max gas value in the transaction will be ignored
/// and the maximum possible gas will be used
estimate_max_gas_amount: Query<Option<bool>>,
/// If set to true, the gas unit price in the transaction will be ignored
/// and the estimated value will be used
estimate_gas_unit_price: Query<Option<bool>>,
/// If set to true, the transaction will use a higher price than the original
/// estimate.
estimate_prioritized_gas_unit_price: Query<Option<bool>>,
data: SubmitTransactionPost,
) -> SimulateTransactionResult<Vec<UserTransaction>> {
data.verify()
.context("Simulated transaction invalid")
.map_err(|err| {
SubmitTransactionError::bad_request_with_code_no_info(
err,
AptosErrorCode::InvalidInput,
)
})?;
fail_point_poem("endpoint_simulate_transaction")?;
if !self.context.node_config.api.transaction_simulation_enabled {
return Err(api_disabled("Simulate transaction"));
}
self.context
.check_api_output_enabled("Simulate transaction", &accept_type)?;
let api = self.clone();
let context = self.context.clone();
api_spawn_blocking(move || {
let ledger_info = context.get_latest_ledger_info()?;
let mut signed_transaction = api.get_signed_transaction(&ledger_info, data)?;
// Confirm the simulation filter allows the transaction. We use HashValue::zero()
// here for the block ID because we don't allow filtering by block ID for the
// simulation filters. See the ConfigSanitizer for ApiConfig.
if !context.node_config.api.simulation_filter.allows(
aptos_crypto::HashValue::zero(),
ledger_info.timestamp(),
&signed_transaction,
) {
return Err(SubmitTransactionError::forbidden_with_code(
"Transaction not allowed by simulation filter",
AptosErrorCode::InvalidInput,
&ledger_info,
));
}
let estimated_gas_unit_price = match (
estimate_gas_unit_price.0.unwrap_or_default(),
estimate_prioritized_gas_unit_price.0.unwrap_or_default(),
) {
(_, true) => {
let gas_estimation = context.estimate_gas_price(&ledger_info)?;
// The prioritized gas estimate should always be set, but if it's not use the gas estimate
Some(
gas_estimation
.prioritized_gas_estimate
.unwrap_or(gas_estimation.gas_estimate),
)
},
(true, false) => Some(context.estimate_gas_price(&ledger_info)?.gas_estimate),
(false, false) => None,
};
// If estimate max gas amount is provided, we will just make it the maximum value
let estimated_max_gas_amount = if estimate_max_gas_amount.0.unwrap_or_default() {
// Retrieve max possible gas units
let (_, gas_params) = context.get_gas_schedule(&ledger_info)?;
let min_number_of_gas_units =
u64::from(gas_params.vm.txn.min_transaction_gas_units)
/ u64::from(gas_params.vm.txn.gas_unit_scaling_factor);
let max_number_of_gas_units =
u64::from(gas_params.vm.txn.maximum_number_of_gas_units);
// Retrieve account balance to determine max gas available, right now this is using
// a view function, but we may want to re-evaluate this based on performance
let (_, _, state_view) = context
.state_view::<BasicErrorWith404>(Option::None)
.map_err(|err| {
SubmitTransactionError::bad_request_with_code_no_info(
err,
AptosErrorCode::InvalidInput,
)
})?;
let output = AptosVM::execute_view_function(
&state_view,
ModuleId::new(AccountAddress::ONE, ident_str!("coin").into()),
ident_str!("balance").into(),
vec![APTOS_COIN_TYPE.clone()],
vec![signed_transaction.sender().to_vec()],
context.node_config.api.max_gas_view_function,
);
let values = output.values.map_err(|err| {
SubmitTransactionError::bad_request_with_code_no_info(
err,
AptosErrorCode::InvalidInput,
)
})?;
let balance: u64 = bcs::from_bytes(&values[0]).map_err(|err| {
SubmitTransactionError::bad_request_with_code_no_info(
err,
AptosErrorCode::InvalidInput,
)
})?;
let gas_unit_price =
estimated_gas_unit_price.unwrap_or_else(|| signed_transaction.gas_unit_price());
// With 0 gas price, we set it to max gas units, since we can't divide by 0
let max_account_gas_units = if gas_unit_price == 0 {
balance
} else {
balance / gas_unit_price
};
// To give better error messaging, we should not go below the minimum number of gas units
let max_account_gas_units =
std::cmp::max(min_number_of_gas_units, max_account_gas_units);
// Minimum of the max account and the max total needs to be used for estimation
Some(std::cmp::min(
max_account_gas_units,
max_number_of_gas_units,
))
} else {
None
};
// If there is an estimation of either, replace the values
if estimated_max_gas_amount.is_some() || estimated_gas_unit_price.is_some() {
signed_transaction = override_gas_parameters(
&signed_transaction,
estimated_max_gas_amount,
estimated_gas_unit_price,
);
}
api.simulate(&accept_type, ledger_info, signed_transaction)
})
.await
}
/// Encode submission
///
/// This endpoint accepts an EncodeSubmissionRequest, which internally is a
/// UserTransactionRequestInner (and optionally secondary signers) encoded
/// as JSON, validates the request format, and then returns that request
/// encoded in BCS. The client can then use this to create a transaction
/// signature to be used in a SubmitTransactionRequest, which it then
/// passes to the /transactions POST endpoint.
///
/// To be clear, this endpoint makes it possible to submit transaction
/// requests to the API from languages that do not have library support for
/// BCS. If you are using an SDK that has BCS support, such as the official
/// Rust, TypeScript, or Python SDKs, you do not need to use this endpoint.
///
/// To sign a message using the response from this endpoint:
/// - Decode the hex encoded string in the response to bytes.
/// - Sign the bytes to create the signature.
/// - Use that as the signature field in something like Ed25519Signature, which you then use to build a TransactionSignature.
//
#[oai(
path = "/transactions/encode_submission",
method = "post",
operation_id = "encode_submission",
tag = "ApiTags::Transactions"
)]
async fn encode_submission(
&self,
accept_type: AcceptType,
data: Json<EncodeSubmissionRequest>,
// TODO: Use a new request type that can't return 507 but still returns all the other necessary errors.
) -> BasicResult<HexEncodedBytes> {
data.0
.verify()
.context("'UserTransactionRequest' invalid")
.map_err(|err| {
BasicError::bad_request_with_code_no_info(err, AptosErrorCode::InvalidInput)
})?;
fail_point_poem("endpoint_encode_submission")?;
if !self.context.node_config.api.encode_submission_enabled {
return Err(api_forbidden(
"Encode submission",
"Only JSON is supported as an AcceptType.",
));
}
self.context
.check_api_output_enabled("Encode submission", &accept_type)?;
let api = self.clone();
api_spawn_blocking(move || api.get_signing_message(&accept_type, data.0)).await
}
pub fn log_gas_estimation(gas_estimation: &GasEstimation) {
metrics::GAS_ESTIMATE
.with_label_values(&[metrics::GAS_ESTIMATE_CURRENT])
.observe(gas_estimation.gas_estimate as f64);
if let Some(deprioritized) = gas_estimation.deprioritized_gas_estimate {
metrics::GAS_ESTIMATE
.with_label_values(&[metrics::GAS_ESTIMATE_DEPRIORITIZED])
.observe(deprioritized as f64);
}
if let Some(prioritized) = gas_estimation.prioritized_gas_estimate {
metrics::GAS_ESTIMATE
.with_label_values(&[metrics::GAS_ESTIMATE_PRIORITIZED])
.observe(prioritized as f64);
}
}
/// Estimate gas price
///
/// Gives an estimate of the gas unit price required to get a transaction on chain in a
/// reasonable amount of time. The gas unit price is the amount that each transaction commits to
/// pay for each unit of gas consumed in executing the transaction. The estimate is based on
/// recent history: it gives the minimum gas that would have been required to get into recent
/// blocks, for blocks that were full. (When blocks are not full, the estimate will match the
/// minimum gas unit price.)
///
/// The estimation is given in three values: de-prioritized (low), regular, and prioritized
/// (aggressive). Using a more aggressive value increases the likelihood that the transaction
/// will make it into the next block; more aggressive values are computed with a larger history
/// and higher percentile statistics. More details are in AIP-34.
#[oai(
path = "/estimate_gas_price",
method = "get",
operation_id = "estimate_gas_price",
tag = "ApiTags::Transactions"
)]
async fn estimate_gas_price(&self, accept_type: AcceptType) -> BasicResult<GasEstimation> {
fail_point_poem("endpoint_encode_submission")?;
self.context
.check_api_output_enabled("Estimate gas price", &accept_type)?;
let context = self.context.clone();
api_spawn_blocking(move || {
let latest_ledger_info = context.get_latest_ledger_info()?;
let gas_estimation = context.estimate_gas_price(&latest_ledger_info)?;
Self::log_gas_estimation(&gas_estimation);
match accept_type {
AcceptType::Json => BasicResponse::try_from_json((
gas_estimation,
&latest_ledger_info,
BasicResponseStatus::Ok,
)),
AcceptType::Bcs => {
let gas_estimation_bcs = GasEstimationBcs {
gas_estimate: gas_estimation.gas_estimate,
};
BasicResponse::try_from_bcs((
gas_estimation_bcs,
&latest_ledger_info,
BasicResponseStatus::Ok,
))
},
}
})
.await
}
}
impl TransactionsApi {
/// List all transactions paging by ledger version
fn list(&self, accept_type: &AcceptType, page: Page) -> BasicResultWith404<Vec<Transaction>> {
let latest_ledger_info = self.context.get_latest_ledger_info()?;
let ledger_version = latest_ledger_info.version();
let limit = page.limit(&latest_ledger_info)?;
let start_version = page.compute_start(limit, ledger_version, &latest_ledger_info)?;
let data = self
.context
.get_transactions(start_version, limit, ledger_version)
.context("Failed to read raw transactions from storage")
.map_err(|err| {
BasicErrorWith404::internal_with_code(
err,
AptosErrorCode::InternalError,
&latest_ledger_info,
)
})?;
match accept_type {
AcceptType::Json => {
let timestamp = self
.context
.get_block_timestamp(&latest_ledger_info, start_version)?;
BasicResponse::try_from_json((
self.context.render_transactions_sequential(
&latest_ledger_info,
data,
timestamp,
)?,
&latest_ledger_info,
BasicResponseStatus::Ok,
))
},
AcceptType::Bcs => {
BasicResponse::try_from_bcs((data, &latest_ledger_info, BasicResponseStatus::Ok))
},
}
}
async fn wait_transaction_by_hash_inner(
&self,
accept_type: &AcceptType,
hash: HashValue,
wait_by_hash_timeout_ms: u64,
wait_by_hash_poll_interval_ms: u64,
) -> BasicResultWith404<Transaction> {
let start_time = std::time::Instant::now();
loop {
let context = self.context.clone();
let accept_type = accept_type.clone();
let ledger_info = api_spawn_blocking(move || context.get_latest_ledger_info()).await?;
let txn_data = self
.get_by_hash(hash.into(), &ledger_info)
.await
.context(format!("Failed to get transaction by hash {}", hash))
.map_err(|err| {
BasicErrorWith404::internal_with_code(
err,
AptosErrorCode::InternalError,
&ledger_info,
)
})?
.context(format!("Failed to find transaction with hash: {}", hash))
.map_err(|_| transaction_not_found_by_hash(hash, &ledger_info))?;
if let TransactionData::Pending(_) = txn_data {
if (start_time.elapsed().as_millis() as u64) < wait_by_hash_timeout_ms {
tokio::time::sleep(Duration::from_millis(wait_by_hash_poll_interval_ms)).await;
continue;
}
}
let api = self.clone();
return api_spawn_blocking(move || {
api.get_transaction_inner(&accept_type, txn_data, &ledger_info)
})
.await;
}
}
async fn get_transaction_by_hash_inner(
&self,
accept_type: &AcceptType,
hash: HashValue,
) -> BasicResultWith404<Transaction> {
let context = self.context.clone();
let accept_type = accept_type.clone();
let ledger_info = api_spawn_blocking(move || context.get_latest_ledger_info()).await?;
let txn_data = self
.get_by_hash(hash.into(), &ledger_info)
.await
.context(format!("Failed to get transaction by hash {}", hash))
.map_err(|err| {
BasicErrorWith404::internal_with_code(
err,
AptosErrorCode::InternalError,
&ledger_info,
)
})?
.context(format!("Failed to find transaction with hash: {}", hash))
.map_err(|_| transaction_not_found_by_hash(hash, &ledger_info))?;
let api = self.clone();
api_spawn_blocking(move || api.get_transaction_inner(&accept_type, txn_data, &ledger_info))
.await
}
fn get_transaction_by_version_inner(
&self,
accept_type: &AcceptType,
version: U64,
) -> BasicResultWith404<Transaction> {
let ledger_info = self.context.get_latest_ledger_info()?;
let txn_data = self
.get_by_version(version.0, &ledger_info)
.context(format!("Failed to get transaction by version {}", version))
.map_err(|err| {
BasicErrorWith404::internal_with_code(
err,
AptosErrorCode::InternalError,
&ledger_info,
)
})?;
match txn_data {
GetByVersionResponse::Found(txn_data) => {
self.get_transaction_inner(accept_type, txn_data, &ledger_info)
},
GetByVersionResponse::VersionTooNew => {
Err(transaction_not_found_by_version(version.0, &ledger_info))
},
GetByVersionResponse::VersionTooOld => Err(version_pruned(version.0, &ledger_info)),
}
}
/// Converts a transaction into the outgoing type
fn get_transaction_inner(
&self,
accept_type: &AcceptType,
transaction_data: TransactionData,
ledger_info: &LedgerInfo,
) -> BasicResultWith404<Transaction> {
match accept_type {
AcceptType::Json => {
let state_view = self.context.latest_state_view_poem(ledger_info)?;
let resolver = state_view.as_move_resolver();
let transaction = match transaction_data {
TransactionData::OnChain(txn) => {
let timestamp =
self.context.get_block_timestamp(ledger_info, txn.version)?;
resolver
.as_converter(
self.context.db.clone(),
self.context.table_info_reader.clone(),
)
.try_into_onchain_transaction(timestamp, txn)
.context("Failed to convert on chain transaction to Transaction")
.map_err(|err| {
BasicErrorWith404::internal_with_code(
err,
AptosErrorCode::InternalError,
ledger_info,
)
})?
},
TransactionData::Pending(txn) => resolver
.as_converter(
self.context.db.clone(),
self.context.table_info_reader.clone(),
)
.try_into_pending_transaction(*txn)
.context("Failed to convert on pending transaction to Transaction")
.map_err(|err| {
BasicErrorWith404::internal_with_code(
err,
AptosErrorCode::InternalError,
ledger_info,
)
})?,
};
BasicResponse::try_from_json((transaction, ledger_info, BasicResponseStatus::Ok))
},
AcceptType::Bcs => BasicResponse::try_from_bcs((
transaction_data,
ledger_info,
BasicResponseStatus::Ok,
)),
}
}
/// Retrieves a transaction by ledger version
fn get_by_version(
&self,
version: u64,
ledger_info: &LedgerInfo,
) -> anyhow::Result<GetByVersionResponse> {
if version > ledger_info.version() {
return Ok(GetByVersionResponse::VersionTooNew);
}
if version < ledger_info.oldest_version() {
return Ok(GetByVersionResponse::VersionTooOld);
}
Ok(GetByVersionResponse::Found(
self.context
.get_transaction_by_version(version, ledger_info.version())?
.into(),
))
}
/// Retrieves a transaction by hash. First the node tries to find the transaction
/// in the DB. If the transaction is found there, it means the transaction is
/// committed. If it is not found there, it looks in mempool. If it is found there,
/// it means the transaction is still pending.
async fn get_by_hash(
&self,
hash: aptos_crypto::HashValue,
ledger_info: &LedgerInfo,
) -> anyhow::Result<Option<TransactionData>> {
let context = self.context.clone();
let version = ledger_info.version();
let from_db =
tokio::task::spawn_blocking(move || context.get_transaction_by_hash(hash, version))
.await
.context("Failed to join task to read transaction by hash")?
.context("Failed to read transaction by hash from DB")?;
Ok(match from_db {
None => self
.context
.get_pending_transaction_by_hash(hash)
.await?
.map(|t| t.into()),
_ => from_db.map(|t| t.into()),
})
}
/// List all transactions for an account
fn list_by_account(
&self,
accept_type: &AcceptType,
page: Page,
address: Address,
) -> BasicResultWith404<Vec<Transaction>> {
// Verify the account exists
let account = Account::new(self.context.clone(), address, None, None, None)?;
account.get_account_resource()?;
let latest_ledger_info = account.latest_ledger_info;
// TODO: Return more specific errors from within this function.
let data = self.context.get_account_transactions(
address.into(),
page.start_option(),