Skip to main content
The Newton Gateway provides a JSON-RPC 2.0 interface for submitting policy evaluation tasks to the Newton Protocol AVS (Actively Validated Service). The protocol evaluates user intents against Rego policies and returns cryptographic proofs of compliance through BLS signatures. For client-side helpers that wrap these RPC calls, see the SDK Reference. For a step-by-step walkthrough of building on Newton, see the Integration Guide.

Base URLs

NetworkEnvironmentURL
SepoliaStaginghttps://gateway-avs.stagef.sepolia.newt.foundation/rpc
SepoliaProductionhttps://gateway-avs.sepolia.newt.foundation/rpc
MainnetStaginghttps://gateway-avs.stagef.newt.foundation/rpc
MainnetProductionhttps://gateway-avs.newt.foundation/rpc
Protocol: JSON-RPC 2.0 over HTTPS
{
  "jsonrpc": "2.0",
  "method": "<method_name>",
  "params": { ... },
  "id": "<request_id>"
}

Authentication

All API requests require authentication via API key. Include the key in the Authorization header:
Authorization: Bearer <your_api_key>
API keys are issued with specific permissions. Email [email protected] to request one.

Permission Levels

PermissionDescription
RpcReadRead-only operations: task submission, simulation
RpcWriteWrite operations: secrets management

Example

curl -X POST https://gateway-avs.sepolia.newt.foundation/rpc \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your_api_key_here" \
  -d '{"jsonrpc":"2.0","method":"newt_createTask","params":{...},"id":1}'

Policy Client Ownership

Some endpoints require ownership verification of a policy_client address. This mechanism protects access to stored secrets and ensures only the user who uploaded secrets can access them. How Ownership Works:
  1. Ownership is established when you first call newt_storeEncryptedSecrets for a policy_client address. The user_id associated with your API key becomes the owner of that policy_client.
  2. Ownership is verified when calling endpoints that require it. The gateway checks that the caller’s API key belongs to the same user who owns the policy_client.
  3. Ownership is permanent (per policy_client). Once established, only the owning user can upload new secrets or access stored secrets for that policy_client.
Endpoints Requiring Ownership Verification:
EndpointOwnership Required
newt_simulatePolicyDataNo (caller provides secrets directly)
newt_simulatePolicyDataWithClientYes (fetches stored secrets)
newt_simulatePolicyConditional (only if PolicyData requires secrets)
newt_storeEncryptedSecretsClaims if unowned, verifies if owned
Conditional Ownership for newt_simulatePolicy: The newt_simulatePolicy endpoint only requires ownership verification when at least one PolicyData contract has a secretsSchemaCid (indicating stored secrets are required). If all PolicyData contracts in your request have empty secretsSchemaCid values (no secrets needed), ownership verification is skipped. This allows testing simple policies without requiring secrets to be uploaded first.
Error Responses: If ownership verification fails, you will receive one of these errors:
  • "policy_client is owned by another user" — The policy_client was registered by a different user.
  • "policy client has no owner - upload secrets first via newt_storeEncryptedSecrets" — No ownership established yet.

Conventions

Hex Value Encoding

Following Ethereum JSON-RPC conventions: Quantities (integers, numbers):
  • Encode as hex with 0x prefix
  • Use most compact representation (no leading zeros except for zero itself)
  • Zero is represented as "0x0"
0x41      (65 in decimal)
0x400     (1024 in decimal)
0x0       (zero)
Unformatted Data (byte arrays, addresses, hashes):
  • Encode as hex with 0x prefix
  • Two hex digits per byte
  • Even number of digits required
0x1234567890123456789012345678901234567890   (20-byte address)
0x28dca9f7                                   (4-byte function selector)
0x                                           (empty data)

Address Format

Ethereum addresses are 20-byte hex strings with 0x prefix:
0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266
Addresses are case-insensitive but checksummed addresses are recommended.

Common Types

TaskIntent

