# Testing & Debugging \[Tools and techniques for testing policies, oracles, and attestations during Newton Protocol development]

Newton provides simulation endpoints and local tools at every layer of the stack. Use these to validate your policies, oracles, and integration before deploying to production.

## Local Policy Simulation

Test Rego policy logic without the network using the Newton CLI. Pass policy and data files with `-d` (repeatable), the intent with `-i`, and the query as a positional argument:

```bash
newton-cli regorus eval \
  -d policy.rego \
  -d data.json \
  -i intent.json \
  --non-strict \
  "data.policy.allow"
```

This evaluates your Rego v1 policy locally with Newton crypto extensions (`newton.crypto.ecdsa_recover_signer`, `newton.crypto.ecdsa_recover_signer_personal`). Newton's Regorus 0.9.0 fork implements an OPA v1.2.0-compatible subset, not every OPA built-in. Use `--non-strict` for OPA-style non-strict evaluation; it does not enable unavailable built-ins.

For writing Rego unit tests with `opa test`, see [Testing Policies & Oracles](/developers/guides/testing-policies).

## Local Oracle Simulation

Test your WASM data oracle without deploying:

```bash
newton-cli --chain-id 11155111 policy-data simulate \
  --wasm-file policy.wasm \
  --input-json '{"address": "0x742d35Cc6634C0532925a3b844Bc9e7595f2bD18"}'
```

The CLI runs your WASM component in a sandboxed environment with the Newton HTTP host. The `--input-json` value is passed to your `run` function as the `input` string.

## Gateway Simulation

The policy-set endpoints resolve a configured client on the specified chain. Use `policy_client`, numeric `chain_id`, `intent`, and positional `wasm_args` arrays. SDK `simulatePolicy` supports this schema in v1.2.2; its `simulateTask` wrapper does not.

| Endpoint | Executes WASM? | Input | Result |
|---|---|---|---|
| `newt_simulatePolicyData` | Yes, one policy's module | Policy address, chain, scalar args, optional inline secrets | Oracle output |
| `newt_simulatePolicyDataWithClient` | Yes, one policy's module | Policy address, chain, client, scalar args; stored secrets | Oracle output |
| `newt_simulatePolicy` | Yes, each policy's optional module | Current client set and ordered oracle inputs | Per-policy verdicts and aggregate `allowed` |
| `newt_simulateTask` | No | Current client set and ordered precomputed oracle outputs | Per-policy verdicts and aggregate `allowed` |

These simulations run in-process on the gateway. They do not produce BLS quorum signatures or execute application transactions. `newt_createTask` / `newt_sendTask` exercise live operator evaluation.

A completed denial has `success: true, allowed: false`; a simulation error has `success: false, allowed: null`. Inspect `policies[i].policy_index`, `policy`, `allowed`, and `result` to find the denying rule. See [RPC examples](/developers/reference/rpc-api#newt_simulatepolicy).

### Historical task investigation

Inspect the original task's frozen `policies`, `policyRevision`, `policyId`, ordered evidence, and aggregate verdict. Neither simulation endpoint replays the original snapshot: both resolve the client's current set. After reconfiguration, the same inputs can produce a different verdict. Reproduce a historical evaluation using its captured snapshot and matching evaluator revision in a local test.

Follow the [policy-set validation checklist](/developers/guides/testing-policies#policy-set-validation-checklist) before claiming end-to-end success.

## Newton Explorer

The [Newton Explorer](/developers/resources/newton-explorer) provides a visual interface for inspecting tasks, attestations, and policy evaluations on-chain. Use it to:

* View task status and results
* Inspect attestation details (signers, quorum, expiration)
* Trace the evaluation flow from intent to on-chain verification

### From the terminal

The same data is available from the [Explorer API](/developers/reference/explorer-api) with your `NEWTON_API_KEY`. Fetch a live task by the `task_id` from `newt_createTask` and pull out the fields that explain its result:

```bash
curl -sS https://explorer.api.newton.xyz/v1/task/$TASK_ID \
  -H "Authorization: Bearer $NEWTON_API_KEY" \
  -H "X-Protocol-Network: testnet" \
  | jq '{evaluation_result, error, operator_errors, policy_task_data}'
```

`policy_task_data` contains ordered evidence from the original evaluation. Preserve the original snapshot for historical reproduction; `newt_simulateTask` resolves the current set and is not a replay endpoint.

## BLS Diagnostics

If an attestation fails on-chain verification, check:

| Check | How |
|-------|-----|
| Attestation expiration | Compare `attestation.expiration` against current block number |
| Signer bitmap | Verify the signer bitmap includes enough operators for quorum |
| Reference block | Ensure the reference block matches the operator set used for verification |
| Chain ID | Confirm the intent's `chainId` matches the chain where the PolicyClient is deployed |

## Debugging Patterns

| Symptom | Likely Cause | Diagnostic Step |
|---------|-------------|-----------------|
| `newt_simulateTask` returns `non-compliant` | Policy logic rejects the intent | Run `newt_simulatePolicy` with the same inputs to isolate the Rego evaluation |
| Oracle returns empty data | WASM `run` function error or HTTP fetch failure | Test locally with `newton-cli policy-data simulate` |
| Attestation expires before on-chain submission | Too much time between evaluation and transaction | Reduce latency or increase the `expiry_offset` parameter |
| On-chain verification fails | Operator set rotated or wrong chain | Check reference block and chain ID |
| `TaskAlreadyExists` error | Duplicate intent hash | Modify the intent nonce or wait for the existing task |
| Policy returns `CAP` instead of `ALLOW` | Intent value exceeds policy threshold | Check `data.params` values on your PolicyClient |
| A live task was non-compliant or failed and you need to know why | Oracle data, params, or operator errors | Fetch the task from the [Explorer API](/developers/reference/explorer-api#check-a-task-after-submitting-it) and inspect `error`, `operator_errors`, and `policy_task_data` |

## SDK Debugging

Enable verbose logging in the Newton SDK:

```typescript
import { createPublicClient, http } from 'viem';
import { sepolia } from 'viem/chains';
import { newtonPublicClientActions } from '@newton-xyz/sdk';

const client = createPublicClient({
  chain: sepolia,
  transport: http(),
}).extend(newtonPublicClientActions());

// Simulate first to debug
const simulation = await client.simulateTask({
  policyClient: '0xYourPolicyClientAddress',
  intent: { /* ... */ },
});

console.log('Simulation result:', JSON.stringify(simulation, null, 2));
```

## Next Steps

<Card icon="list-check" to="/developers/resources/deployment-checklist" title="Deployment Checklist">
  Pre-launch verification checklist
</Card>

<Card icon="circle-exclamation" to="/developers/reference/error-reference" title="Error Reference">
  Complete error code reference
</Card>
