near_fetch/result.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
//! Result and execution types from results of RPC calls to the network.
use near_gas::NearGas;
use near_primitives::borsh;
use near_primitives::views::{
ExecutionOutcomeWithIdView, ExecutionStatusView, FinalExecutionOutcomeView,
FinalExecutionStatus, SignedTransactionView,
};
use base64::{engine::general_purpose, Engine as _};
use crate::error::Result;
use crate::Error;
/// Execution related info as a result of performing a successful transaction
/// execution on the network. This value can be converted into the returned
/// value of the transaction via [`ExecutionSuccess::json`] or [`ExecutionSuccess::borsh`]
pub type ExecutionSuccess = ExecutionResult<Value>;
/// The transaction/receipt details of a transaction execution. This object
/// can be used to retrieve data such as logs and gas burnt per transaction
/// or receipt.
#[derive(PartialEq, Eq, Clone, Debug)]
#[non_exhaustive]
pub struct ExecutionDetails {
/// Original signed transaction.
pub transaction: SignedTransactionView,
/// The execution outcome of the signed transaction.
pub transaction_outcome: ExecutionOutcomeWithIdView,
/// The execution outcome of receipts.
pub receipts_outcome: Vec<ExecutionOutcomeWithIdView>,
}
impl ExecutionDetails {
/// Returns just the transaction outcome.
pub fn outcome(&self) -> &ExecutionOutcomeWithIdView {
&self.transaction_outcome
}
/// Grab all outcomes after the execution of the transaction. This includes outcomes
/// from the transaction and all the receipts it generated.
pub fn outcomes(&self) -> Vec<&ExecutionOutcomeWithIdView> {
let mut outcomes = vec![self.outcome()];
outcomes.extend(self.receipt_outcomes());
outcomes
}
/// Grab all outcomes after the execution of the transaction. This includes outcomes
/// only from receipts generated by this transaction.
pub fn receipt_outcomes(&self) -> &[ExecutionOutcomeWithIdView] {
&self.receipts_outcome
}
/// Grab all outcomes that did not succeed the execution of this transaction. This
/// will also include the failures from receipts as well.
pub fn failures(&self) -> Vec<&ExecutionOutcomeWithIdView> {
let mut failures = Vec::new();
if matches!(
self.transaction_outcome.outcome.status,
ExecutionStatusView::Failure(_)
) {
failures.push(&self.transaction_outcome);
}
failures.extend(self.receipt_failures());
failures
}
/// Just like `failures`, grab only failed receipt outcomes.
pub fn receipt_failures(&self) -> Vec<&ExecutionOutcomeWithIdView> {
self.receipt_outcomes()
.iter()
.filter(|receipt| matches!(receipt.outcome.status, ExecutionStatusView::Failure(_)))
.collect()
}
/// Grab all logs from both the transaction and receipt outcomes.
pub fn logs(&self) -> Vec<&str> {
self.outcomes()
.into_iter()
.flat_map(|outcome| &outcome.outcome.logs)
.map(String::as_str)
.collect()
}
}
/// The result after evaluating the status of an execution. This can be [`ExecutionSuccess`]
/// for successful executions or a [`ExecutionFailure`] for failed ones.
#[derive(PartialEq, Eq, Debug, Clone)]
#[non_exhaustive]
pub struct ExecutionResult<T> {
/// Total gas burnt by the execution
pub total_gas_burnt: NearGas,
/// Value returned from an execution. This is a base64 encoded str for a successful
/// execution or a `TxExecutionError` if a failed one.
pub value: T,
/// Additional details related to the execution.
pub details: ExecutionDetails,
}
/// Execution related info found after performing a transaction. Can be converted
/// into [`ExecutionSuccess`] or [`ExecutionFailure`] through [`into_result`]
///
/// [`into_result`]: crate::result::ExecutionFinalResult::into_result
#[derive(PartialEq, Eq, Clone, Debug)]
// #[must_use = "use `into_result()` to handle potential execution errors"]
pub struct ExecutionFinalResult {
status: FinalExecutionStatus,
pub details: ExecutionDetails,
}
impl ExecutionFinalResult {
pub(crate) fn from_view(view: FinalExecutionOutcomeView) -> Self {
Self {
status: view.status,
details: ExecutionDetails {
transaction: view.transaction,
transaction_outcome: view.transaction_outcome,
receipts_outcome: view.receipts_outcome,
},
}
}
/// Converts this object into a [`Result`] holding either [`ExecutionSuccess`] or [`ExecutionFailure`].
pub fn into_result(self) -> Result<ExecutionSuccess> {
let total_gas_burnt = self.total_gas_burnt();
match self.status {
FinalExecutionStatus::SuccessValue(value) => Ok(ExecutionResult {
total_gas_burnt,
value: Value::from_string(general_purpose::STANDARD.encode(value)),
details: self.details,
}),
FinalExecutionStatus::Failure(tx_error) => Err(Error::TxExecution(Box::new(tx_error))),
FinalExecutionStatus::NotStarted => Err(Error::TxStatus("NotStarted")),
FinalExecutionStatus::Started => Err(Error::TxStatus("Started")),
}
}
pub fn total_gas_burnt(&self) -> NearGas {
NearGas::from_gas(
self.details.transaction_outcome.outcome.gas_burnt
+ self
.details
.receipts_outcome
.iter()
.map(|t| t.outcome.gas_burnt)
.sum::<u64>(),
)
}
/// Returns the contained Ok value, consuming the self value.
///
/// Because this function may panic, its use is generally discouraged. Instead, prefer
/// to call into [`into_result`] then pattern matching and handle the Err case explicitly.
///
/// [`into_result`]: crate::result::ExecutionFinalResult::into_result
pub fn unwrap(self) -> ExecutionSuccess {
self.into_result().unwrap()
}
/// Deserialize an instance of type `T` from bytes of JSON text sourced from the
/// execution result of this call. This conversion can fail if the structure of
/// the internal state does not meet up with [`serde::de::DeserializeOwned`]'s
/// requirements.
pub fn json<T: serde::de::DeserializeOwned>(self) -> Result<T> {
self.into_result()?.json()
}
/// Deserialize an instance of type `T` from bytes sourced from the execution
/// result. This conversion can fail if the structure of the internal state does
/// not meet up with [`borsh::BorshDeserialize`]'s requirements.
pub fn borsh<T: borsh::BorshDeserialize>(self) -> Result<T> {
self.into_result()?.borsh()
}
/// Grab the underlying raw bytes returned from calling into a contract's function.
/// If we want to deserialize these bytes into a rust datatype, use [`ExecutionResult::json`]
/// or [`ExecutionResult::borsh`] instead.
pub fn raw_bytes(self) -> Result<Vec<u8>> {
self.into_result()?.raw_bytes()
}
/// Checks whether the transaction was successful. Returns true if
/// the transaction has a status of [`FinalExecutionStatus::SuccessValue`].
pub fn is_success(&self) -> bool {
matches!(self.status(), FinalExecutionStatus::SuccessValue(_))
}
/// Checks whether the transaction has failed. Returns true if
/// the transaction has a status of [`FinalExecutionStatus::Failure`].
pub fn is_failure(&self) -> bool {
matches!(self.status(), FinalExecutionStatus::Failure(_))
}
/// Returns just the transaction outcome.
pub fn outcome(&self) -> &ExecutionOutcomeWithIdView {
self.details.outcome()
}
/// Grab all outcomes after the execution of the transaction. This includes outcomes
/// from the transaction and all the receipts it generated.
pub fn outcomes(&self) -> Vec<&ExecutionOutcomeWithIdView> {
self.details.outcomes()
}
/// Grab all outcomes after the execution of the transaction. This includes outcomes
/// only from receipts generated by this transaction.
pub fn receipt_outcomes(&self) -> &[ExecutionOutcomeWithIdView] {
self.details.receipt_outcomes()
}
/// Grab all outcomes that did not succeed the execution of this transaction. This
/// will also include the failures from receipts as well.
pub fn failures(&self) -> Vec<&ExecutionOutcomeWithIdView> {
self.details.failures()
}
/// Just like `failures`, grab only failed receipt outcomes.
pub fn receipt_failures(&self) -> Vec<&ExecutionOutcomeWithIdView> {
self.details.receipt_failures()
}
/// Grab all logs from both the transaction and receipt outcomes.
pub fn logs(&self) -> Vec<&str> {
self.details.logs()
}
pub fn status(&self) -> &FinalExecutionStatus {
&self.status
}
}
impl ExecutionSuccess {
/// Deserialize an instance of type `T` from bytes of JSON text sourced from the
/// execution result of this call. This conversion can fail if the structure of
/// the internal state does not meet up with [`serde::de::DeserializeOwned`]'s
/// requirements.
pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T> {
self.value.json()
}
/// Deserialize an instance of type `T` from bytes sourced from the execution
/// result. This conversion can fail if the structure of the internal state does
/// not meet up with [`borsh::BorshDeserialize`]'s requirements.
pub fn borsh<T: borsh::BorshDeserialize>(&self) -> Result<T> {
self.value.borsh()
}
/// Grab the underlying raw bytes returned from calling into a contract's function.
/// If we want to deserialize these bytes into a rust datatype, use [`ExecutionResult::json`]
/// or [`ExecutionResult::borsh`] instead.
pub fn raw_bytes(&self) -> Result<Vec<u8>> {
self.value.raw_bytes()
}
}
impl<T> ExecutionResult<T> {
/// Returns just the transaction outcome.
pub fn outcome(&self) -> &ExecutionOutcomeWithIdView {
&self.details.transaction_outcome
}
/// Grab all outcomes after the execution of the transaction. This includes outcomes
/// from the transaction and all the receipts it generated.
pub fn outcomes(&self) -> Vec<&ExecutionOutcomeWithIdView> {
let mut outcomes = vec![self.outcome()];
outcomes.extend(self.receipt_outcomes());
outcomes
}
/// Grab all outcomes after the execution of the transaction. This includes outcomes
/// only from receipts generated by this transaction.
pub fn receipt_outcomes(&self) -> &[ExecutionOutcomeWithIdView] {
&self.details.receipts_outcome
}
/// Grab all outcomes that did not succeed the execution of this transaction. This
/// will also include the failures from receipts as well.
pub fn failures(&self) -> Vec<&ExecutionOutcomeWithIdView> {
let mut failures = Vec::new();
if matches!(
self.details.transaction_outcome.outcome.status,
ExecutionStatusView::Failure(_)
) {
failures.push(&self.details.transaction_outcome);
}
failures.extend(self.receipt_failures());
failures
}
/// Just like `failures`, grab only failed receipt outcomes.
pub fn receipt_failures(&self) -> Vec<&ExecutionOutcomeWithIdView> {
self.receipt_outcomes()
.iter()
.filter(|receipt| matches!(receipt.outcome.status, ExecutionStatusView::Failure(_)))
.collect()
}
/// Grab all logs from both the transaction and receipt outcomes.
pub fn logs(&self) -> Vec<&str> {
self.outcomes()
.into_iter()
.flat_map(|outcome| &outcome.outcome.logs)
.map(String::as_str)
.collect()
}
}
/// Value type returned from an [`ExecutionOutcome`] or receipt result. This value
/// can be converted into the underlying Rust datatype, or directly grab the raw
/// bytes associated to the value.
#[derive(Debug)]
pub struct Value {
repr: String,
}
impl Value {
fn from_string(value: String) -> Self {
Self { repr: value }
}
/// Deserialize an instance of type `T` from bytes of JSON text sourced from the
/// execution result of this call. This conversion can fail if the structure of
/// the internal state does not meet up with [`serde::de::DeserializeOwned`]'s
/// requirements.
pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T> {
let buf = self.raw_bytes()?;
Ok(serde_json::from_slice(&buf)?)
}
/// Deserialize an instance of type `T` from bytes sourced from the execution
/// result. This conversion can fail if the structure of the internal state does
/// not meet up with [`borsh::BorshDeserialize`]'s requirements.
pub fn borsh<T: borsh::BorshDeserialize>(&self) -> Result<T> {
let buf = self.raw_bytes()?;
Ok(borsh::BorshDeserialize::try_from_slice(&buf)?)
}
/// Grab the underlying raw bytes returned from calling into a contract's function.
/// If we want to deserialize these bytes into a rust datatype, use [`json`]
/// or [`borsh`] instead.
///
/// [`json`]: Value::json
/// [`borsh`]: Value::borsh
pub fn raw_bytes(&self) -> Result<Vec<u8>> {
Ok(general_purpose::STANDARD.decode(&self.repr)?)
}
}