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
pnpm (recommended)
yarn
npm install @magicnewton/newton-protocol-sdk
Requirements:
Node.js >= 20
Package manager: pnpm >= 9 (recommended)
Dependencies:
Package Version Purpose viem^2.35.1 Ethereum client library jose^6.0.13 JWT / cryptographic operations eventemitter3^4.0.4 Event handling
Overview
The SDK is organized into two main client extensions:
Extension Purpose Client Type newtonPublicClientActionsRead-only operations (query tasks, policy state) PublicClientnewtonWalletClientActionsWrite 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:
Parameter Type Required Description options.policyContractAddressAddressNo Scopes all policy read calls to this contract address overridesSdkOverridesNo Override 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:
Parameter Type Required Description config.apiKeystringYes Newton Protocol API key for gateway authentication config.policyContractAddressAddressNo Default policy contract address for write operations overridesSdkOverridesNo Override 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 ;
}
Field Type Description 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:
Parameter Type Required Description policyClientAddressYes The policy client contract address intentIntentFromParamsYes The intent to evaluate timeoutnumberNo Request 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:
Parameter Type Required Description policyClientAddressYes The policy client contract address intentIntentFromParamsYes The intent to evaluate. chainId must be 11155111 (Ethereum Sepolia) or 84532 (Base Sepolia). timeoutnumberNo Request 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:
Parameter Type Required Description policyClientAddressYes The policy client contract address intentIntentFromParamsYes The intent to evaluate. chainId must be 11155111 (Ethereum Sepolia) or 84532 (Base Sepolia). timeoutnumberNo Request 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:
Parameter Type Required Description factoryAddressYes Address of the deploying factory contract entrypointstringYes Policy entrypoint path (e.g., "newton/policy/allow") policyCidstringYes Content identifier (CID) of the policy WASM schemaCidstringYes Content identifier (CID) of the policy schema policyDataAddress[]Yes Array of PolicyData contract addresses metadataCidstringYes Content identifier (CID) of the policy metadata ownerAddressYes Owner 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:
Parameter Type Required Description taskIdTaskId (Hex)Yes The task identifier to monitor timeoutMsnumberNo Maximum wait time in milliseconds abortSignalAbortSignalNo Signal 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 >
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).
Method Return Type Description 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
The intent shape accepted by SDK methods before normalization. interface IntentFromParams {
from : string ;
to : string ;
value : string ;
data : string ;
chainId : string | number ;
functionSignature : string ;
}
The intent after internal normalization, with all fields as consistent types. interface NormalizedIntent {
from : Address ;
to : Address ;
value : Hex ;
data : Hex ;
chainId : number ;
functionSignature : Hex ;
}
The intent with all fields encoded as hex strings for on-chain use. interface HexlifiedIntent {
from : Hex ;
to : Hex ;
value : Hex ;
data : Hex ;
chainId : Hex ;
functionSignature : Hex ;
}
Task Types
A hex-encoded unique identifier for a task.
type TaskStatus =
| 'Created'
| 'Responded'
| 'AttestationSpent'
| 'AttestationExpired'
| 'SuccessfullyChallenged' ;
Represents the lifecycle state of a task on-chain.
interface Task {
taskId : TaskId ;
intent : NormalizedIntent ;
policyId : Hex ;
taskCreatedBlock : number ;
// Additional operator-specific fields
}
The full task object returned by evaluation methods.
interface TaskResponse {
evaluationResult : boolean ;
referenceTaskId : TaskId ;
// Additional response metadata
}
The operator’s response to a task evaluation.
interface TaskResponseResult {
taskResponse : TaskResponse ;
attestation : {
expiration : number ;
// Additional attestation fields
};
}
The combined result returned by waitForTaskResponded.
Show SubmitEvaluationRequestParams
interface SubmitEvaluationRequestParams {
policyClient : Address ;
intent : IntentFromParams ;
timeout ?: number ;
}
Field Type Required Description policyClientAddressYes The policy client contract address intentIntentFromParamsYes The intent to evaluate timeoutnumberNo Request timeout in milliseconds
Simulation Types
Show SimulateTaskParams & SimulateTaskResult
interface SimulateTaskParams {
intent : IntentFromParams ;
policyTaskData : SimulateTaskPolicyTaskData ;
}
interface SimulateTaskPolicyTaskData {
policyId : Hex ;
policyAddress : Address ;
policy : Hex ;
policyData : SimulateTaskPolicyData [];
}
interface SimulateTaskPolicyData {
wasmArgs : Hex ;
data : Hex ;
attestation : Hex ;
policyDataAddress : Address ;
expireBlock : number ;
}
interface SimulateTaskResult {
success : boolean ;
result ?: {
allow : boolean ;
reason ?: string ;
};
error ?: string ;
}
Show SimulatePolicyParams & SimulatePolicyResult
interface SimulatePolicyParams {
policyClient : Address ;
policy : string ;
intent : IntentFromParams ;
policyData : Array <{ policyDataAddress : Address }>;
policyParams ?: Record < string , any >;
entrypoint ?: string ;
}
interface SimulatePolicyResult {
success : boolean ;
evaluation_result ?: SimulatePolicyEvaluationResult ;
error ?: string ;
}
interface SimulatePolicyEvaluationResult {
allow : boolean ;
reason ?: string ;
}
Show SimulatePolicyDataParams & SimulatePolicyDataResult
interface SimulatePolicyDataParams {
policyDataAddress : Address ;
secrets : string ;
wasmArgs : Hex ;
}
interface SimulatePolicyDataResult {
success : boolean ;
policy_data ?: {
specifier : string ;
data : string ;
};
error ?: string ;
}
Show SimulatePolicyDataWithClientParams & SimulatePolicyDataWithClientResult
interface SimulatePolicyDataWithClientParams {
policyDataAddress : Address ;
policyClient : Address ;
wasmArgs : Hex ;
}
interface SimulatePolicyDataWithClientResult {
success : boolean ;
policy_data ?: {
specifier : string ;
data : string ;
};
error ?: string ;
}
Policy Types
Show PolicyId, PolicyInfo, PolicyCodeInfo, PolicyDataInfo
type PolicyId = `0x ${ string } ` ;
interface PolicyInfo {
policyId : PolicyId ;
policyParams : string | object ;
policyParamsHex : `0x ${ string } ` ;
expireAfter : number ;
}
interface PolicyCodeInfo {
policyCid : string ;
schemaCid : string ;
metadataCid : string ;
entrypoint : string ;
}
interface PolicyDataInfo {
addresses : Address [];
}
Show PolicyParamsJson, SetPolicyInput, SetPolicyResult, PolicyDataInput
type PolicyParamsJson = Record < string , any >;
interface SetPolicyInput {
client : Address ;
policyUri : string ;
schemaUri : string ;
entrypoint : string ;
params : PolicyParamsJson ;
policyData : Address [];
expireAfter : number ;
}
interface SetPolicyResult {
txHash : `0x ${ string } ` ;
policyId : PolicyId ;
}
interface PolicyDataInput {
policyDataAddress : Address ;
}
Gateway Types
Show GatewayCreateTaskResult & AggregationResponse
interface GatewayCreateTaskResult {
taskId : Hex ;
txHash : Hex ;
}
interface AggregationResponse {
evaluationResult : boolean ;
task : Task ;
taskResponse : any ;
blsSignature : any ;
}
JSON-RPC Types
Show JsonRpcRequestPayload, JsonRpcResponsePayload, JsonRpcError, NewtonWalletPayloadMethod
interface JsonRpcRequestPayload {
jsonrpc : '2.0' ;
id : number | string ;
method : NewtonWalletPayloadMethod ;
params : any [];
}
interface JsonRpcResponsePayload < T = any > {
jsonrpc : '2.0' ;
id : number | string ;
result ?: T ;
error ?: JsonRpcError ;
}
interface JsonRpcError {
code : number ;
message : string ;
data ?: any ;
}
type NewtonWalletPayloadMethod =
| 'newt_simulateTask'
| 'newt_simulatePolicy'
| 'newt_simulatePolicyData'
| 'newt_simulatePolicyDataWithClient'
| 'newt_createTask'
| 'newt_evaluateIntent'
| 'newt_submitIntent' ;
Builder Types
interface PendingTaskBuilder {
waitForTaskResponded ( args ?: {
timeoutMs ?: number ;
abortSignal ?: AbortSignal ;
}) : Promise < TaskResponseResult >;
}
Returned by submitEvaluationRequest. Call waitForTaskResponded() to poll for the on-chain attestation.
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
Show SDKErrorCode enum values
enum SDKErrorCode {
INVALID_PARAMS = 'INVALID_PARAMS' ,
TIMEOUT = 'TIMEOUT' ,
NETWORK_ERROR = 'NETWORK_ERROR' ,
CONTRACT_ERROR = 'CONTRACT_ERROR' ,
GATEWAY_ERROR = 'GATEWAY_ERROR' ,
UNKNOWN = 'UNKNOWN' ,
}
RPCErrorCode
Show RPCErrorCode enum values
enum RPCErrorCode {
PARSE_ERROR = - 32700 ,
INVALID_REQUEST = - 32600 ,
METHOD_NOT_FOUND = - 32601 ,
INVALID_PARAMS = - 32602 ,
INTERNAL_ERROR = - 32603 ,
SERVER_ERROR = - 32000 ,
}
SDKWarningCode
Show SDKWarningCode enum values
enum SDKWarningCode {
DEPRECATED = 'DEPRECATED' ,
FALLBACK = 'FALLBACK' ,
}
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' ;
ABI Contract Description NewtonProverTaskManagerAbiNewtonProverTaskManager Task creation, response, and challenge functions AttestationValidatorAbiAttestationValidator Attestation validation and status queries NewtonPolicyAbiNewtonPolicy Policy initialization, configuration, and ownership
Subpath Exports
The SDK provides multiple entry points for tree-shaking and targeted imports.
Import Path Description @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.