# Smart Contract Utilities

Smart Contract Utilities provides endpoints for interacting with Plutus scripts (also known as validators). You can use these endpoints to derive addresses, apply parameters, and handle data serialization.

| Endpoint                            | Description                                                                    |
| ----------------------------------- | ------------------------------------------------------------------------------ |
| `GET /validators/{hash}/address`    | Derives the script address from a given script hash.                           |
| `POST /blueprints/apply-params`     | Applies parameters to a script to generate a new, parameterized script hash.   |
| `POST /validators/{hash}/parse`     | Parses a CBOR hex-encoded datum or redeemer into a human-readable JSON object. |
| `POST /validators/{hash}/serialize` | Serializes a JSON object into a CBOR hex-encoded datum or redeemer string.     |

## Available Endpoints

### Get Script Address

**`GET /validators/{hash}/address`**

Derives the script address from a given script hash.

* **Path Parameters**:
  * `hash` (string): The hex-encoded hash of the Plutus script.
* **Query Parameters**:
  * `stake` (string, optional): A stake key hash to associate with the address.

<details>

<summary>TypeScript Example: Get a script address from its hash</summary>

```typescript
async function getScriptAddress(scriptHash: string) {
  const response = await fetch(`https://preprod.api.ada-anvil.app/v2/services/validators/${scriptHash}/address`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': 'YOUR_API_KEY'
    }
  });

  const { hex, bech32 } = await response.json();

  return { hex, bech32 };
}
// Sample output:
// {
//   "hex": "61c9a6c4d47f5c8e...",
//   "bech32": "addr_test1wqsw5u8u7g5m6x0s0qqp9g3zgx9n9ahm0t4105keg3zt0swsgjmzg"
// }

```

</details>

### Apply Parameters to Script

**`POST /blueprints/apply-params`**

Applies a set of parameters to a parameterized script, returning the new script hash and compiled code. See [Hello World Example with Parameters](https://github.com/Cardano-Forge/anvil-api-examples/tree/main/smart-contracts/hello-world/aiken-hello-world-with-params) for an example of a smart contract that uses parameters.

* **Body**:
  * `params` (object): A record mapping validator hashes to arrays of parameters. Each validator hash maps to an array of parameters to apply.
    * Example: `{ "validator_hash_here": [param1, param2, ...] }`
  * `blueprint` (object, optional): Only required if the script is not yet known to Anvil. This is usually your `plutus.json` file from an Aiken build. See the [Blueprint Management](https://github.com/Cardano-Forge/anvil-api/blob/main/docs/guides/guides/smart-contract/blueprint-management.md) guide for more details.

<details>

<summary>TypeScript Example: Apply parameters to a script</summary>

```typescript
async function applyParameters(plutusJson?: object) {
  // Define parameters for each validator that needs them
  const params = {
    // Map validator hash to its parameters
    "333158938654b6e69ce1349aeeadcff7fdc0c285f3102b8697a1e173": [
      "48656c6c6f2c20416e76696c21",  // ByteArray: "Hello, Anvil!" in hex
      // Parameters are applied in order as defined in the blueprint
    ],
    // Multiple validators can be parameterized at once
    "another_validator_hash": [
      "30f4e824283240d2ca66f3e09b0b7adfc5d37816c072279b31f090a4",  // VerificationKeyHash (28 bytes)
      "2c256815c1a9637e624e3264e0e7a0a9a824a303a4cf8dd6c4cf96b5#0"  // UTXO reference (TxId#Index)
    ]
  };

  const response = await fetch(`https://preprod.api.ada-anvil.app/v2/services/blueprints/apply-params`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      params,
      blueprint: plutusJson // Your CIP-57 blueprint (optional if already uploaded)
    })
  });

  const result = await response.json();
  const { preloadedScript, addresses } = result;
  
  return { preloadedScript, addresses };
}
// Sample output:
// {
//   "preloadedScript": { 
//     "type": "plutus", 
//     "blueprint": { /* Updated blueprint with applied params */ },
//     "validatorRefs": {}
//   },
//   "addresses": {
//     "72c6923a040389fa08c728fe41f0bb9be1722867aec4067fcc751cef": {
//       "bech32": "addr_test1wpevdy36qspcn7sgcu50us0shwd7zu3gv7hvgpnle363emcu0m8ar",
//       "hex": "7072c6923a040389fa08c728fe41f0bb9be1722867aec4067fcc751cef"
//     }
//   }
// }
```

</details>

### Parse Plutus Data

**`POST /validators/{hash}/parse`**

Parses a hex-encoded Plutus data string (e.g., datum or redeemer) into a structured JSON object based on the script's schema.

* **Path Parameters**:
  * `hash` (string): The hash of the script. The API uses this hash to fetch the validator's schema, which is required to correctly convert the data between JSON and its hex-encoded format.
* **Body**:
  * `type` (string): The type of data to parse (`"datum"` or `"redeemer"`).
  * `purpose` (string): The purpose of the script, which determines the context in which it's validated. Possible values are:
    * `"mint"`: For minting or burning assets.
    * `"spend"`: For spending transaction outputs from the script address.
    * `"withdraw"`: For withdrawing staking rewards.
    * `"publish"`: For publishing delegation certificates.
    * `"vote"`: For voting on governance proposals.
    * `"propose"`: For executing constitution guardrails when submitting governance proposals.
  * `data` (object): An object containing the hex string: `{ "hex": "..." }`.
  * `addressFormat` (string, optional): The desired address format (`"bech32"` or `"raw"`).
  * `blueprint` (object, optional): The CIP-57 blueprint if the script is not yet known to Anvil. See the [Blueprint Management](https://github.com/Cardano-Forge/anvil-api/blob/main/docs/guides/guides/smart-contract/blueprint-management.md) guide for more details.

<details>

<summary>TypeScript Example: Parse a datum from a transaction output</summary>

```typescript
async function parseDatum(scriptHash: string, datumHex: string) {
  const response = await fetch(`https://preprod.api.ada-anvil.app/v2/services/validators/${scriptHash}/parse`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      type: "datum",
      purpose: "spend", // or "mint", etc., depending on the script
      data: {
        hex: datumHex
      }
    })
  });

  const result = await response.json();
  
  // Returns the parsed datum as a JSON object
  return result;
}

