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 @magicnewton/newton-protocol-sdk package (v0.3.15).
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

npm install @magicnewton/newton-protocol-sdk
Requirements:
  • Node.js >= 20
  • Package manager: pnpm >= 9 (recommended)
Dependencies:
PackageVersionPurpose
viem^2.35.1Ethereum client library
jose^6.0.13JWT / cryptographic operations
eventemitter3^4.0.4Event handling

Overview

The SDK is organized into two main client extensions:
ExtensionPurposeClient Type
newtonPublicClientActionsRead-only operations (query tasks, policy state)PublicClient
newtonWalletClientActionsWrite operations (submit evaluations, manage policies)WalletClient
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) and Base Sepolia (chain ID 84532). Pass the corresponding chain object from viem/chains when constructing your clients.

newtonPublicClientActions

Extends a viem PublicClient with Newton Protocol read methods.
import { createPublicClient, http } from 'viem';
import { sepolia, baseSepolia } from 'viem/chains';
import { newtonPublicClientActions } from '@magicnewton/newton-protocol-sdk';

const publicClient = createPublicClient({
  chain: sepolia,        // or baseSepolia for Base Sepolia
  transport: http('<RPC_URL>'),
}).extend(
  newtonPublicClientActions({
    policyContractAddress: '0x...', // optional
  })
);
Signature:
function newtonPublicClientActions(
  options?: {
    policyContractAddress?: Address;
  },
  overrides?: SdkOverrides
): (publicClient: PublicClient) => NewtonPublicClientMethods;
Parameters:
ParameterTypeRequiredDescription
options.policyContractAddressAddressNoScopes all policy read calls to this contract address
overridesSdkOverridesNoOverride default SDK configuration

newtonWalletClientActions

Extends a viem WalletClient with Newton Protocol write methods.
import { createWalletClient, http } from 'viem';
import { sepolia, baseSepolia } from 'viem/chains';
import { newtonWalletClientActions } from '@magicnewton/newton-protocol-sdk';

const walletClient = createWalletClient({
  chain: sepolia,        // or baseSepolia for Base Sepolia
  transport: http('<RPC_URL>'),
}).extend(
  newtonWalletClientActions({
    apiKey: '<YOUR_API_KEY>',
    policyContractAddress: '0x...', // optional
  })
);
Signature:
function newtonWalletClientActions(
  config: {
    apiKey: string;
    policyContractAddress?: Address;
  },
  overrides?: SdkOverrides
): (walletClient: WalletClient) => NewtonWalletClientMethods;
Parameters:
ParameterTypeRequiredDescription
config.apiKeystringYesNewton Protocol API key for gateway authentication
config.policyContractAddressAddressNoDefault policy contract address for write operations
overridesSdkOverridesNoOverride default SDK configuration
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.
interface SdkOverrides {
  gatewayApiUrl?: string;
  taskManagerAddress?: Address;
  attestationValidatorAddress?: Address;
  newtonIdpUrl?: string;
}
FieldTypeDescription
gatewayApiUrlstringCustom Newton Gateway API URL
taskManagerAddressAddressCustom TaskManager contract address
attestationValidatorAddressAddressCustom AttestationValidator contract address
newtonIdpUrlstringCustom Newton identity provider URL

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.
const { result, waitForTaskResponded } = await walletClient.submitEvaluationRequest({
  policyClient: '0x...',
  intent: {
    from: '0x...',
    to: '0x...',
    value: '0x0',
    data: '0x...',
    chainId: '0xaa36a7', // Ethereum Sepolia (11155111)
    functionSignature: '0x...',
  },
  timeout: 60000,
});

console.log(result.taskId);  // Hex
console.log(result.txHash);  // Hex

