# Transaction

## Introduction

Cardano **transactions** are the fundamental way to move value and interact with the blockchain, whether it's moving ADA, native tokens, and NFTs. Or it's interacting with smart contracts. The **Anvil API** simplifies transaction creation with a flexible interface that supports:

* **Simple to complex outputs** - from basic ADA transfers to multi-asset transactions with multiple recipients
* **Input methods** - using `changeAddress` and `UTXOs` to source funds
* **Complete transaction lifecycle** - building, signing, and submitting in a streamlined workflow

This documentation covers the various **transaction types**, **payload structures**, and **best practices** for creating transactions with the Anvil API.

## The Basic Flow

1. **BUILD**: We structure a simple payload with `changeAddress`, `utxos`, and `outputs`
2. **SIGN**: We sign the transaction with your preferred signing method (See [Signing Transactions](https://dev.ada-anvil.io/guides/transaction/signing-transaction))
3. **SUBMIT**: We send the signed transaction to the Anvil API's transaction submit endpoint
4. **CONFIRM**: We handle the response from the submit endpoint

## Transaction Flow Overview

Below is a sequence diagram that illustrates the basic flow of a transaction between your application and the Anvil API.

{% @mermaid/diagram content="---
config:
theme: neo-dark
---------------

sequenceDiagram
actor A1 as Application User
participant User as Your Application
participant Anvil as Anvil API
participant Cardano as Cardano Network

```
Note over A1, Cardano: Anvil API Transaction Workflow

rect rgba(255, 255, 255, 0.1)
    A1->>+User: Start Transaction
    User->>+Anvil: 1. BUILD<br/>POST '/transaction/build' endpoint<br/>(with payload)
    Anvil-->>-User: 2. RECEIVE<br/>(unsigned transaction)
end

rect rgba(87, 173, 87, 0.25)
    Note over A1, User: 3. SIGN<br/>Using Weld<br/>(CIP-30 browser wallet)
    User->>A1: Prompt to Sign Transaction
    A1->>User: Confirm and Sign Transaction
end

rect rgba(255, 255, 255, 0.1)
    User->>+Anvil: 4. SUBMIT<br/>POST '/transaction/submit' endpoint<br/>(signed transaction)
    Anvil->>Cardano: Submit to blockchain
    Cardano-->>Anvil: Return transaction status
    Anvil-->>-User: 5. CONFIRM<br/>(transaction hash & status)
    User-->>-A1: Show Transaction Confirmation
end" %}
```

## Breakdown of the Basic Flow

The above flow diagram illustrates the basic flow of a transaction. The following sections will break down each step in detail. As you can see there are two API calls that are involved in the basic flow: **Build** and **Submit**. The **Build** API call is used to build a transaction, and the **Submit** API call is used to submit a transaction after the user or application has **signed** it.

### 1. Building Transaction: Defining Addresses, UTXOs, and Outputs

The **Build** (`POST /transaction/build`)API call is used to build a transaction. This call requires a payload that includes the sender address for change, UTXOs for inputs, and outputs.

All transactions need UTXOs for inputs. See: [Selecting UTXOs](https://dev.ada-anvil.io/guides/transaction/selecting-utxos) for more information on how to do this for production applications.

```typescript
// Structure for the transaction build request
const buildBody = {
  // Sender address for change
  changeAddress: "addr_sender...",
  
  // UTXOs for inputs (either address or array of CBOR-encoded UTXOs)
  // For CIP-30 wallets: await wallet.getUtxos()
  utxos: ["8282...", "8282..."],

  // Optional: Force the inclusion of specific UTXOs, often required for smart contract interactions.
  // This is not required, but is useful if you need to force the spending of a specific UTXO.
  requiredInputs: ["8282...", "8282..."],
  
  // Where to send the ADA, assets, and amounts
  outputs: [
    {
      address: "addr_recipient...",
      lovelace: 10_000_000, // 10 ADA
    },
  ],
  // Optional bounds that determine when the transaction is valid. 
  // False can be used to disable a bound.
  // If transactions are submitted outside of the validity interval, they will be rejected.
  validityInterval: {
    start: 1234567890, // POSIX timestamp or slot number (optional)
    end: 1234598765    // POSIX timestamp or slot number (optional)
  }
  //Add additional parameters here.
};

// Send the build request
const buildResponse = await fetch(
  "https://preprod.api.ada-anvil.app/v2/services/transactions/build",
  {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Api-Key": "YOUR_API_KEY",
    },
    body: JSON.stringify(buildBody),
  }
);

const buildData = await buildResponse.json();
```

### Build Response Structure

```json
// After successful build
{
  "hash": "TRANSACTION_HASH",

  // Complete transaction is preferred for signing most transactions.
  "complete": "TRANSACTION_CBOR", 
  
  // Stripped transaction is preferred for minting operations (NFTs/tokens).
  // This is because we want to hide metadata from the client. 
  "stripped": "STRIPPED_CBOR", 
  
  // The witness data component
  "witnessSet": "WITNESS_SET_CBOR"
}
```

> **Important Warning:**
>
> * Use the `complete` format when you don't care about hiding metadata from the frontend client.
> * For minting operations (NFTs/tokens), only exposing the `stripped` format of your `build` response helps hide metadata from the frontend client. The `complete` format will include those attributes allowing users to see the metadata before the transaction is submitted.

### 2. Sign the Transaction

**Sign** the transaction with your preferred signing method (See [Signing Transactions](https://dev.ada-anvil.io/guides/transaction/signing-transaction)). This can be done using a CIP-30 compatible wallet, or by using a private key in your application, or by using a hardware wallet. We recommend using the [@ada-anvil/weld](https://www.npmjs.com/package/@ada-anvil/weld) wallet connector for a seamless experience handling interactions with Cardano wallets.

### 3. Submit the Signed Transaction

Once you have the signatures, we can **submit** `POST /transaction/submit` the transaction in two ways:

1. **Embed signatures in transaction**: You can embed the signatures in the transaction. This is helpful when you are signing a transaction in a backend server (using CSL). Otherwise, option 2 is recommended.
2. **Separate transaction and signatures**: You can separate the transaction and signatures and send them to the API separately.

```typescript
// Option 1: Submit with signatures embedded in transaction.
const submitBody = {
  transaction: "SIGNED_TRANSACTION_CBOR" 
};

// Option 2: Submit with separate transaction and signatures
const submitBody = {
  transaction: "UNSIGNED_TRANSACTION_CBOR", 
  signatures: ["SIGNATURE_1", "SIGNATURE_2"] // Array of signatures
};
```

### Submit Response Structure

```json
// After successful submit
{
  "hash": "TRANSACTION_HASH" // The transaction ID on the blockchain
}
```

> **Cardano is Deterministic:** The transaction hash returned by the build endpoint is the same hash that will appear on-chain. Unlike some other blockchains, Cardano's eUTXO model allows for deterministic transaction creation - the transaction ID is calculated before submission and remains unchanged when confirmed on the blockchain. This feature enables reliable transaction tracking from creation through confirmation.

***

## Best Practices

* **Test on Preprod** first to avoid risking real ADA.
* **Handle Errors gracefully**: watch for `400 Bad Request`, `401 Unauthorized`, or `429 Throttled, please try again later.` responses.
* **Use CIP-30 for a user-friendly Web3 experience**: fetch `utxos` and `changeAddress` directly from the user's connected wallet.
* **Validate JSON**: Ensure your payload is correctly formed—typos in keys like lovelace can cause failures.
* **Include sufficient ADA**: When sending native assets, include at least 2 ADA per output (due to min-UTXO requirements).
* **Verify addresses**: Always double-check recipient addresses before submitting transactions.
* **Keep API keys secure**: Never expose your API keys in client-side code.

***

### Transaction Builder Examples and Next Steps

Now that you have a basic understanding of how to send a transaction, explore how the Anvil API is flexible and can handle many types of transactions. Wether you are sending ADA and/or assets to multiple recipients, adding metadata to transactions, or handling multi-signature transactions, the Anvil API takes advantage of the full power of transactions on Cardano.

Review our guides below for more details. They provide practical examples of how to use the Anvil API transaction builder:

{% content-ref url="transaction/create-basic-transaction" %}
[create-basic-transaction](https://dev.ada-anvil.io/guides/transaction/create-basic-transaction)
{% endcontent-ref %}

{% content-ref url="transaction/create-custom-transaction" %}
[create-custom-transaction](https://dev.ada-anvil.io/guides/transaction/create-custom-transaction)
{% endcontent-ref %}

{% content-ref url="transaction/create-transaction-with-metadata-cip-20" %}
[create-transaction-with-metadata-cip-20](https://dev.ada-anvil.io/guides/transaction/create-transaction-with-metadata-cip-20)
{% endcontent-ref %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dev.ada-anvil.io/guides/transaction.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
