API Reference


This section provides detailed documentation for the Wallet object and its factory functions. You'll find descriptions of each function, its parameters, return values, and practical code examples for common operations like creating wallets, signing messages, and verifying signatures.

Factory Functions#

These functions are the primary way to create Wallet instances. Each function serves a specific purpose, whether you're creating a new wallet from scratch, from existing keys, or from a DID address.

fromSecretKey()#

Creates a complete wallet instance from a secret key. A wallet created this way can be used for both signing and verification.

Parameters

sk
string | Buffer | Uint8Array
required
The secret key, typically in hex format.
_type
DIDTypeArg
default:'default'

The DID type configuration. Can be a predefined string like 'default' or 'eth', or a custom type object. See for more details.

Returns

wallet
WalletObject
A new wallet object capable of signing and verifying.

Example

Signing and Verifying a Message

const assert = require('assert');
const { fromSecretKey } = require('@ocap/wallet');

// A secret key in hex format
const sk = '0xD67C071B6F51D2B61180B9B1AA9BE0DD0704619F0E30453AB4A592B036EDE644E4852B7091317E3622068E62A5127D1FB0D4AE2FC50213295E10652D2F0ABFC7';

// Create a wallet using the default DID type
const wallet = fromSecretKey(sk);

const message = 'data to sign';
const signature = wallet.sign(message);

console.log('Generated Signature:', signature);

const isValid = wallet.verify(message, signature);
assert.ok(isValid, "Signature should be verified successfully.");
console.log('Verification successful!');

fromPublicKey()#

Creates a wallet instance from a public key. This type of wallet can only be used to verify signatures, not to sign messages, as it lacks the secret key.

Parameters

pk
string | Buffer | Uint8Array
required
The public key, typically in hex format.
_type
DIDTypeArg
default:'default'

The DID type configuration. Determines the hashing and signing algorithms associated with the key.

Returns

wallet
WalletObject
A new wallet object capable of verifying signatures.

Example

Verifying a known signature

const assert = require('assert');
const { fromPublicKey } = require('@ocap/wallet');

const pk = '0xE4852B7091317E3622068E62A5127D1FB0D4AE2FC50213295E10652D2F0ABFC7';
const message = 'data to sign';
const knownSignature = '0x8122c608f61b04f6b574f005dc8e0463d393a7fb50e0426bca587b20778a8a9f6376bab87bc3983b0a5f1c9581f6d94162317c715a3c1c0f086be1e514399109';

const wallet = fromPublicKey(pk);

// This wallet can verify the signature
const isValid = wallet.verify(message, knownSignature);
assert.ok(isValid, "Signature should be verified.");

// This will throw an error because there is no secret key
try {
  wallet.sign(message);
} catch (e) {
  console.error(e.message); // Cannot sign data without a secretKey
}

fromAddress()#

Creates a minimal wallet instance from a DID address. Since the public and secret keys are unknown, this wallet cannot be used for signing or verifying. Its primary use is to inspect the DID type information encoded in the address.

Parameters

address
string
required
A valid DID address (e.g., 'zNKtCNqYWLYWYW3gWRA1vnRykfCBZYHZvzKr').

Returns

wallet
WalletObject
A new wallet object containing the address and derived type information.

Example

Inspecting a DID Address

const { fromAddress } = require('@ocap/wallet');
const { types } = require('@ocap/mcrypto');

const appId = 'zNKtCNqYWLYWYW3gWRA1vnRykfCBZYHZvzKr';
const wallet = fromAddress(appId);

console.log('Wallet Address:', wallet.address);
console.log('Role Type:', wallet.type.role); // 2 (ROLE_APPLICATION)
console.log('PK Type:', wallet.type.pk);     // 1 (ED25519)
console.log('Hash Type:', wallet.type.hash);   // 2 (SHA3)

fromRandom()#

Generates a new wallet with a randomly created key pair. This is the standard way to create a new identity.

Parameters

_type
DIDTypeArg
default:'default'

The DID type for the new wallet. Use 'eth' to generate an Ethereum-compatible wallet.

Returns

wallet
WalletObject
A new wallet object with a randomly generated key pair.

Example

Creating a new standard and an Ethereum wallet

const { fromRandom } = require('@ocap/wallet');

// Create a standard wallet (base58 address)
const standardWallet = fromRandom();
console.log('Standard DID Address:', standardWallet.address);
console.log('Secret Key:', standardWallet.secretKey);

// Create an Ethereum-compatible wallet (base16 address)
const ethWallet = fromRandom('eth');
console.log('Ethereum Address:', ethWallet.address);
console.log('Secret Key:', ethWallet.secretKey);