Represents a transaction intent to be evaluated against a policy.
FieldTypeRequiredDescription
fromAddressYesTransaction sender address
toAddressYesTransaction recipient address
valueQuantityYesWei value to transfer (hex encoded)
dataDataYesTransaction calldata (hex encoded)
chain_idQuantityYesTarget chain ID (hex encoded)
function_signatureDataYesABI-encoded function signature (hex encoded)

PolicyDataInput

Specifies a PolicyData contract and optional WASM arguments for policy simulation.
FieldTypeRequiredDescription
policy_data_addressAddressYesDeployed PolicyData contract address
wasm_argsDataNoHex-encoded WASM arguments for this data source

TaskStatus

Enumeration of task processing states.
ValueDescription
pendingTask queued for processing
processingTask being evaluated by operators
successTask completed successfully
failedTask evaluation failed
timeoutTask exceeded timeout threshold

RPC Methods

newt_createTask

Creates a task and waits synchronously for the BLS aggregation result. Use this for simple integrations where blocking is acceptable. Permission: RpcRead

Parameters

FieldTypeRequiredDescription
policy_clientAddressYesPolicy client contract address
intentTaskIntentYesTransaction intent to evaluate
intent_signatureDataNoHex-encoded signature of the intent
quorum_numberDataNoQuorum numbers (hex bytes, e.g., "00" for quorum 0)
quorum_threshold_percentageNumberNoBLS aggregation threshold (0-100)
wasm_argsDataNoHex-encoded WASM plugin arguments
timeoutNumberNoTimeout in seconds (default: 30)
use_two_phaseBooleanNoEnable Two-Phase Consensus Protocol (default: false)

Returns

FieldTypeDescription
task_idData32-byte task identifier
statusTaskStatusFinal task status
aggregation_responseObjectBLS aggregation result (if successful)
taskObjectFull Task struct for validateAttestationDirect (if success)
task_responseObjectFull TaskResponse struct from aggregation (if success)
reference_blockNumberBlock number when response was prepared (if success)
expirationNumberExpiration block: reference_block + policyConfig.expireAfter
errorStringError message (if failed)
timestampNumberUnix timestamp
The task, task_response, reference_block, and expiration fields enable clients to call validateAttestationDirect optimistically without waiting for on-chain task submission. The signature_data field contains pre-built, chain-aware encoded bytes ready to pass directly to the contract.

Example

{
  "jsonrpc": "2.0",
  "method": "newt_createTask",
  "params": {
    "policy_client": "0x1234567890123456789012345678901234567890",
    "intent": {
      "from": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
      "to": "0xb1aD5f82407bC0f19f42b2614fb9083035a36b69",
      "value": "0x0",
      "data": "0x28dca9f7000000000000000000000000e42e3458283032c669c98e0d8f883a92fc64fe22",
      "chain_id": "0xaa36a7",
      "function_signature": "0x627579"
    },
    "timeout": 30
  },
  "id": 1
}

newt_sendTask

Submits a task asynchronously and returns immediately with a WebSocket subscription topic for receiving updates. Permission: RpcRead

Parameters

FieldTypeRequiredDescription
policy_clientAddressYesPolicy client contract address
intentTaskIntentYesTransaction intent to evaluate
intent_signatureDataNoHex-encoded signature of the intent
quorum_numberDataNoQuorum numbers (hex bytes)
quorum_threshold_percentageNumberNoBLS aggregation threshold (0-100)
wasm_argsDataNoHex-encoded WASM plugin arguments

Returns

FieldTypeDescription
task_idData32-byte task identifier
subscription_topicStringWebSocket topic for task updates
messageStringConfirmation message
timestampNumberUnix timestamp

Example

{
  "jsonrpc": "2.0",
  "method": "newt_sendTask",
  "params": {
    "policy_client": "0x1234567890123456789012345678901234567890",
    "intent": {
      "from": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
      "to": "0xb1aD5f82407bC0f19f42b2614fb9083035a36b69",
      "value": "0x0",
      "data": "0x28dca9f7",
      "chain_id": "0x1",
      "function_signature": "0x627579"
    }
  },
  "id": 1
}

