Complete API reference for the @mpc-wallet/sdk TypeScript package.
npm install @mpc-wallet/sdk
# or
yarn add @mpc-wallet/sdk
# or
pnpm add @mpc-wallet/sdkimport {
MpcAgentWallet,
PartyRole,
PolicyConfig,
ChainType
} from '@mpc-wallet/sdk';
const wallet = await MpcAgentWallet.create({
role: PartyRole.Agent,
policy: new PolicyConfig().withDailyLimit(ChainType.Evm, BigInt('10000000000000000000')),
});Main class for managing MPC-secured wallets.
Create a new MPC wallet instance.
const wallet = await MpcAgentWallet.create({
role: PartyRole.Agent,
policy: new PolicyConfig(),
});| Parameter | Type | Description |
|---|---|---|
config.role |
PartyRole |
Party role (Agent, User, Recovery) |
config.policy |
PolicyConfig |
Policy configuration |
config.storage |
KeyShareStore |
Storage backend |
config.keyShare |
KeyShare |
Existing key share to load |
Create a wallet from an existing key share.
const wallet = await MpcAgentWallet.fromShare(keyShare, {
policy: new PolicyConfig(),
});fromStorage(shareId: string, password: string, storage: KeyShareStore, config?: WalletConfig): Promise<MpcAgentWallet>
Create a wallet by loading a key share from storage.
const wallet = await MpcAgentWallet.fromStorage(
'my-wallet',
'secure-password',
new FileStore('./keys')
);Create a key generation session.
const session = wallet.createKeygenSession({
role: PartyRole.Agent,
sessionId: crypto.randomUUID(),
threshold: 2,
parties: 3,
});Set the key share after key generation.
Get the current key share.
Check if a key share is loaded.
Get the party role.
Get the wallet's Ethereum address.
const address = wallet.getAddress();
// '0x742d35Cc6634C0532925a3b844Bc9e7595f...'Get the wallet's compressed public key.
Get address for a specific chain type.
const ethAddress = wallet.getChainAddress(ChainType.Evm);
const solAddress = wallet.getChainAddress(ChainType.Solana);Set the policy configuration.
Get the current policy configuration.
Evaluate a transaction against the policy.
const decision = wallet.evaluatePolicy({
requestId: 'tx-1',
chain: ChainType.Evm,
to: '0x...',
value: '1000000000000000000',
chainId: 1,
timestamp: Date.now(),
});
if (!decision.approved) {
console.log('Rejected:', decision.reason);
}Create a signing session.
const messageHash = wallet.hashTransaction(tx);
const session = wallet.createSigningSession(
{
sessionId: crypto.randomUUID(),
parties: [PartyRole.Agent, PartyRole.User],
threshold: 2,
},
messageHash
);Hash a message using Keccak256.
Hash a message with Ethereum prefix (\x19Ethereum Signed Message:\n).
Create a transaction hash for signing.
Save the key share to storage.
await wallet.saveKeyShare('my-wallet', 'secure-password');Load a key share from storage.
Delete a key share from storage.
List all stored share IDs.
Export wallet state (without secrets) for debugging.
Get wallet info summary.
Manages the distributed key generation (DKG) protocol.
const session = new KeygenSession({
role: PartyRole.Agent,
sessionId: 'session-123',
threshold: 2,
parties: 3,
});Generate round 1 (commitment) message.
Process round 1 messages from other parties.
Generate round 2 (key share) message.
Process round 2 messages from other parties.
Generate round 3 (verification) message.
Finalize key generation and return the key share.
Get current session state.
Manages the distributed signature generation (DSG) protocol.
const session = new SigningSession(
{
sessionId: 'session-456',
parties: [PartyRole.Agent, PartyRole.User],
threshold: 2,
},
keyShare,
messageHash
);Generate round 1 message.
Process round 1 messages from other signing parties.
Generate round 2 message.
Finalize signing and return the signature.
Configuration for the policy engine.
const policy = new PolicyConfig();Add spending limits for a chain.
policy.withSpendingLimits(ChainType.Evm, {
perTransaction: BigInt('1000000000000000000'), // 1 ETH
daily: BigInt('10000000000000000000'), // 10 ETH
weekly: BigInt('50000000000000000000'), // 50 ETH
});Add address whitelist.
policy.withWhitelist([
'0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45',
'0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',
]);Add address blacklist.
Add time restrictions.
policy.withTimeBounds({
startHour: 9,
endHour: 17,
allowedDays: [1, 2, 3, 4, 5], // Monday-Friday
timezone: 'America/New_York',
});Add contract interaction restrictions.
policy.withContractRestrictions({
allowedContracts: ['0x...'],
blockedSelectors: ['0xa9059cbb'], // Block raw ERC20 transfers
});Require recovery guardian approval for transactions above threshold.
Evaluates transactions against configured policies.
const engine = new PolicyEngine(policyConfig);Evaluate a transaction against all policies.
const decision = engine.evaluate(tx);
// { approved: true, requiresAdditionalApproval: false }
// or
// { approved: false, reason: 'Daily spending limit exceeded' }Get the current policy configuration.
Update the policy configuration.
Get current spending statistics.
Interface for key share storage backends.
interface KeyShareStore {
store(id: string, share: KeyShare, password: string): Promise<void>;
load(id: string, password: string): Promise<KeyShare>;
delete(id: string): Promise<boolean>;
list(): Promise<string[]>;
exists(id: string): Promise<boolean>;
}In-memory storage (for testing).
const store = new MemoryStore();File system storage with encryption.
const store = new FileStore('./keys', {
permissions: 0o600,
});Browser IndexedDB storage.
const store = new IndexedDBStore('mpc-wallet');Ethereum/EVM chain adapter.
import { EvmAdapter } from '@mpc-wallet/sdk/chains';
const adapter = new EvmAdapter({
rpcUrls: ['https://eth.llamarpc.com', 'https://rpc.ankr.com/eth'],
chainId: 1,
});
const balance = await adapter.getBalance('0x...');
const tx = await adapter.buildTransaction({
to: '0x...',
value: '1000000000000000000',
});Solana chain adapter.
import { SolanaAdapter } from '@mpc-wallet/sdk/chains';
const adapter = new SolanaAdapter({
rpcUrl: 'https://api.mainnet-beta.solana.com',
commitment: 'confirmed',
});enum PartyRole {
Agent = 0,
User = 1,
Recovery = 2,
}enum ChainType {
Evm = 0,
Solana = 1,
Bitcoin = 2,
}interface TransactionRequest {
requestId: string;
chain: ChainType;
to: string;
value: string;
data?: string;
gasLimit?: number;
chainId?: number;
timestamp: number;
metadata?: Record<string, unknown>;
}interface Signature {
r: string; // Hex string with 0x prefix
s: string; // Hex string with 0x prefix
recoveryId: number; // 0 or 1
}interface PolicyDecision {
approved: boolean;
reason?: string;
requiresAdditionalApproval?: boolean;
}interface KeyShare {
partyId: number;
role: PartyRole;
publicKey: string; // Compressed public key (hex)
ethAddress: string; // Derived Ethereum address
secretShare: string; // Encrypted secret share (base64)
verificationKey: string;
threshold: number;
parties: number;
}type SessionState =
| 'initialized'
| 'round1'
| 'round2'
| 'round3'
| 'complete'
| 'failed';enum ErrorCode {
InvalidConfig = 'INVALID_CONFIG',
InvalidPartyId = 'INVALID_PARTY_ID',
ThresholdNotMet = 'THRESHOLD_NOT_MET',
PolicyViolation = 'POLICY_VIOLATION',
SigningFailed = 'SIGNING_FAILED',
KeygenFailed = 'KEYGEN_FAILED',
StorageError = 'STORAGE_ERROR',
NetworkError = 'NETWORK_ERROR',
Timeout = 'TIMEOUT',
Unknown = 'UNKNOWN',
}class MpcWalletError extends Error {
code: ErrorCode;
cause?: Error;
}import { MpcWalletError, ErrorCode } from '@mpc-wallet/sdk';
try {
await wallet.signTransaction(tx);
} catch (error) {
if (error instanceof MpcWalletError) {
switch (error.code) {
case ErrorCode.PolicyViolation:
console.log('Policy rejected transaction:', error.message);
break;
case ErrorCode.ThresholdNotMet:
console.log('Not enough parties for signing');
break;
case ErrorCode.Timeout:
console.log('Operation timed out');
break;
default:
console.error('Wallet error:', error);
}
}
}import { isHexString, isAddress } from '@mpc-wallet/sdk';
isHexString('0x1234'); // true
isAddress('0x742d35Cc6634C0532925a3b844Bc9e7595f12345'); // trueimport { formatEther, parseEther, formatGwei } from '@mpc-wallet/sdk/utils';
formatEther(BigInt('1000000000000000000')); // '1.0'
parseEther('1.5'); // BigInt('1500000000000000000')The wallet emits events for monitoring:
wallet.on('keyShareLoaded', (share: KeyShare) => {
console.log('Key share loaded:', share.ethAddress);
});
wallet.on('policyEvaluated', (tx: TransactionRequest, decision: PolicyDecision) => {
console.log('Policy decision:', decision);
});
wallet.on('signingStarted', (sessionId: string) => {
console.log('Signing session started:', sessionId);
});
wallet.on('signingComplete', (sessionId: string, signature: Signature) => {
console.log('Signing complete:', signature);
});See the examples directory for complete working examples: