@scafonix/agent
v1.0.13
Published
Next-Generation Non-Custodial M-of-N MPC Security & x402 USDC Payment Infrastructure for Autonomous AI Agents
Maintainers
Readme
@scafonix/agent
Build Your Own Self-Hosted M-of-N MPC Wallet Infrastructure with Zero Upfront Cost & Pay-per-Signature x402 Micropayments ($0.005 USDC)
@scafonix/agent is the official JavaScript/TypeScript SDK that empowers developers to build and deploy their own 100% self-hosted, non-custodial M-of-N MPC wallet security infrastructure for autonomous AI Agents (LangChain, CrewAI, AutoGen, ELIZA, etc.).
🌟 Key Value Proposition
- Build Your Own MPC Infrastructure: You can host and run your own independent, non-custodial multi-agent consensus MPC wallet system without relying on third-party key custodians or centralized servers.
- Zero Fixed Subscription Costs: Key share generation, wallet address derivation, and worker partial signing are 100% free with zero recurring subscription fees.
- Transparent Pay-per-Signature Pricing ($0.005 USDC): You only pay a flat $0.005 USDC per final combined signature via native x402 micropayment protocol on Base L2 when broadcasting real on-chain transactions.
🏗️ Architecture & Sequence Flow (2-of-3 Threshold & x402 Ticket Gate)
The following diagram illustrates how the Master AI, Worker AIs, and Scafonix x402 Ticket Gate interact during an M-of-N threshold signature transaction:

