# view

## Overview

Execute a Move view function without submitting a transaction, consuming gas, or requiring a signature. View functions are read-only operations that run in the Move VM and return computed results. They are the most efficient way to query on-chain state that requires computation, such as calculated balances, prices, permissions, or derived values.

Only functions explicitly marked `view` can be called through this endpoint. The target function must actually be marked as view. A regular public function is not enough on its own.

## Endpoint

`POST /v1/view`

## Request Parameters

- `ledger_version` (`string, optional`): Query parameter: Execute the view function against state at this historical version
- `function` (`string, required`): Request Body: Fully qualified function identifier: `address::module::function_name`
- `type_arguments` (`array, required`): Request Body: Type parameters for generic functions (empty array if none needed)
- `arguments` (`array, required`): Request Body: Function arguments as JSON values (strings for addresses, numbers, booleans)

## Request Example

```json
{
  "function": "0x1::coin::balance",
  "type_arguments": ["0x1::aptos_coin::AptosCoin"],
  "arguments": ["0x1"]
}
```

## Response Fields

- `result` (`OBJECT, required`): ### Success Response (200) Returns an array of return values from the function: ```json [ "1500000000" ] ``` Return values are JSON-encoded according to their Move types. Functions returning multiple values produce arrays with multiple elements. ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 400 | invalid_input | Malformed request body, unknown function, or wrong number of arguments | | 400 | function_not_found | The specified function does not exist at the given address | | 400 | type_error | Type arguments don't match function signature | | 500 | vm_error | Function execution failed in the Move VM (such as arithmetic overflow, abort) |

## Successful Response

```json
[
  "1500000000"
]
```

## Error Responses

### Error 1

- Code: `invalid_input`
- Description: Malformed request body, unknown function, or wrong number of arguments

### Error 2

- Code: `function_not_found`
- Description: The specified function does not exist at the given address

### Error 3

- Code: `type_error`
- Description: Type arguments don't match function signature

### Error 4

- Code: `vm_error`
- Description: Function execution failed in the Move VM (such as arithmetic overflow, abort)

## Code Examples

cURL
Python
TypeScript
Rust

```bash
# Check APT balance
curl -s -X POST "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/view" \
  -H "Content-Type: application/json" \
  -d '{"function":"0x1::coin::balance","type_arguments":["0x1::aptos_coin::AptosCoin"],"arguments":["0x1"]}'

# Check if an account is registered for a coin
curl -s -X POST "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/view" \
  -H "Content-Type: application/json" \
  -d '{"function":"0x1::coin::is_account_registered","type_arguments":["0x1::aptos_coin::AptosCoin"],"arguments":["0x1"]}'

# Query at a historical version
curl -s -X POST "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/view?ledger_version=50000000" \
  -H "Content-Type: application/json" \
  -d '{"function":"0x1::coin::balance","type_arguments":["0x1::aptos_coin::AptosCoin"],"arguments":["0x1"]}'
```

```python
from aptos_sdk.client import RestClient

client = RestClient("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1")

# Check APT balance
result = client.view_function(
    "0x1::coin::balance",
    ["0x1::aptos_coin::AptosCoin"],
    ["0x1"]
)
balance_octas = int(result[0])
print(f"Balance: {balance_octas / 1e8} APT")

# Check coin registration
registered = client.view_function(
    "0x1::coin::is_account_registered",
    ["0x1::aptos_coin::AptosCoin"],
    ["0x1"]
)
print(f"Registered: {registered[0]}")

# Query total supply
supply = client.view_function(
    "0x1::coin::supply",
    ["0x1::aptos_coin::AptosCoin"],
    []
)
print(f"Supply: {supply[0]}")
```

```typescript
import { Aptos, AptosConfig } from "@aptos-labs/ts-sdk";

const config = new AptosConfig({
  fullnode: "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1"
});
const aptos = new Aptos(config);

// Check APT balance
const [balance] = await aptos.view({
  payload: {
    function: "0x1::coin::balance",
    typeArguments: ["0x1::aptos_coin::AptosCoin"],
    functionArguments: ["0x1"]
  }
});
console.log(`Balance: ${Number(balance) / 1e8} APT`);

// Check if account exists
const [exists] = await aptos.view({
  payload: {
    function: "0x1::account::exists_at",
    typeArguments: [],
    functionArguments: ["0x1"]
  }
});
console.log(`Account exists: ${exists}`);

// Query a custom DeFi protocol
const [price] = await aptos.view({
  payload: {
    function: "0xdex_address::pool::get_price",
    typeArguments: ["0x1::aptos_coin::AptosCoin", "0xusdc_address::usdc::USDC"],
    functionArguments: []
  }
});
```