WebSocket Updates

Connect to the WebSocket endpoint and subscribe to the returned topic:
{
  "type": "subscribe",
  "id": "sub-1",
  "method": "newton.task.0x1234567890abcdef...",
  "params": null
}
Updates are received in the following format:
{
  "type": "update",
  "subscription": "sub-1",
  "result": {
    "event": "success",
    "task_id": "0x1234567890abcdef...",
    "timestamp": 1705123460,
    "data": {
      "status": "success",
      "operator_responses": [],
      "result": { },
      "progress": 100
    }
  }
}

newt_simulateTask

Forwards a policy simulation request to an available operator and returns the result. This endpoint tests the full operator evaluation flow without executing on-chain. Requires at least one registered operator to be available. Permission: RpcRead

Parameters

FieldTypeRequiredDescription
intentTaskIntentYesTransaction intent to simulate
policy_task_dataPolicyTaskDataYesPolicy task data for evaluation
PolicyTaskData Structure:
FieldTypeDescription
policyIdbytes32Policy identifier (32-byte hex string)
policyAddressaddressPolicy contract address
policybytesPolicy bytecode (hex string, can be "0x")
policyDataPolicyData[]Array of policy data sources for evaluation
PolicyData Structure:
FieldTypeDescription
wasmArgsbytesWASM plugin arguments (hex-encoded)
databytesPre-fetched data (hex string)
attestationbytesData attestation signature (hex string)
policyDataAddressaddressPolicyData contract address
expireBlockuint32Block number when data expires

Returns

FieldTypeDescription
successBooleanWhether evaluation succeeded
resultObjectEvaluation result (if successful)
errorStringError message (if failed)
detailsObjectExecution details

Example

{
  "jsonrpc": "2.0",
  "result": {
    "success": true,
    "result": {
      "allow": true,
      "reason": "Policy conditions met"
    },
    "error": null,
    "details": null
  },
  "id": 1
}

newt_storeEncryptedSecrets

Uploads KMS-encrypted secrets for a PolicyData contract. Secrets are validated against the on-chain schema and stored for use during task evaluation. Permission: RpcWrite

Parameters

FieldTypeRequiredDescription
policy_clientAddressYesPolicy client contract address
policy_data_addressAddressYesPolicyData contract address
secretsStringYesBase64-encoded KMS ciphertext

Returns

FieldTypeDescription
successBooleanWhether upload succeeded
schemaObjectJSON schema used for validation (on success)
errorStringError message (on failure)

Encryption Requirements

Secrets must be encrypted using AWS KMS before upload:
  1. Create a JSON object with your secrets
  2. Encrypt using Newton Protocol’s KMS key
  3. Base64-encode the ciphertext
Plaintext format (before encryption):
{
  "API_KEY": "sk-xxxxxxxxxxxxx",
  "ENDPOINT": "https://api.example.com"
}

Ownership Model

  • The first user to upload secrets for a policy client becomes the permanent owner.
  • Only the owner can update secrets for that policy client.
  • Ownership cannot be transferred.

Example

{
  "jsonrpc": "2.0",
  "method": "newt_storeEncryptedSecrets",
  "params": {
    "policy_client": "0x1234567890123456789012345678901234567890",
    "policy_data_address": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd",
    "secrets": "AQICAHhZ8...base64_kms_ciphertext..."
  },
  "id": 1
}

newt_simulatePolicyData

Simulates PolicyData WASM execution with caller-provided secrets. Use this endpoint to iterate on WASM plugins before uploading production secrets. Permission: RpcRead Authorization: Rate limiting only. Any valid API key can call this endpoint. No ownership verification is performed because secrets are provided directly by the caller.