// The API parses the hex string into a human-readable JSON object based on the validator's schema.
// {
//   "owner": "30f4e824283240d2ca66f3e09b0b7adfc5d37816c072279b31f090a4"
// }

```

</details>

### Serialize Plutus Data

**`POST /validators/{hash}/serialize`**

Serializes a JSON object into a hex-encoded Plutus data string based on the script's schema. The opposite of parse.

* **Path Parameters**:
  * `hash` (string): The hash of the script. The API uses this hash to fetch the validator's schema, which is required to correctly convert the data between JSON and its hex-encoded format.
* **Body**:
  * `type` (string): The type of data to serialize (`"datum"` or `"redeemer"`).
  * `purpose` (string): The purpose of the script, which determines the context in which it's validated. Possible values are:
    * `"mint"`: For minting or burning assets.
    * `"spend"`: For spending transaction outputs from the script address.
    * `"withdraw"`: For withdrawing staking rewards.
    * `"publish"`: For publishing delegation certificates.
    * `"vote"`: For voting on governance proposals.
    * `"propose"`: For executing constitution guardrails when submitting governance proposals.
  * `data` (object): The JSON object to serialize.
  * `blueprint` (object, optional): The CIP-57 blueprint if the script is not yet known to Anvil. See the [Blueprint Management](https://github.com/Cardano-Forge/anvil-api/blob/main/docs/guides/guides/smart-contract/blueprint-management.md) guide for more details.

<details>

<summary>TypeScript Example: Serialize a datum object into hex</summary>

```typescript
// The is the opposite of parse. It takes a JSON object and returns a hex string.
async function serializeDatum(scriptHash: string, datumObject: unknown) {
  const response = await fetch(`https://preprod.api.ada-anvil.app/v2/services/validators/${scriptHash}/serialize`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      type: "datum",
      purpose: "spend", // or "mint", etc.
      data: datumObject // A JSON object matching the datum schema defined in your blueprint.
    })
  });

  const result = await response.json();
  
  // Returns the hex-encoded datum string
  return result;
}

// The API serializes the JSON object into a hex-encoded string based on the validator's schema.
// Output: "d8799f581c30f4e824283240d2ca..."
```

</details>


---

# 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/smart-contract/smart-contract-utilities.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.