// Optionally wait for the on-chain response
const response = await waitForTaskResponded({ timeoutMs: 120000 });
Signature:
submitEvaluationRequest(
  args: SubmitEvaluationRequestParams
): Promise<{ result: { taskId: Hex; txHash: Hex } } & PendingTaskBuilder>
Parameters:
ParameterTypeRequiredDescription
policyClientAddressYesThe policy client contract address
intentIntentFromParamsYesThe intent to evaluate
timeoutnumberNoRequest timeout in milliseconds
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

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).
const { result } = await walletClient.evaluateIntentDirect({
  policyClient: '0x...',
  intent: {
    from: '0x...',
    to: '0x...',
    value: '0x0',
    data: '0x...',
    chainId: 11155111, // Ethereum Sepolia; use 84532 for Base Sepolia
    functionSignature: '0x...',
  },
  timeout: 30000,
});

console.log(result.evaluationResult); // boolean
console.log(result.task);             // Task object
console.log(result.taskResponse);     // Raw task response
console.log(result.blsSignature);     // BLS signature data
Signature:
evaluateIntentDirect(
  args: SubmitEvaluationRequestParams
): Promise<{
  result: {
    evaluationResult: boolean;
    task: Task;
    taskResponse: any;
    blsSignature: any;
  };
}>
Parameters:
ParameterTypeRequiredDescription
policyClientAddressYesThe policy client contract address
intentIntentFromParamsYesThe intent to evaluate. chainId must be 11155111 (Ethereum Sepolia) or 84532 (Base Sepolia).
timeoutnumberNoRequest timeout in milliseconds
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

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).
const { result, ws } = await walletClient.submitIntentAndSubscribe({
  policyClient: '0x...',
  intent: {
    from: '0x...',
    to: '0x...',
    value: '0x0',
    data: '0x...',
    chainId: 11155111,
    functionSignature: '0x...',
  },
  timeout: 30,
});

console.log(result.task_id);             // Hex task identifier
console.log(result.subscription_topic);  // WebSocket topic

// Listen for the task response
ws.onmessage = (event) => {
  const taskResponse = JSON.parse(event.data);
  console.log(taskResponse);
};
Signature:
submitIntentAndSubscribe(
  args: SubmitEvaluationRequestParams
): Promise<{
  result: SubmitIntentResult;
  ws: WebSocket;
}>
Parameters:
ParameterTypeRequiredDescription
policyClientAddressYesThe policy client contract address
intentIntentFromParamsYesThe intent to evaluate. chainId must be 11155111 (Ethereum Sepolia) or 84532 (Base Sepolia).
timeoutnumberNoRequest timeout in seconds
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:
interface SubmitIntentResult {
  message: string;
  subscription_topic: string;
  task_id: Hex;
  timestamp: number;
}
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.
const result = await walletClient.simulateTask({
  intent: {
    from: '0x...',
    to: '0x...',
    value: '0x0',
    data: '0x...',
    chainId: 11155111, // Ethereum Sepolia; use 84532 for Base Sepolia
    functionSignature: '0x...',
  },
  policyTaskData: {
    policyId: '0x...',
    policyAddress: '0x...',
    policy: '0x...',
    policyData: [
      {
        wasmArgs: '0x',
        data: '0x...',
        attestation: '0x...',
        policyDataAddress: '0x...',
        expireBlock: 999999,
      },
    ],
  },
});

console.log(result.success);
console.log(result.result?.allow);
console.log(result.result?.reason);
console.log(result.error);
Signature:
simulateTask(args: SimulateTaskParams): Promise<SimulateTaskResult>

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.
const result = await walletClient.simulatePolicy({
  policyClient: '0x...',
  policy: '<rego-policy-string>',
  intent: {
    from: '0x...',
    to: '0x...',
    value: '0x0',
    data: '0x...',
    chainId: 11155111, // Ethereum Sepolia; use 84532 for Base Sepolia
    functionSignature: '0x...',
  },
  policyData: [
    { policyDataAddress: '0x...' },
  ],
  policyParams: { max_amount: 1000 },
  entrypoint: 'newton/policy/allow',
});

console.log(result.success);
console.log(result.evaluation_result);
console.log(result.error);
Signature:
simulatePolicy(args: SimulatePolicyParams): Promise<SimulatePolicyResult>

simulatePolicyData

Simulates PolicyData WASM execution (newt_simulatePolicyData) with caller-provided secrets. No ownership verification is required.
const result = await walletClient.simulatePolicyData({
  policyDataAddress: '0x...',
  secrets: '<secrets-json-string>',
  wasmArgs: '0x...',
});

