Skip to main content

Newton Protocol SDK Reference

Official TypeScript SDK for the Newton Protocol. This page provides a complete reference for all exported methods, types, interfaces, and utilities in the @newton-xyz/sdk package.
The SDK integrates with viem by extending PublicClient and WalletClient instances with Newton-specific actions. Make sure you are familiar with viem basics before proceeding.

Installation

Requirements:
  • Node.js >= 20
  • Package manager: pnpm >= 9 (recommended)
Dependencies:

Overview

The SDK is organized into two main client extensions: For a step-by-step walkthrough of integrating these into your application, see the Integration Guide. For the underlying JSON-RPC methods the SDK calls, see the RPC API Reference.

Setup & Initialization

Newton Protocol currently supports Ethereum Sepolia (chain ID 11155111), Base Sepolia (chain ID 84532), Ethereum Mainnet (chain ID 1), and Base (chain ID 8453). Pass the corresponding chain object from viem/chains when constructing your clients.

newtonPublicClientActions

Extends a viem PublicClient with Newton Protocol read methods.
Signature:
Parameters:

newtonWalletClientActions

Extends a viem WalletClient with Newton Protocol write methods.
Signature:
Parameters:
Your API key authenticates requests to the Newton Gateway. Keep it secret and never expose it in client-side code.

SdkOverrides

Optional configuration to override default SDK endpoints and contract addresses.

Wallet Client Methods (Write)

These methods are available after extending a WalletClient with newtonWalletClientActions.

submitEvaluationRequest

Submits an intent evaluation request to the Newton Protocol via the gateway. The task is created on-chain and operators evaluate the intent against the policy. Returns a PendingTaskBuilder that can be used to await the task response.
Signature:
Parameters: Returns: An object containing:
  • result.taskId (Hex) — The unique task identifier
  • result.txHash (Hex) — The transaction hash
  • waitForTaskResponded({ timeoutMs? }) — A method to await the on-chain attestation result
The validate_calldata and operator_errors fields are available on the raw GatewayCreateTaskResult returned by the newt_createTask RPC method (see the RPC API Reference). These fields are not surfaced by the SDK’s submitEvaluationRequest or evaluateIntentDirect wrappers — call the gateway RPC directly when you need them.

evaluateIntentDirect

Evaluates an intent directly through the gateway without waiting for on-chain task response confirmation. Results are intended for use with validateAttestationDirect on NewtonPolicyClient (NewtonProverTaskManagerShared).
Signature:
Parameters: Returns:
  • result.evaluationResult (boolean) — Whether the intent was allowed by the policy
  • result.task (Task) — The full task object
  • result.taskResponse — The raw task response from the operator
  • result.blsSignature — The BLS aggregate signature
Some policy clients and identity-backed flows require intentSignature even though it is optional in the base request type. If you omit it or pass "0x", the gateway can fail before policy evaluation with Failed to encode intent signature: 0x reason: expected exactly 65 bytes.
Read the EIP-712 domain from the policy client whenever possible. Dashboard-deployed clients expose EIP-5267 eip712Domain(), which binds the signature to the correct name, version, chainId, and verifyingContract.
If you deploy a custom policy client that does not implement EIP-5267, hardcoded signing domains must match the contract’s EIP712(name, version) constructor values and the deployed policy client address.

submitIntentAndSubscribe

Submits a task via newt_sendTask and opens a WebSocket connection to receive the evaluation result. Results are intended for use with validateAttestation on NewtonProverTaskManager (the on-chain task verification path).
Signature:
Parameters: Returns:
  • result.message (string) — Status message from the gateway
  • result.subscription_topic (string) — WebSocket topic to subscribe to for task updates
  • result.task_id (Hex) — 32-byte task identifier
  • result.timestamp (number) — Task creation timestamp
  • ws (WebSocket) — Active WebSocket connection subscribed to the task topic
SubmitIntentResult type:
Use submitIntentAndSubscribe when you need on-chain task verification via NewtonProverTaskManager.validateAttestation. Use evaluateIntentDirect for the simpler direct validation path via PolicyClient.validateAttestationDirect.

simulateTask

Simulates task evaluation (newt_simulateTask). Forwards the task to an operator and returns an allow/deny result without executing on-chain. See the RPC API Reference for the underlying JSON-RPC method.
Signature:

simulatePolicy

