> ## Documentation Index
> Fetch the complete documentation index at: https://docs.portalhq.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Evaluate a transaction

> Before committing to a transaction, it's often useful to simulate its outcome to understand the potential changes and detect any errors preemptively.

Portal provides the function **`portal.api.evaluateTransaction`**, which gives you insights into what will happen upon executing the transaction. This function can perform transaction simulation, security validation, or both.

Here's how it works:

<Tabs>
  <Tab title="5.x.x">
    ```kotlin theme={null}
    suspend fun evaluateTransaction(): Result<String> {
        // Basic transaction evaluation
        runCatching {
            val transaction = EvaluateTransactionParam(
                to = "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
                value = "1000000000000000000", // 1 ETH
                data = null,
                maxFeePerGas = "30000000000",
                maxPriorityFeePerGas = "1500000000",
                gas = "21000",
                gasPrice = null
            )

            val evaluation = portal.api.evaluateTransaction(
                chainId = "eip155:1",
                transaction = transaction,
                operationType = ALL
            ).getOrThrow()

            // Check validation results
            evaluation.validation?.let { validation ->
                println("Security Status: ${validation.status}")

                if (validation.status != "VALIDATED") {
                    println("Warning: ${validation.description ?: "Unknown issue"}")

                    // Print detected security features
                    validation.features.forEach { feature ->
                        println("Security Feature: ${feature.type}")
                        println("Description: ${feature.description}")
                    }
                }
            }

            // Check simulation results
            evaluation.simulation?.let { simulation ->
                println("Simulation Status: ${simulation.status}")

                // Print asset changes
                simulation.assetsDiffs.forEach { (token, diffs) ->
                    println("\nToken: $token")
                    diffs.forEach { diff ->
                        println("Incoming transfers:")
                        diff.`in`.forEach { transfer ->
                            println(transfer)
                        }
                        println("Outgoing transfers:")
                        diff.out.forEach { transfer ->
                            println(transfer)
                        }
                    }
                }
            }
        }.onFailure { error ->
            println("Evaluation failed: $error")
            return Result.failure(error)
        }

        // Contract interaction evaluation
        runCatching {
            val transaction = EvaluateTransactionParam(
                to = "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
                value = "0",
                data = "0xa9059cbb000000000000000000000000742d35cc6634c0532925a3b844bc454e4438f44e0000000000000000000000000000000000000000000000000de0b6b3a7640000", // ERC20 transfer
                maxFeePerGas = null,
                maxPriorityFeePerGas = null,
                gas = "65000",
                gasPrice = "20000000000"
            )

            // Validate only
            val evaluation = portal.api.evaluateTransaction(
                chainId = "eip155:1",
                transaction = transaction,
                operationType = VALIDATION
            ).getOrThrow()

            evaluation.validation?.let { validationResult ->
                // Handle potential security issues
                when (validationResult.status) {
                    "VALIDATED" -> {
                        println("Transaction is safe")
                    }
                    "WARNING" -> {
                        println("Warning: ${validationResult.description ?: "Unknown warning"}")
                    }
                    "BLOCKED" -> {
                        println("Blocked: ${validationResult.reason ?: "Unknown reason"}")
                    }
                    else -> {
                        println("Unknown status: ${validationResult.status}")
                    }
                }
            }
        }.onFailure { error ->
            println("Validation failed: $error")
            return Result.failure(error)
        }

        return Result.success("")
    }
    ```

    The `operationType` parameter determines what type of evaluation is performed. It can be one of the following values:

    * `SIMULATION`: Perform transaction simulation only
    * `VALIDATION`: Perform security validation only
    * `ALL`: Perform both validation and simulation
  </Tab>

  <Tab title="3.x.x">
    ```kotlin theme={null}
    suspend fun handleSimulateTransaction() {
        // First, create a transaction.
        val transaction = SimulateTransactionParam(
            to = "0xRecipientAddressHere",  // The recipient address.
            value = "0x10DE4A2A",           // The value to be sent in Wei.
            data = null,                    // Data for the transaction (for contract interactions).
            maxFeePerGas = null,            // Maximum fee per gas.
            maxPriorityFeePerGas = null,    // Maximum priority fee per gas.
            gas = null,                     // The gas limit.
            gasPrice = null                 // Gas price in Wei.
        )

        // Next, simulate the transaction.
        val simulatedResult = portal.api.simulateTransaction(transaction)

        // Finally, handle or display the simulation results.
        when {
            simulatedResult.requestError != null -> {
                print("Request error: ${simulatedResult.requestError.message}")
            }
            simulatedResult.error != null -> {
                print("Transaction will have error: ${simulatedResult.error.message}")
            }
            else -> {
                print("Simulated transaction results: ${simulatedResult.changes}")
            }
        }
    }
    ```
  </Tab>
</Tabs>

This function returns a `BlockaidValidateTrxRes` containing:

* **simulation**: Transaction simulation results including:
  * **accountAddress**: Address being analyzed
  * **accountSummary**: Summary of account state changes
  * **addressDetails**: Detailed information about involved addresses
  * **assetsDiffs**: Asset balance changes, containing:
    * **asset**: Asset information
    * **in**: Incoming transfers
    * **out**: Outgoing transfers
  * **exposures**: Risk exposure analysis
  * **status**: Simulation status
  * **totalUsdDiff**: Total USD value change
  * **totalUsdExposure**: Total USD value at risk
* **validation**: Security validation results (when `operationType` is `VALIDATION` or `ALL`) including:
  * **classification**: Type of potential security issue
  * **description**: Detailed description of the validation results
  * **features**: Array of detected security features
  * **status**: Validation status
* **block**: Block number used for evaluation
* **chain**: Chain identifier

By incorporating transaction simulations, you can provide your users with a preview of the transaction outcomes and preemptively detect and handle errors, ensuring a smoother user experience.

***

And now you are evaluating transactions with Portal! 🙌 🚀 Next, we'll explore how to back up the wallet for recovery if the user loses device access.