fromJSON()#

Reconstructs a wallet instance from a serialized JSON object, typically one created by the wallet.toJSON() method.

Parameters

json
SerializedWallet
required
A serialized wallet object.
4 subfields

Returns

wallet
WalletObject
A wallet object restored from the JSON data.

Example

Serializing and Deserializing a Wallet

const assert = require('assert');
const { fromRandom, fromJSON } = require('@ocap/wallet');

const originalWallet = fromRandom();

// Serialize the wallet to a JSON object
const walletJSON = originalWallet.toJSON();
console.log('Serialized Wallet:', walletJSON);

// Restore the wallet from the JSON object
const restoredWallet = fromJSON(walletJSON);

assert.equal(originalWallet.address, restoredWallet.address, 'Addresses should match');
assert.equal(originalWallet.secretKey, restoredWallet.secretKey, 'Secret keys should match');

console.log('Wallet restored successfully!');

isValid()#

Checks if a given object is a valid WalletObject. This is useful for type guarding and ensuring a wallet has the necessary properties and methods.

Parameters

wallet
any
required
The object to check.
canSign
boolean
default:true
If true, the function will also check for the presence of a secret key and a `sign` method.

Returns

isValid
boolean
Returns `true` if the object is a valid wallet, otherwise `false`.

Example

Validating Wallet Objects

const { fromRandom, fromPublicKey, isValid } = require('@ocap/wallet');

const signingWallet = fromRandom();
const verifyingWallet = fromPublicKey(signingWallet.publicKey);

// A full wallet is valid for signing
console.log('Is signing wallet valid for signing?', isValid(signingWallet)); // true

// A wallet from a public key is not valid for signing
console.log('Is verifying wallet valid for signing?', isValid(verifyingWallet)); // false

// But it is valid if we don't require signing capabilities
console.log('Is verifying wallet valid for verification?', isValid(verifyingWallet, false)); // true

// An empty object is not a valid wallet
console.log('Is empty object a valid wallet?', isValid({})); // false

Wallet Object#

The WalletObject is the core entity returned by the factory functions. It holds the cryptographic keys, DID address, and methods for performing cryptographic operations.

Properties#

address
string
The DID address derived from the public key and type information.
publicKey
BytesType
The public key. The format (e.g., hex string, Buffer) depends on how the wallet was created.
secretKey
BytesType
The secret key. This is `undefined` for wallets created from a public key or address.
type
DIDType
An object containing the DID type information (role, pk, hash, address encoding).

Methods#

.sign()#

Signs a piece of data using the wallet's secret key.

Parameters

data
BytesType
required
The data to be signed.
hashBeforeSign
boolean
default:true
If `true`, the data is hashed using the wallet's hash algorithm before signing.
encoding
string
default:'hex'
The output encoding for the signature ('hex', 'base64', 'base58', 'buffer', etc.).

Returns

signature
BytesType
The generated signature in the specified encoding.

.verify()#

Verifies a signature against a piece of data using the wallet's public key.

Parameters

data
BytesType
required
The original data that was signed.
signature
BytesType
required
The signature to verify.
hashBeforeVerify
boolean
default:true
If `true`, the data is hashed before verification to match the signing process.

Returns

isValid
Promise<boolean>
A promise that resolves to `true` if the signature is valid, otherwise `false`.

.hash()#

Hashes data using the wallet's configured hash algorithm.

Parameters

data
BytesType
required
The data to be hashed.
round
number
default:1
The number of hashing rounds.
encoding
string
default:'hex'
The output encoding for the hash.

Returns

hash
BytesType
The resulting hash in the specified encoding.

.ethSign()#

Signs a message using the Ethereum-specific signing algorithm (eth_sign behavior). Only available for wallets with the 'eth' type.

Parameters

data
string
required
The data to be signed.
hashBeforeSign
boolean
default:true
If `true`, the data is hashed using the Ethereum-specific `ethHash` method first.

Returns

signature
string
The generated Ethereum signature.

.ethVerify()#

Recovers the signer's address from an Ethereum signature and compares it to the wallet's address. Only available for wallets with the 'eth' type.

Parameters

data
string
required
The original data that was signed.
signature
string
required
The Ethereum signature.
hashBeforeVerify
boolean
default:true
If `true`, the data is hashed using `ethHash` before verification.

Returns

isValid
boolean
Returns `true` if the recovered address matches the wallet's address, otherwise `false`.

.toJSON()#

Serializes the wallet's state into a plain JSON object. This is useful for storing or transmitting wallet data.

Returns

serialized
SerializedWallet
A JSON object containing the wallet's type, keys, and address.