When to Use

  • Iterating on PolicyData WASM before uploading production secrets
  • Testing WASM execution with different secret configurations
  • PolicyData contracts that don’t require secrets (secrets field is optional)

Workflow

  1. Deploy PolicyData contract with wasmCid and optional secretsSchemaCid
  2. Call newt_simulatePolicyData with optional encrypted secrets to test
  3. Once satisfied, upload production secrets via newt_storeEncryptedSecrets
  4. Test full policy via newt_simulatePolicy or newt_simulatePolicyDataWithClient

Parameters

FieldTypeRequiredDescription
policy_data_addressAddressYesPolicyData contract address
secretsStringNoBase64-encoded KMS ciphertext (for testing)
wasm_argsDataNoHex-encoded WASM arguments

Returns

FieldTypeDescription
successBooleanWhether simulation succeeded
policy_dataObjectWASM execution result (on success)
errorStringError message (on failure)
The policy_data object contains:
FieldTypeDescription
specifierStringWASM source identifier (IPFS CID)
dataObjectWASM output data
timestampNumberExecution timestamp

Example

{
  "jsonrpc": "2.0",
  "method": "newt_simulatePolicyData",
  "params": {
    "policy_data_address": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "secrets": "AQICAHhZ8...base64_kms_ciphertext...",
    "wasm_args": "0x7b22626173655f73796d626f6c223a22425443227d"
  },
  "id": 1
}

newt_simulatePolicyDataWithClient

Simulates PolicyData WASM execution with previously uploaded secrets. Use this endpoint to test that stored secrets work correctly before testing the full policy. Permission: RpcRead Authorization: Ownership verification required. The caller’s API key must belong to the user who owns the policy_client address. Ownership is established when secrets are first uploaded via newt_storeEncryptedSecrets.

When to Use

  • Testing PolicyData WASM with previously uploaded secrets
  • Verifying stored secrets work correctly before using newt_simulatePolicy
  • Debugging policy failures by testing individual PolicyData sources

Prerequisites

  1. Deploy PolicyData contract with wasmCid and optional secretsSchemaCid
  2. Upload secrets via newt_storeEncryptedSecrets (establishes ownership)
  3. Call this endpoint to test with stored secrets

Parameters

FieldTypeRequiredDescription
policy_data_addressAddressYesPolicyData contract address
policy_clientAddressYesPolicy client address (for ownership check + secrets lookup)
wasm_argsDataNoHex-encoded WASM arguments

Returns

FieldTypeDescription
successBooleanWhether simulation succeeded
policy_dataObjectWASM execution result (on success)
errorStringError message (on failure)

Example

{
  "jsonrpc": "2.0",
  "method": "newt_simulatePolicyDataWithClient",
  "params": {
    "policy_data_address": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "policy_client": "0x1234567890123456789012345678901234567890",
    "wasm_args": "0x7b22626173655f73796d626f6c223a22425443227d"
  },
  "id": 1
}

newt_simulatePolicy

Simulates full Rego policy evaluation locally. This is the final testing step before deploying a policy on-chain. Permission: RpcRead Authorization: Conditional ownership verification. Ownership is only required when at least one PolicyData contract has a secretsSchemaCid (requires stored secrets). If no PolicyData contracts require secrets, the endpoint can be called without ownership verification. When required, the caller’s API key must belong to the user who owns the policy_client address. Ownership is established when secrets are first uploaded via newt_storeEncryptedSecrets.

When to Use

  • Final policy testing before on-chain deployment
  • Iterating on Rego policy logic with real PolicyData outputs
  • Validating end-to-end policy behavior with sample intents

Prerequisites

Before using this endpoint:
  1. Deploy PolicyData contracts with WASM plugins
  2. Test each PolicyData via newt_simulatePolicyData (iterate on WASM logic)
  3. Upload secrets via newt_storeEncryptedSecrets for each PolicyData that requires secrets
  4. (Optional) Test individual PolicyData with stored secrets via newt_simulatePolicyDataWithClient

Parameters