```rust
use aptos_sdk::rest_client::Client;
use serde_json::json;

let client = Client::new("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1".parse()?);

let result = client.view(
    &json!({
        "function": "0x1::coin::balance",
        "type_arguments": ["0x1::aptos_coin::AptosCoin"],
        "arguments": ["0x1"]
    }),
    None,  // ledger_version
).await?;
println!("Balance: {:?}", result.inner());
```

## Common View Function Patterns

### Balance and Token Queries

```json
// Check coin balance
{ "function": "0x1::coin::balance", "type_arguments": ["0x1::aptos_coin::AptosCoin"], "arguments": ["0x1"] }

// Check if registered for a coin
{ "function": "0x1::coin::is_account_registered", "type_arguments": ["0x1::aptos_coin::AptosCoin"], "arguments": ["0x1"] }

// Get coin decimals
{ "function": "0x1::coin::decimals", "type_arguments": ["0x1::aptos_coin::AptosCoin"], "arguments": [] }

// Get coin name
{ "function": "0x1::coin::name", "type_arguments": ["0x1::aptos_coin::AptosCoin"], "arguments": [] }

// Get coin supply
{ "function": "0x1::coin::supply", "type_arguments": ["0x1::aptos_coin::AptosCoin"], "arguments": [] }
```

### Account and System Queries

```json
// Check if account exists
{ "function": "0x1::account::exists_at", "type_arguments": [], "arguments": ["0x1"] }

// Read a view that is explicitly marked `view`
{ "function": "0x1::account::exists_at", "type_arguments": [], "arguments": ["0x1"] }
```

## Use Cases

1. **Balance Queries**: Check account balances for any fungible token without transaction overhead or gas costs. Ideal for wallet UIs, portfolio trackers, and balance verification.

2. **State Inspection**: Read computed contract state like pool prices, lending rates, or staking rewards that require on-chain calculation rather than simple resource reads.

3. **Validation Checks**: Verify conditions before transaction submission (sufficient balance, correct permissions, valid parameters) to prevent failed transactions and wasted gas.

4. **UI Data Fetching**: Power application UIs with real-time blockchain data. View functions are fast enough for user-facing queries without needing a dedicated indexer.

5. **Price Feeds**: Query DEX pool prices, oracle data, or computed exchange rates for display, trading logic, or arbitrage detection.

6. **Permission Checks**: Verify user roles, capabilities, or access control before allowing operations in your application.

## Best Practices

**Function Visibility**: Only functions explicitly marked with the `#[view]` attribute can be called via this endpoint. Entry functions and ordinary `public fun` functions that are not declared as view functions cannot be used here, even if they only read state.

**Gas-Free Execution**: View functions do not consume gas or require signatures, making them ideal for frequent, high-volume queries from frontends and monitoring systems.

**Type Arguments**: Provide full type paths including generics. For example, use `0x1::aptos_coin::AptosCoin` rather than just `AptosCoin`. Type arguments correspond to the generic parameters in the function signature.

**Argument Encoding**: Arguments are passed as JSON values and automatically BCS-encoded by the API. Large integers (u64 and above) must be passed as strings to avoid JSON precision loss.

**Caching**: View function results reflect the state at the current (or specified) ledger version. Cache based on how frequently the underlying state changes -- token balances change with every transfer, while protocol parameters may change infrequently.

**Ledger Version**: Use the `ledger_version` query parameter to query historical state. This enables time-travel queries and consistent multi-call snapshots when all calls use the same version.

**Error Handling**: View functions that call `abort` in the Move VM return a 500 error. Check for this when querying functions that have assertion checks (such as querying a balance for a non-existent coin store).

## Performance Considerations

View functions execute directly in the Move VM without consensus or state commitment overhead. Response times are typically 20-100ms depending on function complexity.

- Simple reads (balance, existence check): 20-50ms
- Moderate computation (price calculation, aggregate queries): 50-100ms
- Complex computations (multi-step simulations): 100-200ms

View functions are significantly faster than full transaction simulation for read operations. For frequently accessed data, implement client-side caching with TTLs based on block time (approximately 4 seconds on mainnet).

For batch queries, make concurrent requests rather than sequential calls. View functions are stateless and can safely run in parallel without ordering concerns.

## Related Endpoints

- `/v1/accounts/{address}/resource/{resource_type}` - Direct resource read (no computation)
- `/v1/accounts/{address}/resources` - List all resources under an account
- `/v1/accounts/{address}/modules` - Discover available view functions via ABI
- `/v1/transactions/simulate` - Simulate a full transaction with state changes
