@cryptoslip/mcp 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +66 -3
- package/SKILL.md +108 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +9 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/pocketSlip.d.ts +231 -0
- package/dist/pocketSlip.d.ts.map +1 -0
- package/dist/pocketSlip.js +867 -0
- package/dist/pocketSlip.js.map +1 -0
- package/dist/server.d.ts +25 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +276 -0
- package/dist/server.js.map +1 -0
- package/package.json +78 -6
|
@@ -0,0 +1,867 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { randomBytes } from 'node:crypto';
|
|
5
|
+
import { bytesToBigInt, bytesToHex, createPublicClient, formatUnits, getAddress, http, isAddress, keccak256, parseUnits, stringToHex, } from 'viem';
|
|
6
|
+
import { base } from 'viem/chains';
|
|
7
|
+
import { privateKeyToAccount } from 'viem/accounts';
|
|
8
|
+
import { BoundedAgentPolicy, CANONICAL_VAULT_V33_ADDRESS, CIRCLE_TOKEN_PAYMASTER_V08_ADDRESS, ERC20_PERMIT_EIP3009_ABI, ISSUE_VAULT, MIN_CIRCLE_PAYMASTER_USDC_UNITS, NARA_LIQUIDITY_HOOK_V5_ADDRESS, SlipMutex, SlipStatus, USDC_BASE_ADDRESS, createPolicyGuardedSigner, createSignedPaymentReceipt, createSlipSignerFromKey, decimalsForAsset, estimateUsdMicro, executeBatchPayoutSlips, formatReceiptCsvRow, fromViemWalletClient, grossUpForExactNet, keepSlip, minSlipAmount, normalizeSdkAsset, parsePopupCheckoutUrl, parseSlipUrl, parseWatchOnlyPosUrl, readOnChainSlip, redactSecretsFromToolOutput, refundSlipDirect, renderPrintableReceiptHtml, scanReclaimableSlips, splitAndPay, verifyPaymentReceiptOnChain, withdrawReferralCredits, } from '@cryptoslip/sdk';
|
|
9
|
+
const SECP256K1_ORDER = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;
|
|
10
|
+
export class PocketSlipError extends Error {
|
|
11
|
+
constructor(message) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = 'PocketSlipError';
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function generateRandomSecp256k1Key() {
|
|
17
|
+
for (let i = 0; i < 64; i++) {
|
|
18
|
+
const bytes = randomBytes(32);
|
|
19
|
+
const scalar = bytesToBigInt(bytes);
|
|
20
|
+
if (scalar > 0n && scalar < SECP256K1_ORDER) {
|
|
21
|
+
return bytesToHex(bytes);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
throw new PocketSlipError('Failed to generate valid secp256k1 key.');
|
|
25
|
+
}
|
|
26
|
+
function parseEnvUsdToMicro(raw, fallbackMicro) {
|
|
27
|
+
if (!raw || !raw.trim())
|
|
28
|
+
return fallbackMicro;
|
|
29
|
+
return parseUnits(raw.trim(), 6);
|
|
30
|
+
}
|
|
31
|
+
export function buildPolicyFromEnv(env = process.env, overrides) {
|
|
32
|
+
const maxPerCallUsdMicro = overrides?.maxPerCallUsdMicro ??
|
|
33
|
+
parseEnvUsdToMicro(env.CRYPTOSLIP_MAX_PER_CALL_USD, 500000n);
|
|
34
|
+
const maxDailyUsdMicro = overrides?.maxDailyUsdMicro ??
|
|
35
|
+
parseEnvUsdToMicro(env.CRYPTOSLIP_MAX_DAILY_USD, 5000000n);
|
|
36
|
+
const maxSpendsPerMinute = overrides?.maxSpendsPerMinute ??
|
|
37
|
+
(env.CRYPTOSLIP_MAX_SPENDS_PER_MIN
|
|
38
|
+
? Number.parseInt(env.CRYPTOSLIP_MAX_SPENDS_PER_MIN, 10)
|
|
39
|
+
: 3);
|
|
40
|
+
const allowedRecipients = overrides?.allowedRecipients ??
|
|
41
|
+
(env.CRYPTOSLIP_ALLOWED_RECIPIENTS
|
|
42
|
+
? env.CRYPTOSLIP_ALLOWED_RECIPIENTS.split(',').map((s) => s.trim()).filter(Boolean)
|
|
43
|
+
: undefined);
|
|
44
|
+
const allowedDomains = overrides?.allowedDomains ??
|
|
45
|
+
(env.CRYPTOSLIP_ALLOWED_DOMAINS
|
|
46
|
+
? env.CRYPTOSLIP_ALLOWED_DOMAINS.split(',').map((s) => s.trim()).filter(Boolean)
|
|
47
|
+
: undefined);
|
|
48
|
+
const allowOutboundSlipLinks = overrides?.allowOutboundSlipLinks ??
|
|
49
|
+
(env.CRYPTOSLIP_ALLOW_OUTBOUND_LINKS
|
|
50
|
+
? env.CRYPTOSLIP_ALLOW_OUTBOUND_LINKS.toLowerCase() !== 'false'
|
|
51
|
+
: true);
|
|
52
|
+
return new BoundedAgentPolicy({
|
|
53
|
+
...overrides,
|
|
54
|
+
maxPerCallUsdMicro,
|
|
55
|
+
maxDailyUsdMicro,
|
|
56
|
+
maxSpendsPerMinute,
|
|
57
|
+
allowedRecipients,
|
|
58
|
+
allowedDomains,
|
|
59
|
+
allowOutboundSlipLinks,
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
function parseAmountUnits(raw, asset, amountIsAtomic = false) {
|
|
63
|
+
if (typeof raw === 'bigint')
|
|
64
|
+
return raw;
|
|
65
|
+
if (amountIsAtomic) {
|
|
66
|
+
const str = String(raw).trim();
|
|
67
|
+
if (!/^\d+$/.test(str)) {
|
|
68
|
+
throw new PocketSlipError(`Invalid atomic integer amount: ${str}`);
|
|
69
|
+
}
|
|
70
|
+
return BigInt(str);
|
|
71
|
+
}
|
|
72
|
+
const str = String(raw).trim();
|
|
73
|
+
if (!/^\d+(?:\.\d+)?$/.test(str)) {
|
|
74
|
+
throw new PocketSlipError(`Invalid decimal amount: ${str}`);
|
|
75
|
+
}
|
|
76
|
+
return parseUnits(str, decimalsForAsset(asset));
|
|
77
|
+
}
|
|
78
|
+
function resolveMerchantAddress(rawRecipient) {
|
|
79
|
+
const trimmed = rawRecipient.trim();
|
|
80
|
+
if (isAddress(trimmed)) {
|
|
81
|
+
return getAddress(trimmed);
|
|
82
|
+
}
|
|
83
|
+
const pos = parseWatchOnlyPosUrl(trimmed);
|
|
84
|
+
if (pos?.merchantAddress && isAddress(pos.merchantAddress)) {
|
|
85
|
+
return getAddress(pos.merchantAddress);
|
|
86
|
+
}
|
|
87
|
+
const checkout = parsePopupCheckoutUrl(trimmed);
|
|
88
|
+
if (checkout?.recipientAddress && isAddress(checkout.recipientAddress)) {
|
|
89
|
+
return getAddress(checkout.recipientAddress);
|
|
90
|
+
}
|
|
91
|
+
throw new PocketSlipError('Recipient must be a valid 0x Base wallet address, #startapp=pos_<address>, or #startapp=pay_<address> URL.');
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* `PocketSlipVault` (`Module #1`):
|
|
95
|
+
* Self-rotating `$5` pocket-money vault for AI agents (`V-01` `<1s` Boot Auto-Keep,
|
|
96
|
+
* `V-02` `BoundedAgentPolicy` firewall, `V-03` `SlipMutex` + `$0.10` dust guard,
|
|
97
|
+
* and `V-04` Circle `TokenPaymasterV08` USDC gas default).
|
|
98
|
+
*/
|
|
99
|
+
export class PocketSlipVault {
|
|
100
|
+
publicClient;
|
|
101
|
+
policy;
|
|
102
|
+
mutex;
|
|
103
|
+
stateFilePath;
|
|
104
|
+
rawSlipUrl;
|
|
105
|
+
walletClient;
|
|
106
|
+
transportOverrides;
|
|
107
|
+
customBatchExecutor;
|
|
108
|
+
operatorPrivateKey;
|
|
109
|
+
operatorAddress;
|
|
110
|
+
originalLineageHash;
|
|
111
|
+
activeSlipId = null;
|
|
112
|
+
activeVault = ISSUE_VAULT;
|
|
113
|
+
activeAsset = 'USDC';
|
|
114
|
+
activeClaimPrivateKey;
|
|
115
|
+
activeClaimSigner;
|
|
116
|
+
bootRotated = false;
|
|
117
|
+
bootRotationTxHash;
|
|
118
|
+
createdRevocableSlipIds = [];
|
|
119
|
+
bootPromise = null;
|
|
120
|
+
initialized = false;
|
|
121
|
+
constructor(config = {}) {
|
|
122
|
+
this.rawSlipUrl = config.slipUrl ?? process.env.CRYPTOSLIP_URL;
|
|
123
|
+
const defaultStateFile = process.env.CRYPTOSLIP_STATE_PATH ??
|
|
124
|
+
path.join(os.homedir(), '.cryptoslip-mcp', 'pocket-state.json');
|
|
125
|
+
this.stateFilePath =
|
|
126
|
+
config.stateFilePath === undefined ? defaultStateFile : config.stateFilePath;
|
|
127
|
+
const rpcUrl = config.rpcUrl ?? process.env.CRYPTOSLIP_RPC_URL ?? 'https://mainnet.base.org';
|
|
128
|
+
this.publicClient =
|
|
129
|
+
config.publicClient ??
|
|
130
|
+
createPublicClient({
|
|
131
|
+
chain: base,
|
|
132
|
+
transport: http(rpcUrl),
|
|
133
|
+
});
|
|
134
|
+
this.walletClient = config.walletClient;
|
|
135
|
+
this.policy =
|
|
136
|
+
config.policy instanceof BoundedAgentPolicy
|
|
137
|
+
? config.policy
|
|
138
|
+
: buildPolicyFromEnv(process.env, config.policy);
|
|
139
|
+
this.mutex = config.mutex ?? new SlipMutex();
|
|
140
|
+
this.transportOverrides = config.transportOverrides ?? {};
|
|
141
|
+
this.customBatchExecutor = config.customBatchExecutor ?? executeBatchPayoutSlips;
|
|
142
|
+
const persisted = this.readPersistedState();
|
|
143
|
+
const initialOpKey = config.operatorPrivateKey ??
|
|
144
|
+
(this.walletClient?.account && 'source' in this.walletClient.account
|
|
145
|
+
? undefined
|
|
146
|
+
: persisted?.operatorPrivateKey) ??
|
|
147
|
+
generateRandomSecp256k1Key();
|
|
148
|
+
this.operatorPrivateKey = (initialOpKey.startsWith('0x') ? initialOpKey : `0x${initialOpKey}`);
|
|
149
|
+
this.operatorAddress = this.walletClient?.account
|
|
150
|
+
? getAddress(this.walletClient.account.address)
|
|
151
|
+
: getAddress(privateKeyToAccount(this.operatorPrivateKey).address);
|
|
152
|
+
this.originalLineageHash = persisted?.originalLineageHash ?? ('0x' + '00'.repeat(32));
|
|
153
|
+
if (persisted?.createdRevocableSlipIds) {
|
|
154
|
+
this.createdRevocableSlipIds = [...persisted.createdRevocableSlipIds];
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
readPersistedState() {
|
|
158
|
+
if (!this.stateFilePath)
|
|
159
|
+
return null;
|
|
160
|
+
try {
|
|
161
|
+
if (!fs.existsSync(this.stateFilePath))
|
|
162
|
+
return null;
|
|
163
|
+
const raw = fs.readFileSync(this.stateFilePath, 'utf8');
|
|
164
|
+
const parsed = JSON.parse(raw);
|
|
165
|
+
if (parsed && parsed.version === 1 && parsed.operatorPrivateKey) {
|
|
166
|
+
return parsed;
|
|
167
|
+
}
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
writePersistedState(state) {
|
|
175
|
+
if (!this.stateFilePath)
|
|
176
|
+
return;
|
|
177
|
+
const dir = path.dirname(this.stateFilePath);
|
|
178
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
179
|
+
const tmpPath = `${this.stateFilePath}.${process.pid}.tmp`;
|
|
180
|
+
fs.writeFileSync(tmpPath, JSON.stringify(state, null, 2), {
|
|
181
|
+
encoding: 'utf8',
|
|
182
|
+
mode: 0o600,
|
|
183
|
+
});
|
|
184
|
+
try {
|
|
185
|
+
fs.chmodSync(tmpPath, 0o600);
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
// Windows NTFS ignores POSIX mode bits; chmod succeeds on Linux/macOS
|
|
189
|
+
}
|
|
190
|
+
fs.renameSync(tmpPath, this.stateFilePath);
|
|
191
|
+
}
|
|
192
|
+
syncStateToDisk() {
|
|
193
|
+
this.writePersistedState({
|
|
194
|
+
version: 1,
|
|
195
|
+
originalLineageHash: this.originalLineageHash,
|
|
196
|
+
activeSlipId: this.activeSlipId,
|
|
197
|
+
vault: this.activeVault,
|
|
198
|
+
asset: this.activeAsset,
|
|
199
|
+
...(this.activeClaimPrivateKey ? { activeClaimPrivateKey: this.activeClaimPrivateKey } : {}),
|
|
200
|
+
...(this.activeClaimSigner ? { activeClaimSigner: this.activeClaimSigner } : {}),
|
|
201
|
+
operatorPrivateKey: this.operatorPrivateKey,
|
|
202
|
+
operatorAddress: this.operatorAddress,
|
|
203
|
+
bootRotated: this.bootRotated,
|
|
204
|
+
...(this.bootRotationTxHash ? { bootRotationTxHash: this.bootRotationTxHash } : {}),
|
|
205
|
+
updatedAt: new Date().toISOString(),
|
|
206
|
+
createdRevocableSlipIds: this.createdRevocableSlipIds,
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* `V-01` Boot Auto-Keep:
|
|
211
|
+
* Immediately checks the configured `CRYPTOSLIP_URL` on Base Mainnet. If unrotated (`nonces == 0`),
|
|
212
|
+
* executes `keepSlip()` (`0%` protocol fee) rotating `claimSigner` to a fresh local key persisted in
|
|
213
|
+
* `0600` local storage, invalidating the `.env` `#k` link on-chain in `<1s`.
|
|
214
|
+
*/
|
|
215
|
+
async bootAndRotate() {
|
|
216
|
+
if (this.bootPromise)
|
|
217
|
+
return this.bootPromise;
|
|
218
|
+
this.bootPromise = this.performBootAndRotate();
|
|
219
|
+
try {
|
|
220
|
+
return await this.bootPromise;
|
|
221
|
+
}
|
|
222
|
+
catch (err) {
|
|
223
|
+
this.bootPromise = null;
|
|
224
|
+
throw err;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
async performBootAndRotate() {
|
|
228
|
+
const persisted = this.readPersistedState();
|
|
229
|
+
if (!this.rawSlipUrl || !this.rawSlipUrl.trim()) {
|
|
230
|
+
if (persisted?.activeSlipId && persisted.activeClaimPrivateKey) {
|
|
231
|
+
const onChain = await readOnChainSlip({
|
|
232
|
+
publicClient: this.publicClient,
|
|
233
|
+
slipId: persisted.activeSlipId,
|
|
234
|
+
vault: persisted.vault,
|
|
235
|
+
});
|
|
236
|
+
if (onChain.status === SlipStatus.ACTIVE &&
|
|
237
|
+
persisted.activeClaimSigner &&
|
|
238
|
+
onChain.claimSigner.toLowerCase() === persisted.activeClaimSigner.toLowerCase()) {
|
|
239
|
+
this.activeSlipId = persisted.activeSlipId;
|
|
240
|
+
this.activeVault = persisted.vault;
|
|
241
|
+
this.activeAsset = onChain.asset;
|
|
242
|
+
this.activeClaimPrivateKey = persisted.activeClaimPrivateKey;
|
|
243
|
+
this.activeClaimSigner = persisted.activeClaimSigner;
|
|
244
|
+
this.bootRotated = persisted.bootRotated;
|
|
245
|
+
this.bootRotationTxHash = persisted.bootRotationTxHash;
|
|
246
|
+
this.initialized = true;
|
|
247
|
+
return {
|
|
248
|
+
bootRotated: false,
|
|
249
|
+
resumedFromLocalState: true,
|
|
250
|
+
slipId: this.activeSlipId,
|
|
251
|
+
vault: this.activeVault,
|
|
252
|
+
asset: this.activeAsset,
|
|
253
|
+
balanceUnits: onChain.amount.toString(),
|
|
254
|
+
humanBalance: formatUnits(onChain.amount, decimalsForAsset(onChain.asset)),
|
|
255
|
+
activeClaimSigner: this.activeClaimSigner,
|
|
256
|
+
operatorAddress: this.operatorAddress,
|
|
257
|
+
...(this.bootRotationTxHash ? { bootRotationTxHash: this.bootRotationTxHash } : {}),
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
this.initialized = true;
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
const parsed = parseSlipUrl(this.rawSlipUrl);
|
|
265
|
+
if (!parsed || parsed.mode !== 'open' || !parsed.claimKey || !parsed.claimAddress) {
|
|
266
|
+
throw new PocketSlipError('CRYPTOSLIP_URL must be an open #startapp=slip_... URL carrying a # fragment claim key.');
|
|
267
|
+
}
|
|
268
|
+
const lineageHash = keccak256(stringToHex(`${parsed.vault}:${parsed.id}`));
|
|
269
|
+
this.originalLineageHash = lineageHash;
|
|
270
|
+
// 1. Resume from local 0600 rotated state if matching lineage and still active on-chain
|
|
271
|
+
if (persisted &&
|
|
272
|
+
persisted.originalLineageHash === lineageHash &&
|
|
273
|
+
persisted.activeSlipId &&
|
|
274
|
+
persisted.activeClaimPrivateKey &&
|
|
275
|
+
persisted.activeClaimSigner) {
|
|
276
|
+
const resumedSlip = await readOnChainSlip({
|
|
277
|
+
publicClient: this.publicClient,
|
|
278
|
+
slipId: persisted.activeSlipId,
|
|
279
|
+
vault: persisted.vault,
|
|
280
|
+
});
|
|
281
|
+
if (resumedSlip.status === SlipStatus.ACTIVE &&
|
|
282
|
+
resumedSlip.claimSigner.toLowerCase() === persisted.activeClaimSigner.toLowerCase()) {
|
|
283
|
+
this.activeSlipId = persisted.activeSlipId;
|
|
284
|
+
this.activeVault = persisted.vault;
|
|
285
|
+
this.activeAsset = resumedSlip.asset;
|
|
286
|
+
this.activeClaimPrivateKey = persisted.activeClaimPrivateKey;
|
|
287
|
+
this.activeClaimSigner = persisted.activeClaimSigner;
|
|
288
|
+
this.bootRotated = persisted.bootRotated;
|
|
289
|
+
this.bootRotationTxHash = persisted.bootRotationTxHash;
|
|
290
|
+
this.initialized = true;
|
|
291
|
+
return {
|
|
292
|
+
bootRotated: false,
|
|
293
|
+
resumedFromLocalState: true,
|
|
294
|
+
slipId: this.activeSlipId,
|
|
295
|
+
vault: this.activeVault,
|
|
296
|
+
asset: this.activeAsset,
|
|
297
|
+
balanceUnits: resumedSlip.amount.toString(),
|
|
298
|
+
humanBalance: formatUnits(resumedSlip.amount, decimalsForAsset(resumedSlip.asset)),
|
|
299
|
+
activeClaimSigner: this.activeClaimSigner,
|
|
300
|
+
operatorAddress: this.operatorAddress,
|
|
301
|
+
...(this.bootRotationTxHash ? { bootRotationTxHash: this.bootRotationTxHash } : {}),
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
// 2. Inspect initial slip on Base
|
|
306
|
+
const initialOnChain = await readOnChainSlip({
|
|
307
|
+
publicClient: this.publicClient,
|
|
308
|
+
slipId: parsed.id,
|
|
309
|
+
vault: parsed.vault,
|
|
310
|
+
});
|
|
311
|
+
if (initialOnChain.status !== SlipStatus.ACTIVE) {
|
|
312
|
+
throw new PocketSlipError(`PocketSlip #${parsed.id} is not active on Base (status=${initialOnChain.status}).`);
|
|
313
|
+
}
|
|
314
|
+
if (initialOnChain.claimSigner.toLowerCase() !== parsed.claimAddress.toLowerCase()) {
|
|
315
|
+
throw new PocketSlipError(`PocketSlip #${parsed.id} claimSigner on-chain does not match CRYPTOSLIP_URL (already rotated by another host).`);
|
|
316
|
+
}
|
|
317
|
+
// 3. V-01 Mandatory Boot Auto-Keep when slip is unrotated (`nonces == 0`)
|
|
318
|
+
if (initialOnChain.nonce === 0n && !initialOnChain.refundFeeRequired) {
|
|
319
|
+
const guardedInitialSigner = createPolicyGuardedSigner(createSlipSignerFromKey(parsed.claimKey), this.policy, { slipAsset: initialOnChain.asset });
|
|
320
|
+
const kept = await keepSlip({
|
|
321
|
+
publicClient: this.publicClient,
|
|
322
|
+
slipId: parsed.id,
|
|
323
|
+
vault: parsed.vault,
|
|
324
|
+
claimSigner: guardedInitialSigner,
|
|
325
|
+
userMainWallet: this.operatorAddress,
|
|
326
|
+
mode: 'agent',
|
|
327
|
+
isBootKeep: true,
|
|
328
|
+
mutex: this.mutex,
|
|
329
|
+
...this.transportOverrides,
|
|
330
|
+
onBeforeBroadcast: ({ newClaimPrivateKey, newClaimSigner }) => {
|
|
331
|
+
this.activeSlipId = parsed.id;
|
|
332
|
+
this.activeVault = parsed.vault;
|
|
333
|
+
this.activeAsset = initialOnChain.asset;
|
|
334
|
+
this.activeClaimPrivateKey = newClaimPrivateKey;
|
|
335
|
+
this.activeClaimSigner = newClaimSigner;
|
|
336
|
+
this.bootRotated = true;
|
|
337
|
+
this.syncStateToDisk();
|
|
338
|
+
},
|
|
339
|
+
});
|
|
340
|
+
this.activeSlipId = kept.slipId.toString();
|
|
341
|
+
this.activeVault = kept.vault;
|
|
342
|
+
this.activeAsset = initialOnChain.asset;
|
|
343
|
+
this.activeClaimPrivateKey = kept.newClaimPrivateKey;
|
|
344
|
+
this.activeClaimSigner = kept.newClaimSigner;
|
|
345
|
+
this.bootRotated = true;
|
|
346
|
+
this.bootRotationTxHash = kept.txHash;
|
|
347
|
+
this.initialized = true;
|
|
348
|
+
this.syncStateToDisk();
|
|
349
|
+
return {
|
|
350
|
+
bootRotated: true,
|
|
351
|
+
resumedFromLocalState: false,
|
|
352
|
+
slipId: this.activeSlipId,
|
|
353
|
+
vault: this.activeVault,
|
|
354
|
+
asset: this.activeAsset,
|
|
355
|
+
balanceUnits: kept.netAmountUnits.toString(),
|
|
356
|
+
humanBalance: formatUnits(kept.netAmountUnits, decimalsForAsset(initialOnChain.asset)),
|
|
357
|
+
activeClaimSigner: this.activeClaimSigner,
|
|
358
|
+
operatorAddress: this.operatorAddress,
|
|
359
|
+
bootRotationTxHash: kept.txHash,
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
// Already rotated (`nonces > 0`) to the key supplied in CRYPTOSLIP_URL
|
|
363
|
+
this.activeSlipId = parsed.id;
|
|
364
|
+
this.activeVault = parsed.vault;
|
|
365
|
+
this.activeAsset = initialOnChain.asset;
|
|
366
|
+
this.activeClaimPrivateKey = parsed.claimKey;
|
|
367
|
+
this.activeClaimSigner = parsed.claimAddress;
|
|
368
|
+
this.bootRotated = false;
|
|
369
|
+
this.initialized = true;
|
|
370
|
+
this.syncStateToDisk();
|
|
371
|
+
return {
|
|
372
|
+
bootRotated: false,
|
|
373
|
+
resumedFromLocalState: false,
|
|
374
|
+
slipId: this.activeSlipId,
|
|
375
|
+
vault: this.activeVault,
|
|
376
|
+
asset: this.activeAsset,
|
|
377
|
+
balanceUnits: initialOnChain.amount.toString(),
|
|
378
|
+
humanBalance: formatUnits(initialOnChain.amount, decimalsForAsset(initialOnChain.asset)),
|
|
379
|
+
activeClaimSigner: this.activeClaimSigner,
|
|
380
|
+
operatorAddress: this.operatorAddress,
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
async ensureBooted() {
|
|
384
|
+
if (!this.initialized) {
|
|
385
|
+
await this.bootAndRotate();
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Tool #1: `cryptoslip_status` — Safe redacted slip/wallet balance, vault `v33`, and policy limits.
|
|
390
|
+
*/
|
|
391
|
+
async getStatus() {
|
|
392
|
+
await this.ensureBooted();
|
|
393
|
+
let balanceUnits = '0';
|
|
394
|
+
let humanBalance = '0';
|
|
395
|
+
if (this.activeSlipId) {
|
|
396
|
+
const state = await readOnChainSlip({
|
|
397
|
+
publicClient: this.publicClient,
|
|
398
|
+
slipId: this.activeSlipId,
|
|
399
|
+
vault: this.activeVault,
|
|
400
|
+
});
|
|
401
|
+
if (state.status === SlipStatus.ACTIVE) {
|
|
402
|
+
balanceUnits = state.amount.toString();
|
|
403
|
+
humanBalance = formatUnits(state.amount, decimalsForAsset(state.asset));
|
|
404
|
+
this.activeAsset = state.asset;
|
|
405
|
+
}
|
|
406
|
+
else {
|
|
407
|
+
this.activeSlipId = null;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
const rawSummary = {
|
|
411
|
+
initialized: this.initialized,
|
|
412
|
+
hasActivePocketSlip: Boolean(this.activeSlipId),
|
|
413
|
+
chainId: 8453,
|
|
414
|
+
vault: this.activeVault,
|
|
415
|
+
vaultAddress: CANONICAL_VAULT_V33_ADDRESS,
|
|
416
|
+
paymasterDefault: CIRCLE_TOKEN_PAYMASTER_V08_ADDRESS,
|
|
417
|
+
naraHookEnforced: NARA_LIQUIDITY_HOOK_V5_ADDRESS,
|
|
418
|
+
slipId: this.activeSlipId,
|
|
419
|
+
asset: this.activeSlipId ? this.activeAsset : null,
|
|
420
|
+
balanceUnits,
|
|
421
|
+
humanBalance,
|
|
422
|
+
bootRotated: this.bootRotated,
|
|
423
|
+
...(this.bootRotationTxHash ? { bootRotationTxHash: this.bootRotationTxHash } : {}),
|
|
424
|
+
activeClaimSigner: this.activeClaimSigner ?? null,
|
|
425
|
+
operatorAddress: this.operatorAddress,
|
|
426
|
+
trackedRevocableSlipIds: [...this.createdRevocableSlipIds],
|
|
427
|
+
policy: this.policy.getSnapshot(),
|
|
428
|
+
};
|
|
429
|
+
return this.policy.redactOutput(rawSummary, {
|
|
430
|
+
allowedPublicHashFields: ['bootRotationTxHash'],
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Tool #2: `cryptoslip_pay_human` — Mints or splits a `No take-back` or revocable `#startapp=slip_...`
|
|
435
|
+
* link (or 12-char `scrypt` code) for X/Telegram/SMS human bounties.
|
|
436
|
+
*/
|
|
437
|
+
async payHuman(input) {
|
|
438
|
+
await this.ensureBooted();
|
|
439
|
+
this.policy.assertCanEmitOutboundSlipLink();
|
|
440
|
+
const asset = normalizeSdkAsset(input.asset ?? this.activeAsset ?? 'USDC');
|
|
441
|
+
const requestedUnits = parseAmountUnits(input.amount, asset, input.amountIsAtomic);
|
|
442
|
+
const grossMintUnits = input.grossUpForExitFee
|
|
443
|
+
? grossUpForExactNet(requestedUnits)
|
|
444
|
+
: requestedUnits;
|
|
445
|
+
const minUnits = minSlipAmount(asset, this.activeVault);
|
|
446
|
+
if (grossMintUnits < minUnits) {
|
|
447
|
+
throw new PocketSlipError(`Amount ${grossMintUnits.toString()} raw ${asset} is below ${this.activeVault} minimum (${minUnits.toString()}).`);
|
|
448
|
+
}
|
|
449
|
+
let splitTxHash;
|
|
450
|
+
// If operating from an active PocketSlip without an externally funded walletClient,
|
|
451
|
+
// split the required funding slice from the PocketSlip into operatorAddress first,
|
|
452
|
+
// then mint the recipient's slip via Circle TokenPaymasterV08 / batch executor.
|
|
453
|
+
if (this.activeSlipId && this.activeClaimPrivateKey && !this.walletClient) {
|
|
454
|
+
let targetNetToOperator = grossMintUnits;
|
|
455
|
+
if (asset === 'USDC' && this.activeAsset === 'USDC') {
|
|
456
|
+
let operatorUsdc = null;
|
|
457
|
+
try {
|
|
458
|
+
const rawBal = await this.publicClient.readContract({
|
|
459
|
+
address: USDC_BASE_ADDRESS,
|
|
460
|
+
abi: ERC20_PERMIT_EIP3009_ABI,
|
|
461
|
+
functionName: 'balanceOf',
|
|
462
|
+
args: [this.operatorAddress],
|
|
463
|
+
});
|
|
464
|
+
if (typeof rawBal === 'bigint')
|
|
465
|
+
operatorUsdc = rawBal;
|
|
466
|
+
}
|
|
467
|
+
catch {
|
|
468
|
+
operatorUsdc = null;
|
|
469
|
+
}
|
|
470
|
+
if (operatorUsdc !== null && operatorUsdc < MIN_CIRCLE_PAYMASTER_USDC_UNITS) {
|
|
471
|
+
const gasDeficit = MIN_CIRCLE_PAYMASTER_USDC_UNITS - operatorUsdc;
|
|
472
|
+
const candidateFunding = grossUpForExactNet(grossMintUnits + gasDeficit);
|
|
473
|
+
const slipState = await readOnChainSlip({
|
|
474
|
+
publicClient: this.publicClient,
|
|
475
|
+
slipId: this.activeSlipId,
|
|
476
|
+
vault: this.activeVault,
|
|
477
|
+
});
|
|
478
|
+
const rem = slipState.amount - candidateFunding;
|
|
479
|
+
const fitsWithoutDust = rem === 0n || rem >= minSlipAmount(slipState.asset, this.activeVault);
|
|
480
|
+
const fitsPerCallCap = estimateUsdMicro(candidateFunding, slipState.asset) <=
|
|
481
|
+
this.policy.maxPerCallUsdMicro;
|
|
482
|
+
if (slipState.amount >= candidateFunding && fitsWithoutDust && fitsPerCallCap) {
|
|
483
|
+
targetNetToOperator = grossMintUnits + gasDeficit;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
const fundingNeeded = grossUpForExactNet(targetNetToOperator);
|
|
488
|
+
const guardedPocketSigner = createPolicyGuardedSigner(createSlipSignerFromKey(this.activeClaimPrivateKey), this.policy, {
|
|
489
|
+
slipAsset: this.activeAsset,
|
|
490
|
+
allowInternalRecipient: this.operatorAddress,
|
|
491
|
+
});
|
|
492
|
+
const splitRes = await splitAndPay({
|
|
493
|
+
publicClient: this.publicClient,
|
|
494
|
+
slipId: this.activeSlipId,
|
|
495
|
+
vault: this.activeVault,
|
|
496
|
+
claimSigner: guardedPocketSigner,
|
|
497
|
+
paymentAmount: fundingNeeded,
|
|
498
|
+
merchant: this.operatorAddress,
|
|
499
|
+
mode: 'agent',
|
|
500
|
+
paymasterSignerKey: this.operatorPrivateKey,
|
|
501
|
+
mutex: this.mutex,
|
|
502
|
+
...this.transportOverrides,
|
|
503
|
+
onBeforeBroadcast: ({ newChangePrivateKey, newChangeSigner, expectedChangeAmount }) => {
|
|
504
|
+
if (expectedChangeAmount > 0n && newChangePrivateKey) {
|
|
505
|
+
this.activeClaimPrivateKey = newChangePrivateKey;
|
|
506
|
+
this.activeClaimSigner = newChangeSigner;
|
|
507
|
+
this.syncStateToDisk();
|
|
508
|
+
}
|
|
509
|
+
},
|
|
510
|
+
});
|
|
511
|
+
splitTxHash = splitRes.txHash;
|
|
512
|
+
if (splitRes.changeAmount > 0n && splitRes.changeSlipId !== null && splitRes.newChangePrivateKey) {
|
|
513
|
+
this.activeSlipId = splitRes.changeSlipId.toString();
|
|
514
|
+
this.activeClaimPrivateKey = splitRes.newChangePrivateKey;
|
|
515
|
+
this.activeClaimSigner = splitRes.newChangeSigner;
|
|
516
|
+
}
|
|
517
|
+
else if (splitRes.changeAmount === 0n) {
|
|
518
|
+
this.activeSlipId = null;
|
|
519
|
+
this.activeClaimPrivateKey = undefined;
|
|
520
|
+
this.activeClaimSigner = undefined;
|
|
521
|
+
}
|
|
522
|
+
this.syncStateToDisk();
|
|
523
|
+
}
|
|
524
|
+
else {
|
|
525
|
+
// Wallet-funded path: enforce policy spend cap on the guarded operator signer
|
|
526
|
+
this.policy.authorizeAndRecordSpend({
|
|
527
|
+
amount: grossMintUnits,
|
|
528
|
+
asset,
|
|
529
|
+
dedupKey: `pay_human:${Date.now()}:${grossMintUnits.toString()}`,
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
const signerForMint = this.walletClient
|
|
533
|
+
? fromViemWalletClient(this.walletClient)
|
|
534
|
+
: createSlipSignerFromKey(this.operatorPrivateKey);
|
|
535
|
+
const batchRes = await this.customBatchExecutor({
|
|
536
|
+
publicClient: this.publicClient,
|
|
537
|
+
...(this.walletClient ? { walletClient: this.walletClient } : {}),
|
|
538
|
+
signer: signerForMint,
|
|
539
|
+
paymasterSignerKey: this.operatorPrivateKey,
|
|
540
|
+
useCirclePaymaster: !this.walletClient,
|
|
541
|
+
bundlerUrls: this.transportOverrides.bundlerUrls,
|
|
542
|
+
bundlerFetch: this.transportOverrides.bundlerFetch,
|
|
543
|
+
vault: this.activeVault,
|
|
544
|
+
items: [
|
|
545
|
+
{
|
|
546
|
+
amount: grossMintUnits,
|
|
547
|
+
asset,
|
|
548
|
+
noTakeBack: Boolean(input.noTakeBack),
|
|
549
|
+
grossUpForExitFee: false,
|
|
550
|
+
mode: input.mode ?? 'open',
|
|
551
|
+
note: input.note,
|
|
552
|
+
recipientRef: input.recipientLabel,
|
|
553
|
+
},
|
|
554
|
+
],
|
|
555
|
+
});
|
|
556
|
+
const minted = batchRes.mintedSlips[0];
|
|
557
|
+
if (!minted) {
|
|
558
|
+
throw new PocketSlipError('Batch mint succeeded without returning a minted slip record.');
|
|
559
|
+
}
|
|
560
|
+
if (!input.noTakeBack) {
|
|
561
|
+
this.createdRevocableSlipIds.push(minted.slipId);
|
|
562
|
+
this.syncStateToDisk();
|
|
563
|
+
}
|
|
564
|
+
const out = {
|
|
565
|
+
slipId: minted.slipId,
|
|
566
|
+
vault: minted.vault,
|
|
567
|
+
asset: minted.asset,
|
|
568
|
+
humanAmount: minted.humanAmount,
|
|
569
|
+
grossAmountUnits: minted.grossAmountUnits,
|
|
570
|
+
guaranteedNetClaimUnits: minted.guaranteedNetClaimUnits,
|
|
571
|
+
mode: minted.mode,
|
|
572
|
+
noTakeBack: Boolean(input.noTakeBack),
|
|
573
|
+
outboundSlipUrl: minted.url,
|
|
574
|
+
...(minted.claimCode ? { claimCode: minted.claimCode } : {}),
|
|
575
|
+
txHash: minted.txHash,
|
|
576
|
+
...(splitTxHash ? { splitTxHash } : {}),
|
|
577
|
+
deliveryNotice: minted.mode === 'code'
|
|
578
|
+
? 'Send outboundSlipUrl and the 12-character claimCode over separate channels (or release claimCode upon task verification).'
|
|
579
|
+
: 'Deliver outboundSlipUrl strictly inside a private DM (Telegram, X DM, or SMS). Never post open # links in public timelines.',
|
|
580
|
+
};
|
|
581
|
+
return this.policy.redactOutput(out, {
|
|
582
|
+
allowOutboundSlipLink: true,
|
|
583
|
+
outboundFields: ['outboundSlipUrl'],
|
|
584
|
+
allowedPublicHashFields: ['txHash', 'splitTxHash'],
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Tool #3: `cryptoslip_batch_payout` — 1-Tx `Multicall3` batch dispenser (`1..500` items) returning JSON/CSV `#` links.
|
|
589
|
+
*/
|
|
590
|
+
async batchPayout(input) {
|
|
591
|
+
await this.ensureBooted();
|
|
592
|
+
this.policy.assertCanEmitOutboundSlipLink();
|
|
593
|
+
if (!input.items || input.items.length === 0 || input.items.length > 500) {
|
|
594
|
+
throw new PocketSlipError('batchPayout requires between 1 and 500 items.');
|
|
595
|
+
}
|
|
596
|
+
const normalizedItems = [];
|
|
597
|
+
let totalUsdMicro = 0n;
|
|
598
|
+
for (const rawItem of input.items) {
|
|
599
|
+
const asset = normalizeSdkAsset(rawItem.asset ?? 'USDC');
|
|
600
|
+
const units = parseAmountUnits(rawItem.amount, asset, rawItem.amountIsAtomic);
|
|
601
|
+
const grossUnits = rawItem.grossUpForExitFee ? grossUpForExactNet(units) : units;
|
|
602
|
+
totalUsdMicro += estimateUsdMicro(grossUnits, asset);
|
|
603
|
+
normalizedItems.push({
|
|
604
|
+
amount: grossUnits,
|
|
605
|
+
asset,
|
|
606
|
+
noTakeBack: Boolean(rawItem.noTakeBack),
|
|
607
|
+
grossUpForExitFee: false,
|
|
608
|
+
mode: rawItem.mode ?? 'open',
|
|
609
|
+
note: rawItem.note,
|
|
610
|
+
recipientRef: rawItem.recipientRef,
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
// Enforce aggregate batch USD budget & rate limit BEFORE signing any permit
|
|
614
|
+
this.policy.authorizeAndRecordSpend({
|
|
615
|
+
amount: totalUsdMicro,
|
|
616
|
+
asset: 'USDC',
|
|
617
|
+
dedupKey: `batch:${Date.now()}:${normalizedItems.length}`,
|
|
618
|
+
});
|
|
619
|
+
const signerForBatch = this.walletClient
|
|
620
|
+
? fromViemWalletClient(this.walletClient)
|
|
621
|
+
: createSlipSignerFromKey(this.operatorPrivateKey);
|
|
622
|
+
const batchRes = await this.customBatchExecutor({
|
|
623
|
+
publicClient: this.publicClient,
|
|
624
|
+
...(this.walletClient ? { walletClient: this.walletClient } : {}),
|
|
625
|
+
signer: signerForBatch,
|
|
626
|
+
paymasterSignerKey: this.operatorPrivateKey,
|
|
627
|
+
useCirclePaymaster: !this.walletClient,
|
|
628
|
+
bundlerUrls: this.transportOverrides.bundlerUrls,
|
|
629
|
+
bundlerFetch: this.transportOverrides.bundlerFetch,
|
|
630
|
+
vault: this.activeVault,
|
|
631
|
+
items: normalizedItems,
|
|
632
|
+
});
|
|
633
|
+
for (const m of batchRes.mintedSlips) {
|
|
634
|
+
if (m.cancelLockedUntil === 0) {
|
|
635
|
+
this.createdRevocableSlipIds.push(m.slipId);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
this.syncStateToDisk();
|
|
639
|
+
const fmt = input.format ?? 'json';
|
|
640
|
+
const rawOut = {
|
|
641
|
+
count: batchRes.mintedSlips.length,
|
|
642
|
+
txHashes: batchRes.txHashes,
|
|
643
|
+
...(fmt === 'json' || fmt === 'both' ? { outboundLinks: batchRes.mintedSlips } : {}),
|
|
644
|
+
...(fmt === 'csv' || fmt === 'both' ? { outboundCsv: batchRes.csv } : {}),
|
|
645
|
+
};
|
|
646
|
+
return this.policy.redactOutput(rawOut, {
|
|
647
|
+
allowOutboundSlipLink: true,
|
|
648
|
+
outboundFields: ['outboundLinks', 'outboundCsv', 'url', 'sovereignUrl'],
|
|
649
|
+
allowedPublicHashFields: ['txHashes', 'txHash'],
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* Tool #4: `cryptoslip_pay_x402_or_merchant` — `splitAndPay` with `BoundedAgentPolicy` (`V-02`),
|
|
654
|
+
* `SlipMutex` + `$0.10` dust guard (`V-03`), and Circle `TokenPaymasterV08` default (`V-04`).
|
|
655
|
+
*/
|
|
656
|
+
async payMerchantOrX402(input) {
|
|
657
|
+
await this.ensureBooted();
|
|
658
|
+
if (!this.activeSlipId || !this.activeClaimPrivateKey) {
|
|
659
|
+
throw new PocketSlipError('No active PocketSlip available. Provision CRYPTOSLIP_URL with an active slip first.');
|
|
660
|
+
}
|
|
661
|
+
if (input.endpointUrl) {
|
|
662
|
+
this.policy.assertAllowedDomain(input.endpointUrl);
|
|
663
|
+
}
|
|
664
|
+
const merchant = resolveMerchantAddress(input.recipient);
|
|
665
|
+
this.policy.assertSafeDestination(merchant, this.activeClaimSigner);
|
|
666
|
+
const paymentAmount = parseAmountUnits(input.amount, this.activeAsset, input.amountIsAtomic);
|
|
667
|
+
// Pre-wrap active slip signer with BoundedAgentPolicy so SplitPermit signature
|
|
668
|
+
// enforces maxPerCallUsdMicro, maxSpendsPerMinute, maxDailyUsdMicro, and destination rules!
|
|
669
|
+
const guardedSlipSigner = createPolicyGuardedSigner(createSlipSignerFromKey(this.activeClaimPrivateKey), this.policy, { slipAsset: this.activeAsset });
|
|
670
|
+
const res = await splitAndPay({
|
|
671
|
+
publicClient: this.publicClient,
|
|
672
|
+
slipId: this.activeSlipId,
|
|
673
|
+
vault: this.activeVault,
|
|
674
|
+
claimSigner: guardedSlipSigner,
|
|
675
|
+
paymentAmount,
|
|
676
|
+
merchant,
|
|
677
|
+
allowFullCashOnDust: Boolean(input.allowFullCashOnDust),
|
|
678
|
+
mode: 'agent', // V-04: defaults headless agent to Circle TokenPaymasterV08 / direct Base tx
|
|
679
|
+
paymasterSignerKey: this.operatorPrivateKey,
|
|
680
|
+
...(this.walletClient ? { walletClient: this.walletClient } : {}),
|
|
681
|
+
mutex: this.mutex,
|
|
682
|
+
...this.transportOverrides,
|
|
683
|
+
onBeforeBroadcast: ({ newChangePrivateKey, newChangeSigner, expectedChangeAmount }) => {
|
|
684
|
+
if (expectedChangeAmount > 0n && newChangePrivateKey) {
|
|
685
|
+
this.activeClaimPrivateKey = newChangePrivateKey;
|
|
686
|
+
this.activeClaimSigner = newChangeSigner;
|
|
687
|
+
this.syncStateToDisk();
|
|
688
|
+
}
|
|
689
|
+
},
|
|
690
|
+
});
|
|
691
|
+
if (res.changeAmount > 0n && res.changeSlipId !== null && res.newChangePrivateKey) {
|
|
692
|
+
this.activeSlipId = res.changeSlipId.toString();
|
|
693
|
+
this.activeClaimPrivateKey = res.newChangePrivateKey;
|
|
694
|
+
this.activeClaimSigner = res.newChangeSigner;
|
|
695
|
+
}
|
|
696
|
+
else if (res.changeAmount === 0n) {
|
|
697
|
+
this.activeSlipId = null;
|
|
698
|
+
this.activeClaimPrivateKey = undefined;
|
|
699
|
+
this.activeClaimSigner = undefined;
|
|
700
|
+
}
|
|
701
|
+
this.syncStateToDisk();
|
|
702
|
+
const summary = {
|
|
703
|
+
txHash: res.txHash,
|
|
704
|
+
parentSlipId: res.parentSlipId.toString(),
|
|
705
|
+
newActiveSlipId: res.changeSlipId !== null ? res.changeSlipId.toString() : null,
|
|
706
|
+
merchant: res.merchant,
|
|
707
|
+
asset: res.asset,
|
|
708
|
+
grossPaymentUnits: res.grossPaymentAmount.toString(),
|
|
709
|
+
feeUnits: res.feeUnits.toString(),
|
|
710
|
+
netMerchantUnits: res.netMerchantAmount.toString(),
|
|
711
|
+
remainingChangeUnits: res.changeAmount.toString(),
|
|
712
|
+
transportTier: res.transportTier,
|
|
713
|
+
};
|
|
714
|
+
return this.policy.redactOutput(summary, {
|
|
715
|
+
allowedPublicHashFields: ['txHash'],
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
/**
|
|
719
|
+
* Tool #5: `cryptoslip_verify_or_export_receipt` — Verifies or generates `PaymentReceiptBundleV1`.
|
|
720
|
+
*/
|
|
721
|
+
async verifyOrExportReceipt(input) {
|
|
722
|
+
if (input.action === 'verify') {
|
|
723
|
+
const verification = await verifyPaymentReceiptOnChain(this.publicClient, input.bundle, input.options);
|
|
724
|
+
return redactSecretsFromToolOutput({
|
|
725
|
+
action: 'verify',
|
|
726
|
+
valid: verification.valid,
|
|
727
|
+
reason: verification.reason,
|
|
728
|
+
verifiedNetAmount: verification.verifiedNetAmount?.toString(),
|
|
729
|
+
verifiedGrossAmount: verification.verifiedGrossAmount?.toString(),
|
|
730
|
+
verifiedFeeAmount: verification.verifiedFeeAmount?.toString(),
|
|
731
|
+
blockNumber: verification.blockNumber,
|
|
732
|
+
blockTimestamp: verification.blockTimestamp,
|
|
733
|
+
issuerVerified: verification.issuerVerified,
|
|
734
|
+
builderCodePresent: verification.builderCodePresent,
|
|
735
|
+
}, { allowedPublicHashFields: ['txHash', 'orderDigest'] });
|
|
736
|
+
}
|
|
737
|
+
const signer = input.signWithOperatorKey
|
|
738
|
+
? createPolicyGuardedSigner(createSlipSignerFromKey(this.operatorPrivateKey), this.policy)
|
|
739
|
+
: undefined;
|
|
740
|
+
const bundle = await createSignedPaymentReceipt({
|
|
741
|
+
...input.receiptInput,
|
|
742
|
+
...(signer ? { signer } : {}),
|
|
743
|
+
});
|
|
744
|
+
const out = {
|
|
745
|
+
action: 'export',
|
|
746
|
+
bundle,
|
|
747
|
+
...(input.includeCsv ? { csvRow: formatReceiptCsvRow(bundle) } : {}),
|
|
748
|
+
...(input.includeHtml ? { html: renderPrintableReceiptHtml(bundle) } : {}),
|
|
749
|
+
};
|
|
750
|
+
return redactSecretsFromToolOutput(out, {
|
|
751
|
+
allowedPublicHashFields: ['txHash', 'orderDigest'],
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* Tool #6: `cryptoslip_reclaim_unclaimed` — `0%`-fee `refundSlipDirect` for unclaimed `cancelLockedUntil == 0` DM slips.
|
|
756
|
+
*/
|
|
757
|
+
async reclaimUnclaimed(input) {
|
|
758
|
+
await this.ensureBooted();
|
|
759
|
+
if (input.scanOnly || !input.slipId) {
|
|
760
|
+
const reclaimable = await scanReclaimableSlips({
|
|
761
|
+
publicClient: this.publicClient,
|
|
762
|
+
creator: this.operatorAddress,
|
|
763
|
+
vault: this.activeVault,
|
|
764
|
+
...(this.createdRevocableSlipIds.length > 0
|
|
765
|
+
? { candidateSlipIds: this.createdRevocableSlipIds }
|
|
766
|
+
: {}),
|
|
767
|
+
minAgeSeconds: input.minAgeSeconds ?? 0,
|
|
768
|
+
});
|
|
769
|
+
if (input.scanOnly || reclaimable.length === 0) {
|
|
770
|
+
return this.policy.redactOutput({
|
|
771
|
+
mode: 'scan',
|
|
772
|
+
reclaimableCount: reclaimable.length,
|
|
773
|
+
reclaimable: reclaimable.map((r) => ({
|
|
774
|
+
slipId: r.slipId.toString(),
|
|
775
|
+
vault: r.vault,
|
|
776
|
+
asset: r.asset,
|
|
777
|
+
amountUnits: r.amount.toString(),
|
|
778
|
+
ageSeconds: r.ageSeconds,
|
|
779
|
+
})),
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
// Reclaim the first discovered slip if slipId wasn't explicitly specified and scanOnly is false
|
|
783
|
+
const target = reclaimable[0];
|
|
784
|
+
const refunded = await refundSlipDirect({
|
|
785
|
+
publicClient: this.publicClient,
|
|
786
|
+
slipId: target.slipId,
|
|
787
|
+
vault: target.vault,
|
|
788
|
+
...(this.walletClient ? { walletClient: this.walletClient } : {}),
|
|
789
|
+
paymasterSignerKey: this.operatorPrivateKey,
|
|
790
|
+
useCirclePaymaster: !this.walletClient,
|
|
791
|
+
bundlerUrls: this.transportOverrides.bundlerUrls,
|
|
792
|
+
bundlerFetch: this.transportOverrides.bundlerFetch,
|
|
793
|
+
mutex: this.mutex,
|
|
794
|
+
});
|
|
795
|
+
this.createdRevocableSlipIds = this.createdRevocableSlipIds.filter((id) => id !== target.slipId.toString());
|
|
796
|
+
this.syncStateToDisk();
|
|
797
|
+
return this.policy.redactOutput({
|
|
798
|
+
mode: 'reclaimed',
|
|
799
|
+
txHash: refunded.txHash,
|
|
800
|
+
slipId: refunded.slipId.toString(),
|
|
801
|
+
vault: refunded.vault,
|
|
802
|
+
asset: refunded.asset,
|
|
803
|
+
refundedAmountUnits: refunded.refundedAmountUnits.toString(),
|
|
804
|
+
feeUnits: '0',
|
|
805
|
+
transportTier: refunded.transportTier,
|
|
806
|
+
}, { allowedPublicHashFields: ['txHash'] });
|
|
807
|
+
}
|
|
808
|
+
const refunded = await refundSlipDirect({
|
|
809
|
+
publicClient: this.publicClient,
|
|
810
|
+
slipId: input.slipId,
|
|
811
|
+
vault: this.activeVault,
|
|
812
|
+
...(this.walletClient ? { walletClient: this.walletClient } : {}),
|
|
813
|
+
paymasterSignerKey: this.operatorPrivateKey,
|
|
814
|
+
useCirclePaymaster: !this.walletClient,
|
|
815
|
+
bundlerUrls: this.transportOverrides.bundlerUrls,
|
|
816
|
+
bundlerFetch: this.transportOverrides.bundlerFetch,
|
|
817
|
+
mutex: this.mutex,
|
|
818
|
+
});
|
|
819
|
+
this.createdRevocableSlipIds = this.createdRevocableSlipIds.filter((id) => id !== refunded.slipId.toString());
|
|
820
|
+
this.syncStateToDisk();
|
|
821
|
+
return this.policy.redactOutput({
|
|
822
|
+
mode: 'reclaimed',
|
|
823
|
+
txHash: refunded.txHash,
|
|
824
|
+
slipId: refunded.slipId.toString(),
|
|
825
|
+
vault: refunded.vault,
|
|
826
|
+
asset: refunded.asset,
|
|
827
|
+
refundedAmountUnits: refunded.refundedAmountUnits.toString(),
|
|
828
|
+
feeUnits: '0',
|
|
829
|
+
transportTier: refunded.transportTier,
|
|
830
|
+
}, { allowedPublicHashFields: ['txHash'] });
|
|
831
|
+
}
|
|
832
|
+
/**
|
|
833
|
+
* Tool #7: `cryptoslip_withdraw_referrals` — Claims `0.25%` lifetime `referralCredits` on Base.
|
|
834
|
+
*/
|
|
835
|
+
async withdrawReferrals(input) {
|
|
836
|
+
await this.ensureBooted();
|
|
837
|
+
const destination = input?.to
|
|
838
|
+
? this.policy.assertSafeDestination(input.to)
|
|
839
|
+
: this.operatorAddress;
|
|
840
|
+
const res = await withdrawReferralCredits({
|
|
841
|
+
publicClient: this.publicClient,
|
|
842
|
+
referrer: this.operatorAddress,
|
|
843
|
+
to: destination,
|
|
844
|
+
assets: input?.assets ?? ['USDC', 'cbBTC', 'ETH', 'NARA'],
|
|
845
|
+
vault: this.activeVault,
|
|
846
|
+
...(this.walletClient ? { walletClient: this.walletClient } : {}),
|
|
847
|
+
paymasterSignerKey: this.operatorPrivateKey,
|
|
848
|
+
useCirclePaymaster: !this.walletClient,
|
|
849
|
+
bundlerUrls: this.transportOverrides.bundlerUrls,
|
|
850
|
+
bundlerFetch: this.transportOverrides.bundlerFetch,
|
|
851
|
+
});
|
|
852
|
+
const formattedWithdrawn = {};
|
|
853
|
+
for (const [k, v] of Object.entries(res.withdrawnByAsset)) {
|
|
854
|
+
if (v !== undefined) {
|
|
855
|
+
formattedWithdrawn[k] = v.toString();
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
return redactSecretsFromToolOutput({
|
|
859
|
+
vault: res.vault,
|
|
860
|
+
referrer: res.referrer,
|
|
861
|
+
to: res.to,
|
|
862
|
+
withdrawnByAsset: formattedWithdrawn,
|
|
863
|
+
txHashes: res.txHashes,
|
|
864
|
+
}, { allowedPublicHashFields: ['txHashes'] });
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
//# sourceMappingURL=pocketSlip.js.map
|