FieldTypeRequiredDescription
policy_clientAddressYesPolicy client address (for ownership check + secrets lookup)
policyStringYesRego policy source code
intentTaskIntentYesSample intent to evaluate
entrypointStringNoRego rule path (default: "policy.allow")
policy_dataArray<PolicyDataInput>YesPolicyData sources with optional wasm_args
policy_paramsObjectNoPolicy parameters JSON (default: {})
intent_signatureDataNoHex-encoded intent signature

Returns

FieldTypeDescription
successBooleanWhether simulation succeeded
evaluation_resultObjectEvaluation result (on success)
errorStringError message (on failure)
error_detailsObjectStructured error details (when secrets are missing)
The evaluation_result object contains:
FieldTypeDescription
policyStringEvaluated policy source
parsed_intentObjectParsed and decoded intent
policy_params_and_dataObjectCombined { params, data } context
entrypointStringEvaluated Rego entrypoint
resultAnyRego evaluation result (true, false, or complex value)
expire_afterNumberExpiration time (0 for simulation)
The error_details object (when secrets are missing) contains:
FieldTypeDescription
missing_secretsArray<Object>List of PolicyData contracts with missing secrets
suggested_actionsArray<String>Actions to resolve the issue
Each entry in missing_secrets:
FieldTypeDescription
policy_data_addressAddressPolicyData contract address requiring secrets
has_secrets_schemaBooleanWhether this PolicyData has a secretsSchemaCid

Example

{
  "jsonrpc": "2.0",
  "result": {
    "success": true,
    "evaluation_result": {
      "policy": "package trading\n\ndefault allow := false\n\nallow if {...}",
      "parsed_intent": {
        "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
        "to": "0xb1ad5f82407bc0f19f42b2614fb9083035a36b69",
        "value": 0,
        "function": {
          "name": "buy",
          "arguments": []
        },
        "chain_id": 11155111
      },
      "policy_params_and_data": {
        "params": { "max_price": 50000 },
        "data": { "price": 42000.50, "base_symbol": "BTC" }
      },
      "entrypoint": "trading.allow",
      "result": true,
      "expire_after": 0
    },
    "error": null
  },
  "id": 1
}

newt_registerWebhook

Registers a webhook URL to receive failure notifications for tasks created with this API key.

Parameters

NameTypeRequiredDescription
urlstringYesHTTPS URL to receive notifications
secretstringNoHMAC secret for payload signing (recommended)
timeout_secondsnumberNoRequest timeout in seconds (default: 10)
max_retriesnumberNoMaximum retry attempts (default: 3)
failure_typesstring[]NoFailure types to notify about (default: all)
Failure Types:
  • channel_error — Internal channel communication failures
  • timeout — Task processing timed out
  • quorum_not_reached — Insufficient operator signatures
  • onchain_submission_failed — Blockchain submission failed
  • policy_evaluation_failed — Policy evaluation error
  • signature_verification_failed — BLS signature verification error
  • internal_error — Unexpected internal error

Example

{
  "jsonrpc": "2.0",
  "method": "newt_registerWebhook",
  "params": {
    "url": "https://api.example.com/newton/webhook",
    "secret": "your-hmac-secret-here",
    "failure_types": ["timeout", "quorum_not_reached", "onchain_submission_failed"]
  },
  "id": 1
}

newt_unregisterWebhook

Removes the webhook configuration for this API key. Parameters: None

Example

{
  "jsonrpc": "2.0",
  "method": "newt_unregisterWebhook",
  "params": {},
  "id": 1
}

Failure Notifications

The Newton Gateway provides real-time failure notifications through two channels: WebSocket subscriptions and webhook callbacks. Use WebSocket for real-time UI updates and webhooks for reliable server-to-server notifications.

WebSocket Notifications

WebSocket notifications are best for:
  • Real-time UI updates in browser applications
  • Low-latency notification requirements
  • Clients that maintain persistent connections