console.log(result.success);
console.log(result.policy_data?.specifier);
console.log(result.policy_data?.data);
Signature:
simulatePolicyData(
  args: SimulatePolicyDataParams
): Promise<SimulatePolicyDataResult>

simulatePolicyDataWithClient

Simulates PolicyData WASM execution (newt_simulatePolicyDataWithClient) using stored secrets for a policy client. Requires ownership of the policy client.
const result = await walletClient.simulatePolicyDataWithClient({
  policyDataAddress: '0x...',
  policyClient: '0x...',
  wasmArgs: '0x...',
});

console.log(result.success);
console.log(result.policy_data?.specifier);
Signature:
simulatePolicyDataWithClient(
  args: SimulatePolicyDataWithClientParams
): Promise<SimulatePolicyDataWithClientResult>

initialize

Initializes a Newton Policy contract with the given configuration. This is a one-time setup call.
const txHash = await walletClient.initialize({
  factory: '0x...',
  entrypoint: 'newton/policy/allow',
  policyCid: 'bafyrei...',
  schemaCid: 'bafyrei...',
  policyData: ['0x...', '0x...'],
  metadataCid: 'bafyrei...',
  owner: '0x...',
});
Signature:
initialize(args: {
  factory: Address;
  entrypoint: string;
  policyCid: string;
  schemaCid: string;
  policyData: Address[];
  metadataCid: string;
  owner: Address;
}): Promise<`0x${string}`>
Parameters:
ParameterTypeRequiredDescription
factoryAddressYesAddress of the deploying factory contract
entrypointstringYesPolicy entrypoint path (e.g., "newton/policy/allow")
policyCidstringYesContent identifier (CID) of the policy WASM
schemaCidstringYesContent identifier (CID) of the policy schema
policyDataAddress[]YesArray of PolicyData contract addresses
metadataCidstringYesContent identifier (CID) of the policy metadata
ownerAddressYesOwner address of the policy contract
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.
const txHash = await walletClient.renounceOwnership();
Signature:
renounceOwnership(): Promise<`0x${string}`>

transferOwnership

Transfers ownership of the policy contract to a new address.
const txHash = await walletClient.transferOwnership({
  newOwner: '0x...',
});
Signature:
transferOwnership(args: {
  newOwner: Address;
}): Promise<`0x${string}`>

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.
const result = await publicClient.waitForTaskResponded({
  taskId: '0x...',
  timeoutMs: 120000,
});

console.log(result.taskResponse.evaluationResult);
console.log(result.attestation.expiration);
Signature:
waitForTaskResponded(args: {
  taskId: TaskId;
  timeoutMs?: number;
  abortSignal?: AbortSignal;
}): Promise<TaskResponseResult>
Parameters:
ParameterTypeRequiredDescription
taskIdTaskId (Hex)YesThe task identifier to monitor
timeoutMsnumberNoMaximum wait time in milliseconds
abortSignalAbortSignalNoSignal to abort the polling

getTaskStatus

Queries the current status of a task from the on-chain contracts.
const status = await publicClient.getTaskStatus({ taskId: '0x...' });
// status: 'Created' | 'Responded' | 'AttestationSpent'
//       | 'AttestationExpired' | 'SuccessfullyChallenged'
Signature:
getTaskStatus(args: {
  taskId: TaskId;
}): Promise<TaskStatus>

getTaskResponseHash

Retrieves the response hash for a given task from the on-chain contract.
const hash = await publicClient.getTaskResponseHash({ taskId: '0x...' });
// hash: '0x...' | null
Signature:
getTaskResponseHash(args: {
  taskId: TaskId;
}): Promise<Hex | null>

Policy Methods

getPolicyId

Returns the policy ID associated with a given client address.
const policyId = await publicClient.getPolicyId({ client: '0x...' });
Signature:
getPolicyId(args: { client: Address }): Promise<`0x${string}`>

getPolicyConfig

