# Utility Functions

Anvil provides several utility endpoints to simplify common operations when building Cardano applications. These endpoints handle tasks like address parsing, native script analysis, and time-slot conversions.

See full examples of the utility functions in the [examples repository](https://github.com/Cardano-Forge/anvil-api-examples/blob/main/utils/shared.ts).

## Quick Reference

| Category                                                | Function                                                   | Endpoint                               | Purpose                                                                         |
| ------------------------------------------------------- | ---------------------------------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------- |
| [**Address Utilities**](#address-utilities)             | [Parse Address](#post-utilsaddressesparse)                 | `POST /utils/addresses/parse`          | Extract payment and stake key hashes from Cardano addresses                     |
|                                                         | [Get Address Info](#post-addressesinfo)                    | `POST /addresses/info`                 | Extract payment and stake hashes with script detection for transaction building |
| [**Native Script Utilities**](#native-script-utilities) | [Parse Script](#post-utilsnative-scriptsparse)             | `POST /utils/native-scripts/parse`     | Calculate policy ID from native script                                          |
|                                                         | [Create Native Script](#post-utilsnative-scriptsserialize) | `POST /utils/native-scripts/serialize` | Create native script from JSON schema                                           |
| [**Network Time Utilities**](#network-time-utilities)   | [Slot to Time](#post-utilsnetworkslot-to-time)             | `POST /utils/network/slot-to-time`     | Convert slot number to timestamp                                                |
|                                                         | [Time to Slot](#post-utilsnetworktime-to-slot)             | `POST /utils/network/time-to-slot`     | Convert timestamp to slot number                                                |

## Available Utility Endpoints

### Address Utilities

#### POST `/utils/addresses/parse`

**What It Does:**

* Extracts payment and stake key hashes from Cardano addresses

**Parameters:**

* `address`: Bech32 or hex encoded address

**Returns:**

* `payment`: Payment key hash (hex encoded)
* `stake`: Optional stake key hash (hex encoded)

**Common Use Case:**

* Getting the payment key hash from a wallet address for native scripts
* Extracting stake key hash for delegation operations

<details>

<summary>TypeScript Example: Parse an address</summary>

```typescript
async function getPaymentCredentialFromAddress(address) {
  const response = await fetch('https://preprod.api.ada-anvil.app/v2/services/utils/addresses/parse', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      address: address
    })
  });

  return await response.json();
}
// Sample Output
// {
//   "payment": "addr1egrtarthsndgre...",
//   "stake": "stake1grhyjajuwsfbudh...",
// }

```

</details>

#### POST `/addresses/info`

**What It Does:**

* Returns detailed information about a Cardano address including payment and stake hashes
* Detects whether payment and stake hashes are script-based or key-based

**Parameters:**

* `address`: Bech32 or hex encoded address

**Returns:**

* `payment`: Object containing payment hash information
  * `hash`: Payment hash (hex encoded)
  * `isScript`: Boolean indicating if payment hash is a script hash
* `stake`: Optional object containing stake hash information
  * `hash`: Stake hash (hex encoded)
  * `isScript`: Boolean indicating if stake hash is a script hash

**Common Use Cases:**

* **Transaction Building**: Extract payment hashes for transaction inputs/outputs and stake hashes for delegation
* **Address Analysis**: Determine if an address uses script hashes for smart contract interactions
* **Multi-signature Setup**: Identify key hashes for multi-sig wallet configurations
* **Staking Management**: Extract stake hashes for delegation to different stake pools
* **Policy Creation**: Use payment hashes as conditions in native script minting policies

<details>

<summary>TypeScript Example: Get address information</summary>

```typescript
async function getAddressInfo(address) {
  const response = await fetch('https://preprod.api.ada-anvil.app/v2/services/utils/addresses/info', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      address: address
    })
  });

  return await response.json();
}
// Sample Output
// {
//   "payment": {
//     "hash": "1dd6dd756e5397e019debb4d116e11748a93d2f09fd7a894ec8f8af2",
//     "isScript": false
//   },
//   "stake": {
//     "hash": "7ba59464b2e19d6dcb3af04f6c0529a42d489290f3595ad68836df09",
//     "isScript": false
//   }
// }

```

</details>

### Native Script Utilities

#### POST `/utils/native-scripts/parse`

**What It Does:**

* Calculates policy ID and returns policy ID from the provided native script

**Parameters:**

* `script`: Hex encoded native script

**Returns:**

* `policyId`: The hash of the script (policy ID)

**Common Use Case:**

* Extracting a policy ID from a minting script
* Verifying script properties before transaction submission

<details>

<summary>TypeScript Example: Get policy ID from a native script</summary>

```typescript
async function getPolicyId(nativeScriptHex) {
  const response = await fetch('https://preprod.api.ada-anvil.app/v2/services/utils/native-scripts/parse', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      script: nativeScriptHex
    })
  });

  const result = await response.json();
  return result.policyId;
}
// Sample Output
// {
//   "policyId": "df37e17a949b061c15c53c485609652a6516315de90a88b611c03a9c"
// }

```

</details>

#### POST `/utils/native-scripts/serialize`

**What It Does:**

* Converts a native script JSON schema into CBOR hex-encoded format and generates its policy ID
* Essential for creating minting policies that can be used in transactions

**Parameters:**

* `schema`: The JSON representation of the native script (see [Native Scripts documentation](/guides/nft-and-ft/native-scripts.md) for structure details)

**Returns:**

* `policyId`: The hash of the script - this becomes your token's policy ID
* `script`: The CBOR hex-encoded script ready for transactions

**Common Use Cases:**

* Creating minting policies for NFT collections
* Setting up time-locked or multi-signature token policies

<details>

<summary>TypeScript Example: Create a time-locked minting policy</summary>

```typescript
async function createNativeScript(keyHash, slotNumber) {
  // Define a native script that requires signature AND time constraint
  const nativeScriptSchema = {
    type: "all",
    scripts: [
      {
        type: "sig",
        keyHash: keyHash // Payment key hash from wallet
      },
      {
        type: "before",
        slot: slotNumber // Minting deadline slot
      }
    ]
  };

  const response = await fetch('https://preprod.api.ada-anvil.app/v2/services/utils/native-scripts/serialize', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      schema: nativeScriptSchema
    })
  });

  const result = await response.json();
  
  return result;
}

// Sample Output
// {
//   "policyId": "df37e17a949b061c15c53c485609652a6516315de90a88b611c03a9c",
//   "script": "8201828200581c3910f0db63599cd9cb1484d5591491629470761a89cde0473e4b94f682051a06a60080"
// }

```

</details>

### Network Time Utilities

#### POST `/utils/network/slot-to-time`

**What It Does:**

* Converts a Cardano slot number to a timestamp

**Parameters:**

* `slot`: Absolute slot number

**Returns:**

* `time`: Unix timestamp in milliseconds (UTC)

**Common Use Case:**

* Converting slot-based time locks to human-readable DateTimes
* Displaying blockchain time information to users

<details>

<summary>TypeScript Example: Convert a slot to a timestamp</summary>

```typescript
async function slotToTimestamp(slotNumber) {
  const response = await fetch('https://preprod.api.ada-anvil.app/v2/services/utils/network/slot-to-time', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      slot: slotNumber
    })
  });

  const result = await response.json();
  // Returns Unix timestamp in milliseconds
  return new Date(result.time);
}
```

</details>

#### POST `/utils/network/time-to-slot`

**What It Does:**

* Returns the enclosing slot of the provided timestamp

**Parameters:**

* `time`: Unix timestamp in milliseconds (UTC)

**Returns:**

* `slot`: Absolute slot number

**Common Use Case:**

* Setting expiration times for minting policies
* Creating time-bounded transactions
* Creating time-bounded transactions

<details>

<summary>TypeScript Example: Convert a timestamp to a slot</summary>

```typescript
async function timeToSlot(date) {
  const response = await fetch('https://preprod.api.ada-anvil.app/v2/services/utils/network/time-to-slot', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      time: date.getTime() // Unix timestamp in milliseconds
    })
  });

  const result = await response.json();
  return result.slot;
}
```

</details>

## Best Practices

1. **Environment Awareness**
   * Remember that slot calculations differ between Mainnet, Preprod, and Preview
   * Always use the appropriate network endpoint for your target environment
2. **Error Handling**
   * Always check for error responses from utility endpoints
   * Handle edge cases appropriately in your application logic
3. **Caching**
   * Consider caching results from utility functions when appropriate
   * This can reduce API calls and improve application performance


---

# 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/developer-tools/utility-functions.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.
