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.
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), Base Sepolia (chain ID 84532), and Ethereum Mainnet (chain ID 1). 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 ;
identityRegistry ?: Address ;
}
Field Type Description gatewayApiUrlstringCustom Newton Gateway API URL taskManagerAddressAddressCustom TaskManager contract address attestationValidatorAddressAddressCustom AttestationValidator contract address newtonIdpUrlstringCustom Newton identity provider URL identityRegistryAddressCustom IdentityRegistry contract address
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 : unknown ;
blsSignature : unknown ;
};
}>
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 } ` >
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.
await walletClient . connectIdentityWithNewton ({
appWalletAddress: '0x...' ,
appClientAddress: '0x...' ,
});
Signature:
connectIdentityWithNewton ( args : {
appWalletAddress: Address ;
appClientAddress : Address ;
}): Promise < unknown >
registerUserData
Registers KYC user data through the identity provider popup.
await walletClient . registerUserData ({
userData: {
status: 'approved' ,
selected_country_code: 'US' ,
address_subdivision: 'CA' ,
address_country_code: 'US' ,
birthdate: '1990-01-15' ,
expiration_date: '2030-01-15' ,
issue_date: '2020-01-15' ,
issuing_authority: 'US_DL' ,
},
appIdentityDomain: '0x...' ,
policyClient: '0xYourPolicyClientAddress' ,
});
Signature:
registerUserData ( args : {
userData: KycUserData ;
appIdentityDomain : Hex ;
policyClient : Address ;
}): Promise < unknown >
linkApp
Links an application to the user’s Newton identity.
await walletClient . linkApp ({
appWalletAddress: '0x...' ,
appClientAddress: '0x...' ,
appIdentityDomain: '0x...' ,
});
Signature:
linkApp ( args : {
appWalletAddress: Address ;
appClientAddress : Address ;
appIdentityDomain : Hex ;
}): Promise < unknown >
unlinkApp
Unlinks an application from the user’s Newton identity.
await walletClient . unlinkApp ({
appWalletAddress: '0x...' ,
appClientAddress: '0x...' ,
appIdentityDomain: '0x...' ,
});
Signature:
unlinkApp ( args : {
appWalletAddress: Address ;
appClientAddress : Address ;
appIdentityDomain : Hex ;
}): Promise < unknown >
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.
const { public_key , key_type , encryption_suite } = await walletClient . getPrivacyPublicKey ();
Signature:
getPrivacyPublicKey (): Promise < PrivacyPublicKeyResponse >
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.
const signingKeyPair = walletClient . generateSigningKeyPair ();
const { envelope , signature , senderPublicKey } = await walletClient . createSecureEnvelope (
{
plaintext: { secret: 'value' },
policyClient: '0x...' ,
chainId: 11155111 ,
recipientPublicKey: '<gateway-public-key>' ,
},
signingKeyPair . privateKey // Uint8Array from generateSigningKeyPair()
);
Signature:
createSecureEnvelope (
args : CreateSecureEnvelopeParams ,
signingKey : Uint8Array
): Promise < SecureEnvelopeResult >
Parameters:
Parameter Type Required Description args.plaintextUint8Array | string | Record<string, unknown>Yes Data to encrypt (objects are JSON-stringified) args.policyClientAddressYes PolicyClient address (bound via AAD) args.chainIdnumberYes Chain ID (bound via AAD) args.recipientPublicKeystringYes Gateway’s X25519 public key signingKeyUint8ArrayYes Ed25519 private key seed (32 bytes)
uploadEncryptedData
Encrypts data with HPKE and uploads it to the Newton Gateway in a single call.
const { success , data_ref_id } = await walletClient . uploadEncryptedData ({
senderAddress: '0x...' ,
policyClient: '0x...' ,
chainId: 11155111 ,
plaintext: { secret: 'value' },
signingKey: '<ed25519-private-key>' ,
});
Signature:
uploadEncryptedData (
args : UploadEncryptedDataParams
): Promise < UploadEncryptedDataResponse >
Returns:
success (boolean) — Whether the upload succeeded
data_ref_id (string) — Reference ID for the uploaded data (use in encryptedDataRefs)
generateSigningKeyPair
Generates a random Ed25519 key pair for privacy authorization signatures.
const { privateKey , publicKey } = walletClient . generateSigningKeyPair ();
// Both are 32-byte hex strings without 0x prefix
Signature:
generateSigningKeyPair (): Ed25519KeyPair
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.
const { success } = await walletClient . storeEncryptedSecrets ({
policyClient: '0x...' ,
policyDataAddress: '0x...' ,
plaintext: { API_KEY: 'sk-...' , ENDPOINT: 'https://api.example.com' },
chainId: 11155111 ,
});
Signature:
storeEncryptedSecrets (
args : StoreEncryptedSecretsParams
): Promise < StoreEncryptedSecretsResponse >
signPrivacyAuthorization
Computes dual Ed25519 signatures (user + app) for privacy-enabled task creation. Runs entirely offline.
const { userSignature , appSignature , userPublicKey , appPublicKey } =
walletClient . signPrivacyAuthorization ({
policyClient: '0x...' ,
intentHash: '0x...' ,
encryptedDataRefs: [ 'ref-id-1' , 'ref-id-2' ],
userSigningKey: '<user-ed25519-private-key>' ,
appSigningKey: '<app-ed25519-private-key>' ,
});
Signature:
signPrivacyAuthorization (
args : SignPrivacyAuthorizationParams
): PrivacyAuthorizationResult
This is a synchronous method. Signatures are computed locally.
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.
await walletClient . registerIdentityData ({
identityDomain: identityDomainHash ( 'kyc' ),
dataRefId: 'QmEncryptedDataRef...' ,
gatewaySignature: '0x...' , // from newt_uploadIdentityEncrypted response
deadline: 1700000000 n , // from newt_uploadIdentityEncrypted response
})
Signature:
registerIdentityData ( args : RegisterIdentityDataParams ): Promise < Hex >
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.
await walletClient . linkIdentityAsSignerAndUser ({
policyClient: '0xPolicyClientAddress' ,
identityDomains: [ identityDomainHash ( 'kyc' )],
});
Signature:
linkIdentityAsSignerAndUser ( args : LinkIdentityAsSignerAndUserParams ): Promise < Hex >
Parameters:
Parameter Type Description policyClientAddressPolicyClient contract address identityDomainsHex[]Array of domain hashes (use identityDomainHash())
Returns: Transaction hash (Hex).
linkIdentityAsSigner
Link identity data as the identity owner (signer). Requires a counterparty EIP-712 signature from the client user.
await walletClient . linkIdentityAsSigner ({
policyClient: '0xPolicyClientAddress' ,
identityDomains: [ identityDomainHash ( 'kyc' )],
clientUser: '0xClientUserAddress' ,
clientUserSignature: '0x...' ,
clientUserNonce: 0 n ,
clientUserDeadline: BigInt ( Math . floor ( Date . now () / 1000 ) + 3600 ),
});
Signature:
linkIdentityAsSigner ( args : LinkIdentityAsSignerParams ): Promise < Hex >
Parameters:
Parameter Type Description policyClientAddressPolicyClient contract address identityDomainsHex[]Array of domain hashes clientUserAddressThe client user’s address clientUserSignatureHexEIP-712 signature from the client user clientUserNoncebigintNonce for the client user’s signature clientUserDeadlinebigintDeadline timestamp for the signature
Returns: Transaction hash (Hex).
linkIdentityAsUser
Link identity data as the client user. Requires a counterparty EIP-712 signature from the identity owner.
await walletClient . linkIdentityAsUser ({
identityOwner: '0xIdentityOwnerAddress' ,
policyClient: '0xPolicyClientAddress' ,
identityDomains: [ identityDomainHash ( 'kyc' )],
identityOwnerSignature: '0x...' ,
identityOwnerNonce: 0 n ,
identityOwnerDeadline: BigInt ( Math . floor ( Date . now () / 1000 ) + 3600 ),
});
Signature:
linkIdentityAsUser ( args : LinkIdentityAsUserParams ): Promise < Hex >
Parameters:
Parameter Type Description identityOwnerAddressThe identity owner’s address policyClientAddressPolicyClient contract address identityDomainsHex[]Array of domain hashes identityOwnerSignatureHexEIP-712 signature from the identity owner identityOwnerNoncebigintNonce for the identity owner’s signature identityOwnerDeadlinebigintDeadline timestamp for the 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.
Signature:
linkIdentity ( args : LinkIdentityParams ): Promise < Hex >
Parameters:
Parameter Type Description identityOwnerAddressThe identity owner’s address clientUserAddressThe client user’s address policyClientAddressPolicyClient contract address identityDomainsHex[]Array of domain hashes identityOwnerSignatureHexEIP-712 signature from the identity owner identityOwnerNoncebigintNonce for the identity owner’s signature identityOwnerDeadlinebigintDeadline timestamp for the owner signature clientUserSignatureHexEIP-712 signature from the client user clientUserNoncebigintNonce for the client user’s signature clientUserDeadlinebigintDeadline timestamp for the 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.
await walletClient . unlinkIdentityAsSigner ({
clientUser: '0xClientUserAddress' ,
policyClient: '0xPolicyClientAddress' ,
identityDomains: [ identityDomainHash ( 'kyc' )],
});
Signature:
unlinkIdentityAsSigner ( args : UnlinkIdentityAsSignerParams ): Promise < Hex >
Parameters:
Parameter Type Description clientUserAddressThe client user whose link to remove policyClientAddressPolicyClient contract address identityDomainsHex[]Array of domain hashes to unlink
Returns: Transaction hash (Hex).
unlinkIdentityAsUser
Unlink identity data as the client user. Allows users to revoke links to their own account.
await walletClient . unlinkIdentityAsUser ({
policyClient: '0xPolicyClientAddress' ,
identityDomains: [ identityDomainHash ( 'kyc' )],
});
Signature:
unlinkIdentityAsUser ( args : UnlinkIdentityAsUserParams ): Promise < Hex >
Parameters:
Parameter Type Description policyClientAddressPolicyClient contract address identityDomainsHex[]Array of domain hashes to unlink
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.
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 ;
blockTimestamp ?: bigint ;
}): `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({ index })Promise<Address>Returns the PolicyData contract address at the given index 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
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:
createSecureEnvelope (
params : CreateSecureEnvelopeParams ,
signingKey : Uint8Array
): Promise < SecureEnvelopeResult >
Wallet client signature:
client . createSecureEnvelope ( params : CreateSecureEnvelopeParams , signingKey : Uint8Array ): Promise < SecureEnvelopeResult >
Parameters:
Parameter Type Description params.plaintextUint8Array | string | Record<string, unknown>Data to encrypt params.policyClientAddressPolicy client address this data is scoped to params.chainIdnumberChain ID for AAD context binding params.recipientPublicKeystringGateway’s X25519 public key (hex, no 0x prefix) signingKeyUint8ArrayEd25519 private key seed (32 bytes). Caller owns the buffer lifecycle.
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:
getPrivacyPublicKey (
chainId : number ,
apiKey : string ,
gatewayApiUrlOverride ?: string
): Promise < PrivacyPublicKeyResponse >
Wallet client signature:
client . getPrivacyPublicKey (): Promise < PrivacyPublicKeyResponse >
Returns:
Field Type Description public_keystringX25519 public key (hex, no 0x prefix) key_typestringAlways "x25519" encryption_suitestringEncryption suite identifier
uploadEncryptedData
Encrypt data and upload to the gateway in a single call. If recipientPublicKey is not provided, it is fetched from the gateway first.
Standalone signature:
uploadEncryptedData (
chainId : number ,
apiKey : string ,
params : UploadEncryptedDataParams ,
gatewayApiUrlOverride ?: string
): Promise < UploadEncryptedDataResponse >
Wallet client signature:
client . uploadEncryptedData ( params : UploadEncryptedDataParams ): Promise < UploadEncryptedDataResponse >
Parameters:
Parameter Type Description params.senderAddressAddressEVM address of the end user params.policyClientAddressPolicy client address params.chainIdnumberChain ID the policy client lives on params.plaintextUint8Array | string | Record<string, unknown>Data to encrypt and upload params.recipientPublicKeystring?Gateway’s X25519 key. If omitted, fetched via RPC. params.signingKeyUint8ArrayEd25519 private key seed (32 bytes) params.ttlnumber?Optional TTL in seconds
uploadSecureEnvelope
Upload a pre-built SecureEnvelope to the gateway. Use this when you have already created an envelope via createSecureEnvelope and want to control the upload separately — for example, offline-first apps that encrypt now and upload later, or batching multiple envelopes.
Standalone signature:
uploadSecureEnvelope (
chainId : number ,
apiKey : string ,
params : UploadSecureEnvelopeParams ,
gatewayApiUrlOverride ?: string
): Promise < UploadEncryptedDataResponse >
Wallet client signature:
client . uploadSecureEnvelope ( params : UploadSecureEnvelopeParams ): Promise < UploadEncryptedDataResponse >
Parameters:
Parameter Type Description params.senderAddressAddressEVM address of the end user params.envelopeResultSecureEnvelopeResultPre-built envelope from createSecureEnvelope params.ttlnumber?Optional TTL in seconds
Returns (both upload methods):
Field Type Description successbooleanWhether the upload succeeded data_ref_idstring | nullUUID of the stored data reference errorstring | nullError message if upload failed
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:
uploadConfidentialData (
chainId : number ,
apiKey : string ,
params : UploadConfidentialDataParams ,
gatewayApiUrlOverride ?: string
): Promise < UploadConfidentialDataResult >
Wallet client signature:
client . uploadConfidentialData ( params : UploadConfidentialDataParams ): Promise < UploadConfidentialDataResult >
Parameters:
Parameter Type Description params.providerstringProvider address (must be registered on-chain with ConfidentialDataRegistry) params.domainstringConfidential domain as 0x-prefixed bytes32 hex (e.g., keccak256("newton.privacy.blacklist")) params.plaintextUint8Array | string | Record<string, unknown>Data to encrypt and upload params.chainIdnumberChain ID for AAD context binding params.recipientPublicKeystring?Gateway’s X25519 key (hex, no 0x prefix). If omitted, fetched via RPC.
Returns:
Field Type Description data_ref_idstringContent-hash data reference ID
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:
getConfidentialData (
chainId : number ,
apiKey : string ,
dataRefId : string ,
gatewayApiUrlOverride ?: string
): Promise < GetConfidentialDataResult >
Wallet client signature:
client . getConfidentialData ( args : { dataRefId: string }): Promise < GetConfidentialDataResult >
Parameters:
Parameter Type Description dataRefIdstringContent-hash data reference ID returned from uploadConfidentialData
Returns:
Field Type Description envelopestringJSON-serialized HPKE SecureEnvelope domainstringConfidential domain as 0x-prefixed bytes32 hex providerstringProvider address
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:
identityDomainHash ( domainName : string ): Hex
Example:
import { identityDomainHash } from '@magicnewton/newton-protocol-sdk' ;
const kycDomain = identityDomainHash ( 'kyc' );
// Returns keccak256 of "kyc" as 0x-prefixed bytes32
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:
linkIdentityAsSignerAndUser (
walletClient : WalletClient ,
params : LinkIdentityAsSignerAndUserParams
): Promise < Hex >
Parameters:
Parameter Type Description policyClientAddressPolicyClient contract address identityDomainsHex[]Array of domain hashes (use identityDomainHash())
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:
linkIdentityAsSigner (
walletClient : WalletClient ,
params : LinkIdentityAsSignerParams
): Promise < Hex >
Parameters:
Parameter Type Description policyClientAddressPolicyClient contract address identityDomainsHex[]Array of domain hashes clientUserAddressThe client user’s address clientUserSignatureHexEIP-712 signature from the client user clientUserNoncebigintNonce for the client user’s signature clientUserDeadlinebigintDeadline timestamp for the 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:
linkIdentityAsUser (
walletClient : WalletClient ,
params : LinkIdentityAsUserParams
): Promise < Hex >
Parameters:
Parameter Type Description identityOwnerAddressThe identity owner’s address policyClientAddressPolicyClient contract address identityDomainsHex[]Array of domain hashes identityOwnerSignatureHexEIP-712 signature from the identity owner identityOwnerNoncebigintNonce for the identity owner’s signature identityOwnerDeadlinebigintDeadline timestamp for the 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:
linkIdentity (
walletClient : WalletClient ,
params : LinkIdentityParams
): Promise < Hex >
Parameters:
Parameter Type Description identityOwnerAddressThe identity owner’s address clientUserAddressThe client user’s address policyClientAddressPolicyClient contract address identityDomainsHex[]Array of domain hashes identityOwnerSignatureHexEIP-712 signature from the identity owner identityOwnerNoncebigintNonce for the identity owner’s signature identityOwnerDeadlinebigintDeadline timestamp for the owner signature clientUserSignatureHexEIP-712 signature from the client user clientUserNoncebigintNonce for the client user’s signature clientUserDeadlinebigintDeadline timestamp for the 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.
Standalone signature:
unlinkIdentityAsSigner (
walletClient : WalletClient ,
params : UnlinkIdentityAsSignerParams
): Promise < Hex >
Parameters:
Parameter Type Description clientUserAddressThe client user whose link to remove policyClientAddressPolicyClient contract address identityDomainsHex[]Array of domain hashes to unlink
Returns: Transaction hash (Hex).
unlinkIdentityAsUser
Unlink identity data as the client user. Allows users to revoke links to their own account.
Standalone signature:
unlinkIdentityAsUser (
walletClient : WalletClient ,
params : UnlinkIdentityAsUserParams
): Promise < Hex >
Parameters:
Parameter Type Description policyClientAddressPolicyClient contract address identityDomainsHex[]Array of domain hashes to unlink
Returns: Transaction hash (Hex).
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 : unknown ;
blsSignature : unknown ;
}
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 ;
}
enum NewtonWalletPayloadMethod {
ShowUI = 'newton_wallet_wallet' ,
Receive = 'newton_wallet_wallet_receive' ,
PersonalSign = 'personal_sign' ,
SendUserOperation = 'eth_sendUserOperation' ,
Connect = 'newton_wallet_user_connect' ,
Disconnect = 'newton_wallet_user_disconnect' ,
IsConnected = 'newton_wallet_user_is_connected' ,
GetConnectedProfile = 'newton_wallet_user_get_connected_profile' ,
}
Builder Types
interface PendingTaskBuilder {
waitForTaskResponded ( args ?: {
timeoutMs ?: number ;
abortSignal ?: AbortSignal ;
}) : Promise < TaskResponseResult >;
}
Returned by submitEvaluationRequest. Call waitForTaskResponded() to poll for the on-chain attestation.
Privacy Types
Show SecureEnvelope & CreateSecureEnvelopeParams
interface SecureEnvelope {
enc : string ;
ciphertext : string ;
policy_client : string ;
chain_id : number ;
recipient_pubkey : string ;
}
interface CreateSecureEnvelopeParams {
plaintext : Uint8Array | string | Record < string , unknown >;
policyClient : Address ;
chainId : number ;
recipientPublicKey : string ;
}
interface SecureEnvelopeResult {
envelope : SecureEnvelope ;
signature : string ;
senderPublicKey : string ;
}
interface Ed25519KeyPair {
privateKey : string ; // 32-byte hex, no 0x prefix
publicKey : string ; // 32-byte hex, no 0x prefix
}
Show UploadEncryptedDataParams & Response
interface UploadEncryptedDataParams {
senderAddress : Address ;
policyClient : Address ;
chainId : number ;
plaintext : Uint8Array | string | Record < string , unknown >;
recipientPublicKey ?: string ;
signingKey : string ;
ttl ?: number ;
}
interface UploadEncryptedDataResponse {
success : boolean ;
data_ref_id : string ;
error ?: string ;
}
Show StoreEncryptedSecretsParams & Response
interface StoreEncryptedSecretsParams {
policyClient : Address ;
policyDataAddress : Address ;
/** Plaintext secrets as a JSON object (e.g., { "API_KEY": "...", "ENDPOINT": "..." }) */
plaintext : Record < string , unknown >;
chainId : number ;
/** Gateway's X25519 public key (hex, no 0x prefix). Fetched automatically if omitted. */
recipientPublicKey ?: string ;
}
interface StoreEncryptedSecretsResponse {
success : boolean ;
schema ?: string ;
error ?: string ;
}
Show SignPrivacyAuthorizationParams & PrivacyAuthorizationResult
interface SignPrivacyAuthorizationParams {
policyClient : Address ;
intentHash : Hex ;
encryptedDataRefs : string [];
userSigningKey : string ;
appSigningKey : string ;
}
interface PrivacyAuthorizationResult {
userSignature : string ;
appSignature : string ;
userPublicKey : string ;
appPublicKey : string ;
}
Show PrivacyPublicKeyResponse
interface PrivacyPublicKeyResponse {
public_key : string ;
key_type : string ;
encryption_suite : string ;
}
Identity Types
Show LinkIdentityAsSignerAndUserParams
interface LinkIdentityAsSignerAndUserParams {
policyClient : Address ;
identityDomains : Hex [];
}
Show LinkIdentityAsSignerParams
interface LinkIdentityAsSignerParams {
policyClient : Address ;
identityDomains : Hex [];
clientUser : Address ;
clientUserSignature : Hex ;
clientUserNonce : bigint ;
clientUserDeadline : bigint ;
}
Show LinkIdentityAsUserParams
interface LinkIdentityAsUserParams {
identityOwner : Address ;
policyClient : Address ;
identityDomains : Hex [];
identityOwnerSignature : Hex ;
identityOwnerNonce : bigint ;
identityOwnerDeadline : bigint ;
}
interface LinkIdentityParams {
identityOwner : Address ;
clientUser : Address ;
policyClient : Address ;
identityDomains : Hex [];
identityOwnerSignature : Hex ;
identityOwnerNonce : bigint ;
identityOwnerDeadline : bigint ;
clientUserSignature : Hex ;
clientUserNonce : bigint ;
clientUserDeadline : bigint ;
}
Show UnlinkIdentityAsSignerParams
interface UnlinkIdentityAsSignerParams {
clientUser : Address ;
policyClient : Address ;
identityDomains : Hex [];
}
Show UnlinkIdentityAsUserParams
interface UnlinkIdentityAsUserParams {
policyClient : Address ;
identityDomains : Hex [];
}
Show RegisterIdentityDataParams
interface RegisterIdentityDataParams {
identityDomain : Hex ;
dataRefId : string ;
gatewaySignature : Hex ;
deadline : bigint ;
}
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).
class SDKError extends Error {
code : SDKErrorCode ;
rawMessage : string ;
constructor ( code : SDKErrorCode , rawMessage : string );
}
MagicRPCError
Thrown when the Newton Gateway returns a JSON-RPC error.
class MagicRPCError extends Error {
code : RPCErrorCode | number ;
rawMessage : string ;
data : unknown ;
constructor ( sourceError ?: JsonRpcError | null );
}
SDKErrorCode
Show SDKErrorCode enum values
enum SDKErrorCode {
MissingApiKey = 'MISSING_API_KEY' ,
PopupAlreadyExists = 'POPUP_ALREADY_EXISTS' ,
MalformedResponse = 'MALFORMED_RESPONSE' ,
InvalidArgument = 'INVALID_ARGUMENT' ,
ExtensionNotInitialized = 'EXTENSION_NOT_INITIALIZED' ,
IncompatibleExtensions = 'INCOMPATIBLE_EXTENSIONS' ,
FailedToOpenPopup = 'FAILED_TO_OPEN_POPUP' ,
FailedToRetrieveNativeTokenBalance = 'FAILED_TO_RETRIEVE_NATIVE_TOKEN_BALANCE' ,
MissingChain = 'MISSING_CHAIN' ,
MissingAccount = 'MISSING_ACCOUNT' ,
InvalidAddress = 'INVALID_ADDRESS' ,
}
RPCErrorCode
Show RPCErrorCode enum values
enum RPCErrorCode {
// Standard JSON-RPC 2.0 error codes
ParseError = - 32700 ,
InvalidRequest = - 32600 ,
MethodNotFound = - 32601 ,
InvalidParams = - 32602 ,
InternalError = - 32603 ,
// Custom Newton error codes
MagicLinkRateLimited = - 10002 ,
UserAlreadyLoggedIn = - 10003 ,
AccessDeniedToUser = - 10011 ,
UserRejectedAction = - 10012 ,
RequestCancelled = - 10014 ,
RedirectLoginComplete = - 10015 ,
NewtonWalletSessionTerminated = - 10016 ,
PopupRequestOverriden = - 10017 ,
}
SDKWarningCode
Show SDKWarningCode enum values
enum SDKWarningCode {
SyncWeb3Method = 'SYNC_WEB3_METHOD' ,
ReactNativeEndpointConfiguration = 'REACT_NATIVE_ENDPOINT_CONFIGURATION' ,
DeprecationNotice = 'DEPRECATION_NOTICE' ,
ProductAnnouncement = 'ANNOUNCEMENT' ,
}
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.
Import Path Description @magicnewton/newton-protocol-sdkFull SDK — all methods, types, utilities, and constants @magicnewton/newton-protocol-sdk/typesType definitions and interfaces only
Use subpath exports to minimize bundle size when you only need a subset of SDK functionality.