Simulates full Rego policy evaluation (newt_simulatePolicy). Tests a policy with a sample intent and policy data. May require ownership if PolicyData uses stored secrets.
Signature:

simulatePolicyData

Simulates PolicyData WASM execution (newt_simulatePolicyData) with caller-provided secrets. No ownership verification is required.
Signature:

simulatePolicyDataWithClient

Simulates PolicyData WASM execution (newt_simulatePolicyDataWithClient) using stored secrets for a policy client. Requires ownership of the policy client.
Signature:

initialize

Initializes a Newton Policy contract with the given configuration. This is a one-time setup call. The contract requires keccak256 of the Rego policy bytes as _policyCodeHash so the on-chain hash matches the policy referenced by policyCid. Provide it one of two ways:
  • policyCodeHash — pre-computed hex hash (from policy_cids.json or another out-of-band source). Takes precedence when both are set.
  • policyBytes — the raw Rego policy bytes; the SDK computes keccak256 for you. Useful when fetching from IPFS via policyCid, reading a local file, or any other transport.
Signature:
Parameters: Returns: `0x${string}` — The transaction hash.

renounceOwnership

Renounces ownership of the policy contract. After calling this, no one will be able to perform owner-restricted actions.
This action is irreversible. Once ownership is renounced, administrative operations on the policy contract can never be performed again.
Signature:

transferOwnership

Transfers ownership of the policy contract to a new address.
Signature:

Identity Methods

These methods interact with the Newton Identity Provider for verified credential flows. They open a popup window for user interaction.

connectIdentityWithNewton

Connects the user’s identity with Newton via the identity provider popup.
Signature:

registerUserData

Registers KYC user data through the identity provider popup.
Signature:

linkApp

Links an application to the user’s Newton identity.
Signature:

unlinkApp

Unlinks an application from the user’s Newton identity.
Signature:

Privacy Methods

These methods are available on the wallet client for privacy-preserving policy evaluation using client-side HPKE encryption. They are also exported as standalone functions from the package.

getPrivacyPublicKey

Fetches the Newton Gateway’s X25519 HPKE public key for encrypting data.
Signature:
Returns:
  • public_key (string) — The gateway’s X25519 public key (hex-encoded)
  • key_type (string) — Key type identifier
  • encryption_suite (string) — HPKE suite identifier

createSecureEnvelope

Creates an HPKE-encrypted envelope from plaintext. Runs entirely offline with zero network calls.
Signature:
Parameters:

getSecretsPublicKey

Fetches the Newton Gateway’s X25519 HPKE public key for encrypting WASM secrets. In threshold DKG mode, this returns a different key than getPrivacyPublicKey.
Signature:
Returns:
  • public_key (string) — The gateway’s X25519 public key (hex-encoded)
  • key_type (string) — Key type identifier
  • encryption_suite (string) — HPKE suite identifier

uploadIdentityEncrypted

Uploads HPKE-encrypted identity data to the Newton Gateway. The caller must provide a pre-built SecureEnvelope (via createSecureEnvelope) and an EIP-712 signature of the envelope JSON from the identity owner. The gateway stores the envelope and returns a data_ref_id + gateway signature for the on-chain registerIdentityData call.
Signature:
Returns:
  • data_ref_id (string) — Content-hash data reference ID: keccak256(envelope_json_bytes)
  • gateway_signature (string) — Gateway EIP-712 signature for registerIdentityData on-chain call
  • deadline (number) — Signature expiration (unix timestamp)

getIdentityEncrypted

Fetches encrypted identity data by its content-hash reference ID. Used to resolve a data_ref_id (stored on-chain in IdentityRegistry) back to the encrypted data blob (stored off-chain in the gateway).
Signature:
Returns:
  • envelope (string) — The HPKE-encrypted identity data as a SecureEnvelope JSON string
  • identity_domain (string) — The identity domain this data was registered under
  • identity_owner (string) — The identity owner address

generateSigningKeyPair

Generates a random Ed25519 key pair for privacy authorization signatures.
Signature:
This is a synchronous method. Keys are generated locally and never sent to any server.

storeEncryptedSecrets

Encrypts plaintext secrets client-side with HPKE and uploads the envelope to the gateway for a PolicyClient’s PolicyData oracle. The gateway’s X25519 public key is fetched automatically if not provided.
Signature:

signPrivacyAuthorization

