-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathocp-cli.js
More file actions
192 lines (165 loc) · 6.38 KB
/
Copy pathocp-cli.js
File metadata and controls
192 lines (165 loc) · 6.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#!/usr/bin/env node
/**
* OCP CLI - Open Commerce Protocol Command Line Interface
*
* Scaffolds OCP projects, manages agent identities, issues mandates, and checks balances.
*/
const { Command } = require('commander');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const MandateService = require('../src/services/mandate');
const TokenizationService = require('../src/services/tokenization');
const Web3Service = require('../src/services/web3');
const program = new Command();
program
.name('ocp')
.description('CLI for Open Commerce Protocol (OCP) SDK')
.version('1.0.0');
// ocp init
program.command('init')
.description('Scaffolds a new OCP project with local vault simulation')
.action(() => {
console.log('Scaffolding new OCP project...');
const projectStructure = [
'src',
'src/agents',
'src/mandates',
'config'
];
projectStructure.forEach(dir => {
if (!fs.existsSync(dir)) fs.mkdirSync(dir);
});
const envContent = `
TOKENIZATION_API_KEY=test-key
TOKENIZATION_BASE_URL=http://localhost:8080
MANDATE_SIGNING_KEY=${crypto.randomBytes(32).toString('hex')}
STRICT_MANDATE_MODE=true
`.trim();
fs.writeFileSync('.env', envContent);
console.log('Project initialized successfully. Local vault simulation configured in .env');
});
// ocp agent:create
program.command('agent:create')
.description('Generates an agent identity (did:key) and linked wallet')
.argument('<name>', 'Name of the agent')
.action((name) => {
const agentId = `agent_${crypto.randomBytes(4).toString('hex')}`;
const agentDid = `did:key:${crypto.randomBytes(16).toString('hex')}`;
const agentData = {
id: agentId,
name: name,
did: agentDid,
wallet_address: `0x${crypto.randomBytes(20).toString('hex')}`,
created_at: new Date().toISOString()
};
if (!fs.existsSync('src/agents')) fs.mkdirSync('src/agents', { recursive: true });
fs.writeFileSync(`src/agents/${agentId}.json`, JSON.stringify(agentData, null, 2));
console.log(`Agent created: ${name}`);
console.log(`ID: ${agentId}`);
console.log(`DID: ${agentDid}`);
});
// ocp mandate:issue
program.command('mandate:issue')
.description('Interactively creates a signed Intent Mandate for an agent')
.option('--agent <id>', 'Agent ID')
.option('--budget <amount>', 'Maximum budget', '100')
.option('--currency <code >', 'Currency', 'USD')
.action(async (options) => {
if (!options.agent) {
console.error('Error: Agent ID required. Use --agent <id>');
return;
}
const signingKey = process.env.MANDATE_SIGNING_KEY || 'default-secret-key';
const mandateService = new MandateService({ signingKey });
const mandateToken = await mandateService.issueIntentMandate({
userDid: 'did:key:user-local',
agentDid: `did:key:${options.agent}`,
maxBudget: parseFloat(options.budget),
currency: options.currency,
purposeCode: 'CLI_ISSUED'
});
const decoded = await mandateService.verifyMandate(mandateToken);
const mandateId = decoded.mandate_id;
if (!fs.existsSync('src/mandates')) fs.mkdirSync('src/mandates', { recursive: true });
fs.writeFileSync(`src/mandates/${mandateId}.jwt`, mandateToken);
console.log(`Intent Mandate issued for agent ${options.agent}`);
console.log(`Mandate ID: ${mandateId}`);
console.log(`Budget: ${options.budget} ${options.currency}`);
console.log(`Saved to: src/mandates/${mandateId}.jwt`);
});
// ocp wallet:balance
program.command('wallet:balance')
.description('Checks real-time balances across ledger and Web3 rails')
.argument('<address>', 'Wallet address or Agent ID')
.action((address) => {
console.log(`Checking balances for ${address}...`);
// Mock balance retrieval
const balances = {
ledger: '500.00 USD',
web3: {
eth: '1.25 ETH',
usdc: '250.00 USDC',
pyusd: '100.00 PYUSD'
}
};
console.log(`Ledger Balance: ${balances.ledger}`);
console.log(`Web3 Balances:`);
console.log(` - ETH: ${balances.web3.eth}`);
console.log(` - USDC: ${balances.web3.usdc}`);
console.log(` - PYUSD: ${balances.web3.pyusd}`);
});
// ocp x402:settle
program.command('x402:settle')
.description('Executes a 24/7 stablecoin settlement (USDC/PYUSD) using the x402 extension')
.argument('<amount>', 'Amount to settle')
.option('--to <address>', 'Recipient address')
.option('--token <type>', 'Stablecoin token (USDC/PYUSD)', 'USDC')
.option('--mandate <path>', 'Path to the signed Mandate JWT')
.action(async (amount, options) => {
if (!options.to) {
console.error('Error: Recipient address required. Use --to <address>');
return;
}
console.log(`x402: Initiating ${options.token} settlement of ${amount} to ${options.to}...`);
let mandateToken = null;
if (options.mandate) {
if (fs.existsSync(options.mandate)) {
mandateToken = fs.readFileSync(options.mandate, 'utf8');
} else {
console.error(`Error: Mandate file not found at ${options.mandate}. In STRICT_MANDATE_MODE, a valid mandate is required for signing.`);
return;
}
} else if (process.env.STRICT_MANDATE_MODE === 'true') {
console.error(`Error: Mandate required for x402 settlement in STRICT_MANDATE_MODE.`);
return;
}
// Initialize Services for real settlement rails logic
const tokenizationService = new TokenizationService({
apiKey: process.env.TOKENIZATION_API_KEY || 'test-key',
mandateConfig: {
signingKey: process.env.MANDATE_SIGNING_KEY || 'default-secret-key'
}
});
const web3Service = new Web3Service(tokenizationService);
try {
const amountNum = parseFloat(amount);
const result = await web3Service.executeX402Settlement({
keyTokenId: 'cli-default-key', // Use default CLI key
to: options.to,
amount: amountNum,
stablecoin: options.token,
mandate: mandateToken
});
console.log(`Settlement Successful!`);
console.log(`ID: ${result.settlement_id}`);
console.log(`Token: ${result.stablecoin}`);
console.log(`Amount: ${result.amount}`);
console.log(`Recipient: ${result.recipient}`);
console.log(`Transaction Hash: ${result.tx_hash}`);
console.log(`Status: Finalized (24/7 Low-Latency Rails)`);
} catch (error) {
console.error(error.message);
}
});
program.parse();