Returns the full policy configuration for a given policy ID, including parameters and expiration settings.
const config = await publicClient.getPolicyConfig({ policyId: '0x...' });
console.log(config.policyParams);
console.log(config.policyParamsHex);
console.log(config.expireAfter);
Signature:
getPolicyConfig(args: {
  policyId: `0x${string}`;
}): Promise<{
  policyParams: string | object;
  policyParamsHex: `0x${string}`;
  expireAfter: number;
}>

getPolicyCid

Returns the content identifier (CID) of the policy WASM stored in the contract.
const cid = await publicClient.getPolicyCid();
Signature:
getPolicyCid(): Promise<string>

getSchemaCid

Returns the content identifier (CID) of the policy schema.
const cid = await publicClient.getSchemaCid();
Signature:
getSchemaCid(): Promise<string>

getMetadataCid

Returns the content identifier (CID) of the policy metadata.
const cid = await publicClient.getMetadataCid();
Signature:
getMetadataCid(): Promise<string>

getEntrypoint

Returns the policy entrypoint string (e.g., "newton/policy/allow").
const entrypoint = await publicClient.getEntrypoint();
Signature:
getEntrypoint(): Promise<string>

getPolicyData

Returns the array of PolicyData contract addresses associated with the policy.
const addresses = await publicClient.getPolicyData();
Signature:
getPolicyData(): Promise<Address[]>

isPolicyVerified

Returns whether the policy contract has been verified.
const verified = await publicClient.isPolicyVerified();
Signature:
isPolicyVerified(): Promise<boolean>

precomputePolicyId

Synchronously computes a policy ID from its constituent parts without making an on-chain call.
const policyId = publicClient.precomputePolicyId({
  policyContract: '0x...',
  policyData: ['0x...'],
  params: {
    admin: '0x...',
    allowed_actions: {},
    token_whitelist: {},
  },
  client: '0x...',
  policyUri: 'ipfs://...',
  schemaUri: 'ipfs://...',
  entrypoint: 'newton/policy/allow',
  expireAfter: 3600,
});
Signature:
precomputePolicyId(args: {
  policyContract: Address;
  policyData: Address[];
  params: Record<string, any>;
  client: Address;
  policyUri: string;
  schemaUri: string;
  entrypoint: string;
  expireAfter: number;
}): `0x${string}`
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).
MethodReturn TypeDescription
owner()Promise<Address>Returns the owner address of the policy contract
factory()Promise<Address>Returns the factory address that deployed the contract
entrypoint()Promise<string>Returns the policy entrypoint path
clientToPolicyId({ client })Promise<\0x$string`>`Maps a client address to its policy ID
policyData()Promise<Address[]>Returns the PolicyData contract addresses
policyCid()Promise<string>Returns the policy CID
schemaCid()Promise<string>Returns the schema CID
metadataCid()Promise<string>Returns the metadata CID
supportsInterface({ interfaceId })Promise<boolean>EIP-165 interface support check

Types & Interfaces

Intent Types


Task Types


Simulation Types


Policy Types


Gateway Types


JSON-RPC Types


Builder Types


Error Handling

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

SDKError

class SDKError extends Error {
  code: SDKErrorCode;
  details?: any;

  constructor(code: SDKErrorCode, message: string, details?: any);
}

MagicRPCError

class MagicRPCError extends Error {
  code: RPCErrorCode;
  data?: any;

  constructor(code: RPCErrorCode, message: string, data?: any);
}

SDKErrorCode

RPCErrorCode

SDKWarningCode

Example error handling:
import { SDKError, SDKErrorCode } from '@magicnewton/newton-protocol-sdk';

try {
  const { result } = await walletClient.submitEvaluationRequest({ /* ... */ });
} catch (error) {
  if (error instanceof SDKError) {
    switch (error.code) {
      case SDKErrorCode.TIMEOUT:
        console.error('Request timed out:', error.message);
        break;
      case SDKErrorCode.GATEWAY_ERROR:
        console.error('Gateway error:', error.message, error.details);
        break;
      default:
        console.error('SDK error:', error.code, error.message);
    }
  }
}

Utility Functions

The SDK exports several utility functions for common operations.

