# 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 policy locally with full support for Newton crypto extensions (`newton.crypto.ecdsa_recover_signer`, `newton.crypto.ecdsa_recover_signer_personal`). Use `--non-strict` for OPA-compatible evaluation.

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

Simulate a full policy evaluation via the Gateway RPC without any on-chain interaction:

### Simulate a Task

Tests the complete evaluation pipeline (data oracle + policy) for a specific PolicyClient:

```bash
curl -X POST https://gateway.testnet.newton.xyz/rpc \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <your_api_key>" \
  -d '{
    "jsonrpc": "2.0",
    "method": "newt_simulateTask",
    "params": {
      "policy_client": "0xYourPolicyClientAddress",
      "intent": {
        "from": "0xCallerAddress",
        "to": "0xTargetAddress",
        "value": "0x0",
        "data": "0x",
        "chain_id": "0xaa36a7",
        "function_signature": "0x"
      }
    },
    "id": "7ca6621b-7aa4-4bb7-a896-1f2b58a18c78"
  }'
```

### Simulate Policy Only

Test full Rego policy evaluation, running each referenced oracle and merging its output into `data.wasm`. Pass the Rego source, one entry per oracle in `policy_data`, and `policy_params`:

```bash
curl -X POST https://gateway.testnet.newton.xyz/rpc \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <your_api_key>" \
  -d '{
    "jsonrpc": "2.0",
    "method": "newt_simulatePolicy",
    "params": {
      "policy_client": "0xYourPolicyClient",
      "policy": "package trading\n\ndefault allow := false\n...",
      "entrypoint": "trading.allow",
      "intent": { "from": "0x...", "to": "0x...", "value": "0x0", "data": "0x", "chain_id": "0xaa36a7", "function_signature": "0x" },
      "policy_data": [ { "policy_data_address": "0xYourPolicyData" } ],
      "policy_params": { "max_price": 50000 }
    },
    "id": "7ca6621b-7aa4-4bb7-a896-1f2b58a18c78"
  }'
```

### Simulate PolicyData Only

Test a WASM oracle execution via the Gateway:

<Tabs>
  <Tab title="With inline secrets">
    ```bash
    curl -X POST https://gateway.testnet.newton.xyz/rpc \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer <your_api_key>" \
      -d '{
        "jsonrpc": "2.0",
        "method": "newt_simulatePolicyData",
        "params": {
          "policy_data_address": "0xYourPolicyData",
          "wasm_args": "0x7b2261646472657373223a22307830227d",
          "chain_id": 11155111
        },
        "id": "7ca6621b-7aa4-4bb7-a896-1f2b58a18c78"
      }'
    ```

    :::note
    Pass encrypted secrets via the optional `secrets` field (base64-encoded ciphertext) to test with credentials. See the [RPC API](/developers/reference/rpc-api#newt-simulatepolicydata).
    :::
  </Tab>

  <Tab title="With stored secrets">
    ```bash
    curl -X POST https://gateway.testnet.newton.xyz/rpc \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer <your_api_key>" \
      -d '{
        "jsonrpc": "2.0",
        "method": "newt_simulatePolicyDataWithClient",
        "params": {
          "policy_data_address": "0xYourPolicyData",
          "policy_client": "0xYourPolicyClientAddress",
          "wasm_args": "0x7b2261646472657373223a22307830227d"
        },
        "id": "7ca6621b-7aa4-4bb7-a896-1f2b58a18c78"
      }'
    ```

    :::note
    Requires ownership of the PolicyClient. The Gateway reads secrets stored via `newt_storeEncryptedSecrets`.
    :::
  </Tab>
</Tabs>

## Simulation Endpoints Comparison

Newton provides four distinct simulation endpoints for different phases of policy development:

| Endpoint | Purpose | Data Source | Operators | Use Case |
|----------|---------|-------------|-----------|----------|
| `newt_simulatePolicyData` | Test WASM plugin execution | Caller provides secrets directly | Yes (delegation) | Iterate WASM before uploading secrets |
| `newt_simulatePolicyDataWithClient` | Verify stored secrets work | Reads secrets from gateway DB | Yes (delegation) | Verify uploaded secrets |
| `newt_simulatePolicy` | Full Rego + WASM evaluation | Delegates to operators for full pipeline | Yes (full pipeline) | Final testing before deployment |
| `newt_simulateTask` | Replay with pre-assembled data | Uses provided PolicyTaskData directly | No (local only) | Replay historical tasks, debugging |

`simulatePolicy` delegates to an operator via `broadcast_first_success` — it runs the full data pipeline (fetches WASM from IPFS, decrypts stored secrets, executes each PolicyData plugin, merges outputs, evaluates Rego). `simulateTask` takes pre-assembled `PolicyTaskData` and evaluates Rego against it locally — the data pipeline is skipped because data is already assembled.

**Recommended development workflow:**

1. Deploy PolicyData contracts
2. Test WASM locally with `newt_simulatePolicyData`
3. Upload secrets via `newt_storeEncryptedSecrets`
4. Verify stored secrets with `newt_simulatePolicyDataWithClient`
5. Test full policy end-to-end with `newt_simulatePolicy`
6. Deploy Policy on-chain
7. Submit production tasks with `newt_createTask` / `newt_sendTask`
8. Debug/replay tasks with `newt_simulateTask`

## 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

## 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 |

## 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>