Computes dual Ed25519 signatures (user + app) for privacy-enabled task creation. Runs entirely offline.
Signature:
This is a synchronous method. Signatures are computed locally.

Webhook Methods

registerWebhook

Registers a webhook URL to receive task failure notifications. The gateway sends HMAC-SHA256 signed payloads to the registered URL when tasks fail.
Signature:
Parameters:

unregisterWebhook

Removes the registered webhook for the current API key.
Signature:

Identity Methods

These methods handle identity data registration and identity-to-PolicyClient linking via direct contract calls to the IdentityRegistry. They are also exported as standalone functions from the package.

registerIdentityData

Register an identity data reference on-chain. The identity owner (caller) submits a data_ref_id obtained from the gateway’s newt_uploadIdentityEncrypted RPC, along with the gateway’s co-signature and deadline.
Signature:
The contract verifies the gateway signature against REGISTER_IDENTITY_TYPEHASH and checks that the signer is a registered task generator via isTaskGenerator(). Overwrites are allowed — users can update their identity data reference by calling this again.

linkIdentityAsSignerAndUser

Link identity data when the caller is both the identity owner and the client user. The simplest linking flow — no counterparty signatures needed.
Signature:
Parameters: Returns: Transaction hash (Hex).

linkIdentityAsSigner

Link identity data as the identity owner (signer). Requires a counterparty EIP-712 signature from the client user.
Signature:
Parameters: Returns: Transaction hash (Hex).

linkIdentityAsUser

Link identity data as the client user. Requires a counterparty EIP-712 signature from the identity owner.
Signature:
Parameters: Returns: Transaction hash (Hex).

linkIdentity

Link identity data as a 3rd party with EIP-712 signatures from both the identity owner and the client user. Signature:
Parameters: Returns: Transaction hash (Hex).

unlinkIdentityAsSigner

Unlink identity data as the identity owner (signer). Only the identity owner who created the link can call this.
Signature:
Parameters: Returns: Transaction hash (Hex).

unlinkIdentityAsUser

Unlink identity data as the client user. Allows users to revoke links to their own account.
Signature:
Parameters: Returns: Transaction hash (Hex).

Public Client Methods (Read)

These methods are available after extending a PublicClient with newtonPublicClientActions.

Task Methods

waitForTaskResponded

Polls the on-chain TaskManager contract for a TaskResponded event for the given task ID.
Signature:
Parameters:

getTaskStatus

Queries the current status of a task from the on-chain contracts.
Signature:

getTaskResponseHash

Retrieves the response hash for a given task from the on-chain contract.
Signature:

Policy Methods

getPolicyId

Returns the policy ID associated with a given client address.
Signature:

getPolicyConfig

Returns the full policy configuration for a given policy ID, including parameters and expiration settings.
Signature:

getPolicyCid

Returns the content identifier (CID) of the policy WASM stored in the contract.
Signature:

getSchemaCid

Returns the content identifier (CID) of the policy schema.
Signature:

getMetadataCid

Returns the content identifier (CID) of the policy metadata.
Signature:

getEntrypoint

Returns the policy entrypoint string (e.g., "newton/policy/allow").
Signature:

getPolicyData

Returns the array of PolicyData contract addresses associated with the policy.
Signature:

isPolicyVerified

Returns whether the policy contract has been verified.
Signature:

precomputePolicyId

Synchronously computes a policy ID from its constituent parts without making an on-chain call.
Signature:
This is a synchronous method. It does not make any network or contract calls.

Additional Policy Contract Readers

The following methods read individual fields from the policy contract. They all require a policyContractAddress to have been set during initialization (or passed via overrides).

Privacy Methods

Client-side HPKE encryption for privacy-preserving policy evaluation. These methods are available as wallet client actions and as standalone exports.
The privacy module uses X25519 KEM + HKDF-SHA256 + ChaCha20-Poly1305 (RFC 9180, Base mode) and is compatible with the Rust gateway implementation.

createSecureEnvelope

Encrypt plaintext into a SecureEnvelope using HPKE. This is a pure offline function — zero network calls. The ephemeral HPKE key is generated internally and zeroed after use. Standalone signature:
Wallet client signature:
Parameters: Returns: SecureEnvelopeResult containing the encrypted envelope, Ed25519 signature, and sender public key.
The caller is responsible for zeroing the signingKey buffer when done. The function copies the key internally and zeroes the copy after signing, but the original buffer remains in the caller’s control.