normalizeIntent

Normalizes an IntentFromParams into a NormalizedIntent with consistent field types.
import { normalizeIntent } from '@magicnewton/newton-protocol-sdk';

const normalized = normalizeIntent({
  from: '0x...',
  to: '0x...',
  value: '0x0',
  data: '0x...',
  chainId: '0xaa36a7',
  functionSignature: '0x...',
});

sanitizeIntentForRequest

Prepares an intent for gateway API requests by encoding fields as expected by the backend.
import { sanitizeIntentForRequest } from '@magicnewton/newton-protocol-sdk';

const sanitized = sanitizeIntentForRequest(intent);

removeHexPrefix

Strips the 0x prefix from a hex string.
import { removeHexPrefix } from '@magicnewton/newton-protocol-sdk';

const raw = removeHexPrefix('0xabcdef'); // 'abcdef'

decodeJWT

Decodes a JWT token and returns its payload.
import { decodeJWT } from '@magicnewton/newton-protocol-sdk';

const payload = decodeJWT(token);

fetchWithCache

A fetch wrapper with a built-in caching layer to avoid redundant network requests.
import { fetchWithCache } from '@magicnewton/newton-protocol-sdk';

const response = await fetchWithCache(url, options);

createJsonRpcRequestPayload

Constructs a well-formed JSON-RPC 2.0 request payload for Newton RPC methods.
import { createJsonRpcRequestPayload } from '@magicnewton/newton-protocol-sdk';

const payload = createJsonRpcRequestPayload('newt_simulateTask', [params]);

createPromiEvent / isPromiEvent

Creates and detects promise-event hybrids that are both Promise and EventEmitter.
import { createPromiEvent, isPromiEvent } from '@magicnewton/newton-protocol-sdk';

const promiEvent = createPromiEvent((resolve, reject) => {
  // async logic
});

promiEvent.on('taskCreated', (taskId) => { /* ... */ });
const result = await promiEvent;

convertLogToTaskResponse

Converts a raw on-chain event log into a typed TaskResponse object.
import { convertLogToTaskResponse } from '@magicnewton/newton-protocol-sdk';

const taskResponse = convertLogToTaskResponse(log);

Constants

The SDK exports pre-configured constants for network addresses and gateway endpoints.

GATEWAY_API_URLS

const GATEWAY_API_URLS: Record<string, string>;
Maps network identifiers to their Newton Gateway API URLs.

GATEWAY_METHODS

const GATEWAY_METHODS: Record<string, NewtonWalletPayloadMethod>;
Mapping of method names to their JSON-RPC method identifiers.

NEWTON_PROVER_TASK_MANAGER

const NEWTON_PROVER_TASK_MANAGER: Record<string, Address>;
Deployed NewtonProverTaskManager contract addresses per network.

ATTESTATION_VALIDATOR

const ATTESTATION_VALIDATOR: Record<string, Address>;
Deployed AttestationValidator contract addresses per network.

Contract ABIs

The SDK exports typed ABI arrays for direct use with viem contract interactions.
import {
  NewtonProverTaskManagerAbi,
  AttestationValidatorAbi,
  NewtonPolicyAbi,
} from '@magicnewton/newton-protocol-sdk';
ABIContractDescription
NewtonProverTaskManagerAbiNewtonProverTaskManagerTask creation, response, and challenge functions
AttestationValidatorAbiAttestationValidatorAttestation validation and status queries
NewtonPolicyAbiNewtonPolicyPolicy initialization, configuration, and ownership

Subpath Exports

The SDK provides multiple entry points for tree-shaking and targeted imports.
Import PathDescription
@magicnewton/newton-protocol-sdkFull SDK — all methods, types, utilities, and constants
@magicnewton/newton-protocol-sdk/viemviem client extensions (newtonPublicClientActions, newtonWalletClientActions)
@magicnewton/newton-protocol-sdk/typesType definitions and interfaces only
@magicnewton/newton-protocol-sdk/networksNetwork constants, contract addresses, and gateway URLs
Use subpath exports to minimize bundle size when you only need a subset of SDK functionality.