Skip to content

Commit

Permalink
Move transaction preview analysis (#231)
Browse files Browse the repository at this point in the history
* Extract tx signers. Request tx preview from gw

* Handle more tx preview request errors

* Compute transaction fees

* Expose transaction fee mutation functions

* Remove transaction fees from review analysis

* Remove fee models

* Take notary private key and nonce generation from hosts

* Add unit tests

* Fix tests

* Improve coverage

* Version bump

* Improve coverage

* Update file structure

* Version bump

* Split tx submit and poll status in two files

* Fix test

* Address PR comments

* Fix swift and kotlin tests

* Fix swift tests

* Add test

* Fmt

* Address PR comments

* Address PR comments

* Version bump

* Revert unnecessary changes

* Update naming

* Code cleanup

* Add docs and tests

---------

Co-authored-by: Matias Bzurovski <[email protected]>
  • Loading branch information
sergiupuhalschi-rdx and matiasbzurovski authored Oct 17, 2024
1 parent 8540902 commit cebe60c
Show file tree
Hide file tree
Showing 34 changed files with 1,338 additions and 305 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,4 @@ extension TransactionManifest {
public var summary: ManifestSummary {
transactionManifestSummary(manifest: self)
}

/// Creates the `ExecutionSummary` based on the `engineToolkitReceipt` data.
///
/// Such value should be obtained from the Gateway `/transaction/preview` endpoint, under the `radix_engine_toolkit_receipt` field.
/// Its content will be parsed into a `String` representation and used as parameter here.
public func executionSummary(engineToolkitReceipt: String) throws -> ExecutionSummary {
try transactionManifestExecutionSummary(
manifest: self,
engineToolkitReceipt: engineToolkitReceipt
)
}
}
10 changes: 0 additions & 10 deletions apple/Tests/TestCases/RET/TransactionManifestTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,6 @@ final class TransactionManifestTests: Test<TransactionManifest> {
func test_manifest_summary() {
XCTAssertNoDifference(SUT.sample.summary.addressesOfAccountsWithdrawnFrom, [AccountAddress.sampleMainnet])
}

func test_execution_summary() throws {
let name = "third_party_deposits_update"
let receipt = try engineToolkitReceipt(name)
let manifest = try rtm(name)

let summary = try manifest.executionSummary(engineToolkitReceipt: receipt)

XCTAssertNoDifference(summary.addressesOfAccountsRequiringAuth, ["account_tdx_2_129uv9r46an4hwng8wc97qwpraspvnrc7v2farne4lr6ff7yaevaz2a"])
}

func test_from_instructions_string_with_max_sbor_depth_is_ok() throws {
let instructionsString = """
Expand Down
2 changes: 1 addition & 1 deletion crates/sargon/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "sargon"
version = "1.1.29"
version = "1.1.30"
edition = "2021"
build = "build.rs"

Expand Down
13 changes: 13 additions & 0 deletions crates/sargon/src/core/error/common_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -674,6 +674,19 @@ pub enum CommonError {

#[error("Invalid security structure. A factor must not be present in both threshold and override list.")]
InvalidSecurityStructureFactorInBothThresholdAndOverride = 10188,

#[error("One of the receiving accounts does not allow deposits")]
OneOfReceivingAccountsDoesNotAllowDeposits = 10189,

#[error("Failed transaction preview with status: {error_message}")]
FailedTransactionPreview { error_message: String } = 10190,

#[error("Failed to extract radix engine toolkit receipt bytes")]
FailedToExtractTransactionReceiptBytes = 10191,

#[error("Transaction Manifest contains forbidden instructions: {reserved_instructions}")]
ReservedInstructionsNotAllowedInManifest { reserved_instructions: String } =
10192,
}

#[uniffi::export]
Expand Down
19 changes: 17 additions & 2 deletions crates/sargon/src/core/types/epoch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,24 @@ uniffi::custom_newtype!(Epoch, u64);
)]
pub struct Epoch(pub u64);

impl Epoch {
/// Circa 1 hour, since one epoch is circa 6 minutes.
pub const DEFAULT_EPOCH_WINDOW_SIZE: u64 = 10;
}

impl Epoch {
pub fn new(value: u64) -> Self {
Self(value)
}

pub fn window_end_from_start(start: Self) -> Self {
Self::new(start.0 + Self::DEFAULT_EPOCH_WINDOW_SIZE)
}
}

impl From<u64> for Epoch {
fn from(value: u64) -> Self {
Self(value)
Self::new(value)
}
}

Expand All @@ -39,7 +54,7 @@ impl From<Epoch> for ScryptoEpoch {

impl From<ScryptoEpoch> for Epoch {
fn from(value: ScryptoEpoch) -> Self {
Self(value.number())
Self::new(value.number())
}
}

Expand Down
37 changes: 17 additions & 20 deletions crates/sargon/src/gateway_api/methods/transaction_methods.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::prelude::*;
use native_radix_engine_toolkit::receipt::SerializableToolkitTransactionReceipt;

#[uniffi::export]
impl GatewayClient {
Expand All @@ -9,26 +10,6 @@ impl GatewayClient {
.map(|state| Epoch::from(state.epoch))
}

/// Returns the String version of the `radix_engine_toolkit_receipt` by running a "dry run" of a
/// transaction - a preview of the transaction. The `radix_engine_toolkit_receipt`` is
/// required by the [`execution_summary` method](TransactionManifest::execution_summary)
/// on [`TransactionManifest`].
pub async fn dry_run_transaction(
&self,
intent: TransactionIntent,
signer_public_keys: Vec<PublicKey>,
) -> Result<String> {
let request =
TransactionPreviewRequest::new(intent, signer_public_keys, None);
self.transaction_preview(request)
.await
.map(|r| r.radix_engine_toolkit_receipt)
.and_then(|s| {
serde_json::to_string(&s)
.map_err(|_| CommonError::FailedToSerializeToJSON)
})
}

/// Submits a signed transaction payload to the network.
///
/// Returns `Ok(IntentHash)` if the transaction was submitted and not a duplicate.
Expand Down Expand Up @@ -60,4 +41,20 @@ impl GatewayClient {
let request = TransactionStatusRequest::new(intent_hash.to_string());
self.transaction_status(request).await
}

/// Returns the `radix_engine_toolkit_receipt` by running a "dry run" of a
/// transaction - a preview of the transaction. The `radix_engine_toolkit_receipt`` is
/// required by the [`execution_summary` method](TransactionManifest::execution_summary)
/// on [`TransactionManifest`].
pub async fn dry_run_transaction(
&self,
intent: TransactionIntent,
signer_public_keys: Vec<PublicKey>,
) -> Result<Option<ScryptoSerializableToolkitTransactionReceipt>> {
let request =
TransactionPreviewRequest::new(intent, signer_public_keys, None);
self.transaction_preview(request)
.await
.map(|r| r.radix_engine_toolkit_receipt)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ use crate::prelude::*;

impl TransactionPreviewRequestFlags {
pub fn new(
use_free_credit: bool,
assume_all_signature_proofs: bool,
skip_epoch_check: bool,
use_free_credit: UseFreeCredit,
assume_all_signature_proofs: AssumeAllSignatureProofs,
skip_epoch_check: SkipEpochCheck,
) -> Self {
Self {
use_free_credit,
Expand All @@ -16,7 +16,11 @@ impl TransactionPreviewRequestFlags {

impl Default for TransactionPreviewRequestFlags {
fn default() -> Self {
Self::new(true, false, false)
Self::new(
UseFreeCredit::default(),
AssumeAllSignatureProofs::default(),
SkipEpochCheck::default(),
)
}
}

Expand All @@ -28,10 +32,32 @@ mod tests {
type SUT = TransactionPreviewRequestFlags;

#[test]
fn default_value() {
fn default_is_use_free_credit() {
assert!(SUT::default().use_free_credit.0);
}

#[test]
fn default_assume_all_signature_proofs() {
assert!(!SUT::default().assume_all_signature_proofs.0);
}

#[test]
fn default_skip_epoch_check() {
assert!(!SUT::default().skip_epoch_check.0);
}

#[test]
fn json_roundtrip() {
let sut = SUT::default();
assert!(sut.use_free_credit);
assert!(!sut.assume_all_signature_proofs);
assert!(!sut.skip_epoch_check);
assert_eq_after_json_roundtrip(
&sut,
r#"
{
"use_free_credit": true,
"assume_all_signature_proofs": false,
"skip_epoch_check": false
}
"#,
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ mod tests {
let do_test = |intent: TransactionIntent| {
let header = intent.header;
let keys = vec![PublicKey::sample(), PublicKey::sample_other()];
let flags = TransactionPreviewRequestFlags::new(false, true, true);
let sut = SUT::new(intent.clone(), keys.clone(), flags);
let flags = TransactionPreviewRequestFlags::default();
let sut = SUT::new(intent.clone(), keys.clone(), flags.clone());
assert_eq!(sut.flags, flags);
assert_eq!(
sut.signer_public_keys,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@ use crate::prelude::*;

#[derive(
Clone,
Copy,
Debug,
PartialEq,
Eq,
Serialize,
Deserialize, /* Deserialize so we can test roundtrip of JSON vectors */
)]
pub struct TransactionPreviewRequestFlags {
pub(crate) use_free_credit: bool,
pub(crate) assume_all_signature_proofs: bool,
pub(crate) skip_epoch_check: bool,
pub(crate) use_free_credit: UseFreeCredit,
pub(crate) assume_all_signature_proofs: AssumeAllSignatureProofs,
pub(crate) skip_epoch_check: SkipEpochCheck,
}

decl_bool_type!(UseFreeCredit, true);
decl_bool_type!(AssumeAllSignatureProofs, false);
decl_bool_type!(SkipEpochCheck, false);
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
mod logs_inner;
mod transaction_preview_response;
mod transaction_receipt;
mod transaction_receipt_status;

pub use logs_inner::*;
pub use transaction_preview_response::*;
pub use transaction_receipt::*;
pub use transaction_receipt_status::*;
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub struct TransactionPreviewResponse {
/** Hex-encoded binary blob. */
pub encoded_receipt: String,
pub radix_engine_toolkit_receipt:
ScryptoSerializableToolkitTransactionReceipt,
Option<ScryptoSerializableToolkitTransactionReceipt>,
pub logs: Vec<TransactionPreviewResponseLogsInner>,
pub receipt: TransactionReceipt,
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use crate::prelude::*;

/// This is part of the response to a transaction preview request, and contains the status of the transaction.
/// Error message is only present if status is `Failed` or `Rejected`.
#[derive(
Deserialize,
Serialize,
Clone,
PartialEq,
Eq,
Debug,
derive_more::Display,
uniffi::Record,
)]
#[display("{status}")]
pub struct TransactionReceipt {
pub status: TransactionReceiptStatus,
pub error_message: Option<String>,
}

impl HasSampleValues for TransactionReceipt {
fn sample() -> Self {
Self {
status: TransactionReceiptStatus::Succeeded,
error_message: None,
}
}

fn sample_other() -> Self {
Self {
status: TransactionReceiptStatus::Failed,
error_message: Some("An error occurred".to_string()),
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[allow(clippy::upper_case_acronyms)]
type SUT = TransactionReceipt;

#[test]
fn equality() {
assert_eq!(SUT::sample(), SUT::sample());
assert_eq!(SUT::sample_other(), SUT::sample_other());
}

#[test]
fn inequality() {
assert_ne!(SUT::sample(), SUT::sample_other());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use crate::prelude::*;

#[derive(
Deserialize,
Serialize,
Clone,
PartialEq,
Eq,
Debug,
derive_more::Display,
uniffi::Enum,
)]
pub enum TransactionReceiptStatus {
Succeeded,
Failed,
Rejected,
}
Loading

0 comments on commit cebe60c

Please sign in to comment.