💻 Installation
npm install @scafonix/agent🎲 What are seed1 and seed2? (Dual Entropy Mechanism)
Scafonix Agentic MPC uses a Dual-Source Entropy Mixing Algorithm to guarantee cryptographic security even if one entropy source is compromised:
seed1(User / Master AI Entropy): A 32-byte (64-char hex) random string generated by your application, Master AI, or user secret (crypto.randomBytes(32).toString('hex')).seed2(Client / System Hardware Entropy): A 32-byte (64-char hex) random string generated by the client environment, OS hardware RNG, or secondary worker.
🛡️ Why Two Seeds?
If one random number generator (RNG) is compromised or flawed, the second independent seed guarantees 100% cryptographic randomness and zero key leak risk.
🔑 Return Data Structure Example
Object structure returned when calling await agent.generateKeyShares(seed1, seed2):
{
share1: "1-97c44a91cb12b926de7b01479e282a5b11f0eb6e5a5255443e7d172f552fecac",
share2: "2-3333333333333333333333333333333333333333333333333333333333333333",
share3: "3-8bce03f349a389019e3e580d1d855404c18f2b3df2cd77275a6c7cb80c70541e",
_meta: { m: 2, n: 3 }
}🚀 Quick Start: Complete 5-Step Agent Integration Guide
Copy and paste this ready-to-run 5-step JavaScript integration workflow:
const { ScafonixAgent } = require('@scafonix/agent');
const { ethers } = require('ethers');
const crypto = require('crypto');
async function main() {
// -------------------------------------------------------------
// STEP 1. Initialize Master AI & 3 Worker AIs (2-of-3 Threshold)
// -------------------------------------------------------------
const master = new ScafonixAgent({ agentId: 'Master-Orchestrator' });
const worker1 = new ScafonixAgent({ agentId: 'Worker-1-TradingAI' });
const worker2 = new ScafonixAgent({ agentId: 'Worker-2-ChartAI' });
const worker3 = new ScafonixAgent({ agentId: 'Worker-3-AuditAI' });
await master.init();
await worker1.init();
await worker2.init();
await worker3.init();
// -------------------------------------------------------------
// STEP 2. Generate 2-of-3 Key Shares & Derive EVM Address
// -------------------------------------------------------------
const seed1 = crypto.randomBytes(32).toString('hex');
const seed2 = crypto.randomBytes(32).toString('hex');
const shares = await master.generateKeyShares(seed1, seed2);
// [Isolated Worker Storage]
const worker1Share = shares['share1']; // Worker 1 holds Share 1
const worker2Share = shares['share2']; // Worker 2 holds Share 2
const worker3Share = shares['share3']; // Worker 3 holds Share 3 (Master holds ZERO shares!)
// Derive Consensus Wallet Address (Share 1 + Share 2 pairing)
const walletAddress = await master.deriveAddress(worker1Share, worker2Share);
console.log("📍 Agent Consensus Wallet Address:", walletAddress);
// -------------------------------------------------------------
// STEP 3. Target Transaction Hash (32-byte Hex Hash)
// -------------------------------------------------------------
const tx = ethers.Transaction.from({
to: "0x678faFD22Fcc96B89Ad96942C86D139b005e4A9D",
value: ethers.parseEther("0.001"),
nonce: 0,
gasLimit: 21000n,
gasPrice: 10000000n,
chainId: 8453 // Base Mainnet
});
const txHash = ethers.keccak256(tx.unsignedSerialized);
// -------------------------------------------------------------
// STEP 4. Buy x402 Signed Ticket ($0.005 USDC on Base via mpc-api.scafonix.com)
// -------------------------------------------------------------
// Official Ticket object issued by Scafonix Gate (https://agent.scafonix.com)
// after Master Orchestrator confirms $0.005 USDC payment.
const ticket = {
ticketId: "s_tkt_8f92a10b4c739d2e",
agentId: "Master-Orchestrator",
payerAddress: "0xd2131430dc801a74909a58166a3a25cde82ec75a",
msgHash: txHash,
status: "VALID",
issuedAt: 1786000000,
expiresAt: 1786000600,
network: "base-mainnet",
feePaid: "0.005 USDC",
signedProof: "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0aWNrZXRJZCI6InNfdGt0XzhmOTJhMTBiNGM3MzlkMmUiLCJtc2dIYXNoIjoiMHgwMTIzNDU2Nzg5YWJjZGVmIiwiZXhwaXJlcyI6MTc4NjAwMDYwMH0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
};
// -------------------------------------------------------------
// STEP 5. 2-of-3 Voting: Workers Sign Partial & Master Combines
// -------------------------------------------------------------
// Worker 1 (Trading AI): APPROVE ✅ (Generates Partial Signature 1 with singleShare)
const part1 = await worker1.signPartial({
singleShare: worker1Share,
msgHash: txHash
});
// Worker 2 (Chart AI): APPROVE ✅ (Generates Partial Signature 2 with singleShare)
const part2 = await worker2.signPartial({
singleShare: worker2Share,
msgHash: txHash
});
// Worker 3 (Audit AI): REJECT ❌ (Suspicious risk detected - Does NOT sign)
// Master AI combines 2 valid worker partial signatures + x402 Ticket -> Final (R, S, V)
const finalSig = await master.combineSignatures({
partialSignatures: [part1, part2],
ticket: ticket
});
console.log("🎉 Final Valid Signature (R, S, V):", finalSig);
// -------------------------------------------------------------
// STEP 6. Broadcast Signed Transaction to Network
// -------------------------------------------------------------
tx.signature = { r: '0x' + finalSig.r, s: '0x' + finalSig.s, v: finalSig.v };
const signedTxSerialized = tx.serialized;
console.log("🚀 Ready to Broadcast Signed Tx Serialized:", signedTxSerialized);
}
main().catch(console.error);💳 Master Orchestrator Payment Role & Anti Front-Running Protection (payerAddress)
1. Master Orchestrator Payment Role
In the Scafonix M-of-N architecture, the Master Orchestrator Agent is responsible for purchasing 1-time x402 tickets ($0.005 USDC on Base L2) using its payment wallet.
- Isolated Worker AIs only generate partial signatures (
signPartial) locally for FREE without requiring gas or payment keys.
2. Anti Front-Running & Ticket Theft Protection (payerAddress)
To prevent malicious third-party bots from intercepting and stealing on-chain 0.005 USDC payment transaction hashes:
- When requesting a ticket (
POST /v1/ticket/issue), the Master Agent submits itspayerAddress(its payment wallet address). - The Scafonix Ticket Gate verifies on-chain that the
payerAddressmatches the actual sender of the 0.005 USDC transfer in the transaction logs. - If a hacker attempts to submit a stolen
txHashwith a differentpayerAddress, the request is instantly rejected withHTTP 403 Payment Authorization Mismatch, guaranteeing 100% ticket theft protection.
🗝️ Human Owner Emergency Private Key Export (No x402 Ticket Required)
Human System Owners can independently export the raw 256-bit EOA Private Key (0x...) for emergency backup or cold storage.
[!CAUTION] AI AGENT RESTRICTION RULE: This method is strictly reserved for Human System Owners. Autonomous AI Agents are prohibited from possessing or invoking key export functions.
const { ScafonixAgent } = require('@scafonix/agent');
const master = new ScafonixAgent({ agentId: 'Human-Owner-Admin' });
// Supply any 2 threshold key shares (e.g. worker1Share and worker2Share)
const rawPrivateKey = await master.exportPrivateKey(worker1Share, worker2Share);
console.log("🔑 Raw EOA Private Key:", rawPrivateKey); // 0x...64-char hex📖 API Reference Summary
| Method | Parameters | Description / Return Value |
| :--- | :--- | :--- |
| generateKeyShares(seed1, seed2) | Two 32-byte hex entropy seeds | { share1, share2, share3, _meta } key share object |
| deriveAddress(shareA, shareB) | Two key share strings | On-chain EOA Wallet Address (0x...) |
| signPartial({ singleShare, msgHash }) | Own share, txHash | 1-time Worker Partial Signature (partialS, r, v) |
| combineSignatures({ partialSignatures, ticket }) | Array of partial signatures, x402 Ticket | On-chain Final Signature (r, s, v, ticketId) |
| exportPrivateKey(shareA, shareB) | Two key share strings | [HUMAN ONLY] Raw 256-bit Hex Private Key (0x...) |
📄 License
MIT © Scafonix Team
