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
- Node.js >= 20
- Package manager: pnpm >= 9 (recommended)
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 viemPublicClient with Newton Protocol read methods.
newtonWalletClientActions
Extends a viemWalletClient with Newton Protocol write methods.
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 aWalletClient 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 aPendingTaskBuilder that can be used to await the task response.
Returns: An object containing:
result.taskId(Hex) — The unique task identifierresult.txHash(Hex) — The transaction hashwaitForTaskResponded({ 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 withvalidateAttestationDirect on NewtonPolicyClient (NewtonProverTaskManagerShared).
Returns:
result.evaluationResult(boolean) — Whether the intent was allowed by the policyresult.task(Task) — The full task objectresult.taskResponse— The raw task response from the operatorresult.blsSignature— The BLS aggregate signature
eip712Domain(), which binds the signature to the correct name, version, chainId, and verifyingContract.
EIP712(name, version) constructor values and the deployed policy client address.
submitIntentAndSubscribe
Submits a task vianewt_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).
Returns:
result.message(string) — Status message from the gatewayresult.subscription_topic(string) — WebSocket topic to subscribe to for task updatesresult.task_id(Hex) — 32-byte task identifierresult.timestamp(number) — Task creation timestampws(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.
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.
simulatePolicyData
Simulates PolicyData WASM execution (newt_simulatePolicyData) with caller-provided secrets. No ownership verification is required.
simulatePolicyDataWithClient
Simulates PolicyData WASM execution (newt_simulatePolicyDataWithClient) using stored secrets for a policy client. Requires ownership of the policy client.
initialize
Initializes a Newton Policy contract with the given configuration. This is a one-time setup call. The contract requireskeccak256 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 (frompolicy_cids.jsonor another out-of-band source). Takes precedence when both are set.policyBytes— the raw Rego policy bytes; the SDK computeskeccak256for you. Useful when fetching from IPFS viapolicyCid, reading a local file, or any other transport.
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.
transferOwnership
Transfers ownership of the policy contract to a new address.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.registerUserData
Registers KYC user data through the identity provider popup.linkApp
Links an application to the user’s Newton identity.unlinkApp
Unlinks an application from the user’s Newton identity.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.public_key(string) — The gateway’s X25519 public key (hex-encoded)key_type(string) — Key type identifierencryption_suite(string) — HPKE suite identifier
createSecureEnvelope
Creates an HPKE-encrypted envelope from plaintext. Runs entirely offline with zero network calls.getSecretsPublicKey
Fetches the Newton Gateway’s X25519 HPKE public key for encrypting WASM secrets. In threshold DKG mode, this returns a different key thangetPrivacyPublicKey.
public_key(string) — The gateway’s X25519 public key (hex-encoded)key_type(string) — Key type identifierencryption_suite(string) — HPKE suite identifier
uploadIdentityEncrypted
Uploads HPKE-encrypted identity data to the Newton Gateway. The caller must provide a pre-built SecureEnvelope (viacreateSecureEnvelope) 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.
data_ref_id(string) — Content-hash data reference ID:keccak256(envelope_json_bytes)gateway_signature(string) — Gateway EIP-712 signature forregisterIdentityDataon-chain calldeadline(number) — Signature expiration (unix timestamp)
getIdentityEncrypted
Fetches encrypted identity data by its content-hash reference ID. Used to resolve adata_ref_id (stored on-chain in IdentityRegistry) back to the encrypted data blob (stored off-chain in the gateway).
envelope(string) — The HPKE-encrypted identity data as a SecureEnvelope JSON stringidentity_domain(string) — The identity domain this data was registered underidentity_owner(string) — The identity owner address
generateSigningKeyPair
Generates a random Ed25519 key pair for privacy authorization signatures.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.signPrivacyAuthorization
Computes dual Ed25519 signatures (user + app) for privacy-enabled task creation. Runs entirely offline.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.unregisterWebhook
Removes the registered webhook for the current API key.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 adata_ref_id obtained from the gateway’s newt_uploadIdentityEncrypted RPC, along with the gateway’s co-signature and deadline.
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.
Returns: Transaction hash (
Hex).
linkIdentityAsSigner
Link identity data as the identity owner (signer). Requires a counterparty EIP-712 signature from the client user.
Returns: Transaction hash (
Hex).
linkIdentityAsUser
Link identity data as the client user. Requires a counterparty EIP-712 signature from the identity owner.
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:
Returns: Transaction hash (
Hex).
unlinkIdentityAsSigner
Unlink identity data as the identity owner (signer). Only the identity owner who created the link can call this.
Returns: Transaction hash (
Hex).
unlinkIdentityAsUser
Unlink identity data as the client user. Allows users to revoke links to their own account.
Returns: Transaction hash (
Hex).
Public Client Methods (Read)
These methods are available after extending aPublicClient with newtonPublicClientActions.
Task Methods
waitForTaskResponded
Polls the on-chainTaskManager contract for a TaskResponded event for the given task ID.
getTaskStatus
Queries the current status of a task from the on-chain contracts.getTaskResponseHash
Retrieves the response hash for a given task from the on-chain contract.Policy Methods
getPolicyId
Returns the policy ID associated with a given client address.getPolicyConfig
Returns the full policy configuration for a given policy ID, including parameters and expiration settings.getPolicyCid
Returns the content identifier (CID) of the policy WASM stored in the contract.getSchemaCid
Returns the content identifier (CID) of the policy schema.getMetadataCid
Returns the content identifier (CID) of the policy metadata.getEntrypoint
Returns the policy entrypoint string (e.g.,"newton/policy/allow").
getPolicyData
Returns the array of PolicyData contract addresses associated with the policy.isPolicyVerified
Returns whether the policy contract has been verified.precomputePolicyId
Synchronously computes a policy ID from its constituent parts without making an on-chain call.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 apolicyContractAddress 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:
Returns:
SecureEnvelopeResult containing the encrypted envelope, Ed25519 signature, and sender public key.
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:
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:
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:
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:
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:
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:
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:
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:
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:
Returns: Transaction hash (
Hex).
linkIdentityAsUser
Link identity data as the client user. Requires a counterparty EIP-712 signature from the identity owner.
Standalone signature:
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:
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:
Returns: Transaction hash (
Hex).
unlinkIdentityAsUser
Unlink identity data as the client user. Allows users to revoke links to their own account.
Standalone signature:
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.
Related Resources
- Integration Guide — Step-by-step guide to building with the Newton Protocol SDK
- RPC API Reference — Underlying JSON-RPC methods called by the SDK