getPrivacyPublicKey

Fetch the gateway’s X25519 HPKE public key. Call this once and cache the result — the key only changes on gateway restart or key rotation. Standalone signature:
Wallet client signature:
Returns:

getSecretsPublicKey

Fetch the gateway’s X25519 HPKE public key for WASM secrets encryption. In threshold DKG mode, this returns a different key than getPrivacyPublicKey. Use this key when encrypting secrets via storeEncryptedSecrets. Standalone signature:
Wallet client signature:
Returns:

uploadIdentityEncrypted

Upload HPKE-encrypted identity data to the gateway. The caller must provide a pre-built SecureEnvelope (via createSecureEnvelope) and an EIP-712 signature of the envelope JSON from the identity owner. The gateway stores the envelope and returns a data_ref_id + gateway signature for the on-chain registerIdentityData call. Standalone signature:
Wallet client signature:
Parameters: Returns:

getIdentityEncrypted

Fetch encrypted identity data by its content-hash reference ID. Used to resolve a data_ref_id (stored on-chain in IdentityRegistry) back to the encrypted data blob (stored off-chain in the gateway). Standalone signature:
Wallet client signature:
Parameters: Returns:

uploadConfidentialData

Encrypt confidential data (blacklists, allowlists, sanctions lists, etc.) client-side with HPKE and upload the envelope to the gateway. The gateway stores it and returns a content-hash data_ref_id. The provider then calls ConfidentialDataRegistry.publishData(domain, dataRefId) on-chain. The gateway validates provider registration via on-chain lookup — no Ed25519 signing key required. Standalone signature:
Wallet client signature:
Parameters: Returns:

getConfidentialData

Retrieve an HPKE-encrypted confidential data envelope by its data reference ID. The caller is responsible for decryption using their HPKE private key. Standalone signature:
Wallet client signature:
Parameters: Returns:

Identity Methods

EIP-712 signed identity data submission to the on-chain IdentityRegistry. These methods are available as wallet client actions and as standalone exports.
The identity module uses a single EncryptedIdentityData { string data } EIP-712 struct across all identity domains. The identity_domain field (bytes32 hash of the domain name) tells the gateway how to interpret the encrypted blob.

identityDomainHash

Compute the bytes32 identity domain hash from a human-readable domain name. Matches the Rust convention: keccak256(toBytes(domainName)). Signature:
Example:

linkIdentityAsSignerAndUser

Link identity data when the caller is both the identity owner and the client user. Calls the IdentityRegistry contract directly via writeContract. Standalone signature:
Parameters: Returns: Transaction hash (Hex).

linkIdentityAsSigner

Link identity data as the identity owner (signer). Requires a counterparty EIP-712 signature from the client user. Standalone signature:
Parameters: Returns: Transaction hash (Hex).

linkIdentityAsUser

Link identity data as the client user. Requires a counterparty EIP-712 signature from the identity owner. Standalone signature:
Parameters: Returns: Transaction hash (Hex).

linkIdentity

Link identity data as a 3rd party with EIP-712 signatures from both the identity owner and the client user. Standalone signature:
Parameters: Returns: Transaction hash (Hex).

unlinkIdentityAsSigner

Unlink identity data as the identity owner (signer). Only the identity owner who created the link can call this. Standalone signature:
Parameters: Returns: Transaction hash (Hex).

unlinkIdentityAsUser

Unlink identity data as the client user. Allows users to revoke links to their own account. Standalone signature:
Parameters: Returns: Transaction hash (Hex).

Types & Interfaces

Intent Types


Task Types


Simulation Types


Policy Types


Gateway Types


JSON-RPC Types


Builder Types


Privacy Types


Webhook Types

Identity Types


Error Handling

The SDK provides structured error classes with typed error codes for precise error handling.

SDKError

Thrown when an SDK-level error occurs (e.g., missing API key, invalid arguments).

MagicRPCError

Thrown when the Newton Gateway returns a JSON-RPC error.

SDKErrorCode

RPCErrorCode

SDKWarningCode

SDKError, MagicRPCError, and the error code enums are currently internal types. They are not exported from the package’s public API. You can catch errors generically using instanceof Error and inspect the message property.

Subpath Exports

The SDK provides multiple entry points for tree-shaking and targeted imports.
Use subpath exports to minimize bundle size when you only need a subset of SDK functionality.