When subscribed to a task via WebSocket, failure notifications are delivered as JSON messages containing the full TaskFailureNotification payload.

Webhook Callbacks

Webhook callbacks are best for:
  • Server-to-server integrations
  • Reliable delivery with automatic retries
  • Auditable notification history
  • Clients that cannot maintain persistent connections
Webhook Request Format: The gateway sends POST requests to your registered URL with the following structure: Security Headers:
HeaderDescription
X-Newton-SignatureHMAC-SHA256 signature (if secret configured)
X-Idempotency-KeyUnique notification ID for deduplication
Content-Typeapplication/json
Signature Verification:
import hmac
import hashlib

def verify_signature(payload: bytes, signature: str, secret: str) -> bool:
    expected = "sha256=" + hmac.new(
        secret.encode(),
        payload,
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(signature, expected)
Retry Behavior:
  • Initial retry after 100ms with exponential backoff
  • Maximum 3 retry attempts (configurable)
  • Backoff capped at 10 seconds
  • 4xx client errors (except 429) are not retried

Developer Workflow

Policy Development Lifecycle

Integration Checklist

  1. Obtain API Key
    • Request API key with appropriate permissions
    • RpcRead for task submission and simulation
    • RpcWrite for secrets management
  2. Set Up PolicyData
    • Deploy PolicyData contracts
    • Test WASM execution with newt_simulatePolicyData
    • Upload secrets with newt_storeEncryptedSecrets
  3. Develop Policy
    • Write Rego policy code
    • Test with newt_simulatePolicy
    • Deploy policy contract on-chain
  4. Integrate Task Submission
    • Use newt_createTask for synchronous flow
    • Use newt_sendTask + WebSocket for async flow

Error Codes

JSON-RPC Standard Errors

CodeMessageDescription
-32700Parse errorInvalid JSON
-32600Invalid requestInvalid JSON-RPC structure
-32601Method not foundUnknown RPC method
-32602Invalid paramsInvalid method parameters
-32603Internal errorServer error

Newton-Specific Error Codes

CodeNameDescription
-32615PolicyEvaluationErrorPolicy evaluation failed
-32616ContractErrorSmart contract interaction error
-32617OperatorNotRegisteredOperator is not registered with the AVS
-32618IncompatiblePolicyVersionPolicy version mismatch between client/server
-32619IncompatiblePolicyDataVersionPolicy data version mismatch
-32620DataProviderErrorError fetching policy data from data provider

Newton-Specific Error Messages

Error MessageCauseResolution
"Unknown Newton RPC method: {method}"Invalid method nameCheck method spelling
"Invalid request format: {details}"Malformed parametersReview parameter types
"RpcRead permission required"Missing read permissionUse key with RpcRead
"RpcWrite permission required"Missing write permissionUse key with RpcWrite
"Invalid API key"Invalid or expired keyVerify API key
"policy client {addr} is owned by another user"Ownership violationUse API key that owns the policy_client
"policy client {addr} has no owner..."No ownership establishedUpload secrets first via newt_storeEncryptedSecrets
"Missing secrets for N PolicyData contract(s)"Secrets not uploadedUpload secrets via newt_storeEncryptedSecrets
"No secrets found for policy_client ... and policy_data..."Secrets not uploaded for pairUpload secrets or use newt_simulatePolicyData instead
"Secrets upload validation failed: {details}"Schema validation failureFix secrets format
"WASM execution failed: {details}"WASM runtime errorCheck WASM and inputs
"Rego evaluation failed: {details}"Policy syntax/runtime errorFix Rego code
"Contract read failed: {details}"On-chain read errorVerify contract addresses
"Task timeout"Aggregation timeoutIncrease timeout or retry

HTTP Status Codes

StatusDescription
200Success (check JSON-RPC result for errors)
401Unauthorized - Invalid API key
403Forbidden - Insufficient permissions
429Too Many Requests - Rate limited
500Internal Server Error
502Bad Gateway - Service unavailable