/**
* MPP agent subscribe — subscribe to a plan (Startup/Growth/Enterprise, monthly/yearly).
*
* Usage:
* MPPX_PRIVATE_KEY=0x<key> bun run scripts/src/mpp/agent-subscribe.ts
*
* Optional env:
* API_URL (default: https://api.mobula.io)
* PLAN (default: growth)
* PAYMENT_FREQUENCY (default: yearly)
*/
import { createPublicClient, formatUnits, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
const API_URL = process.env.API_URL ?? 'https://api.mobula.io';
const PLAN = process.env.PLAN ?? 'growth';
const PAYMENT_FREQUENCY = process.env.PAYMENT_FREQUENCY ?? 'yearly';
const PATHUSD = '0x20c0000000000000000000000000000000000000' as const;
const PATHUSD_DECIMALS = 6;
const PRIVATE_KEY = process.env.MPPX_PRIVATE_KEY as `0x${string}` | undefined;
if (!PRIVATE_KEY) {
console.error('ERROR: Set MPPX_PRIVATE_KEY=0x<your_private_key>');
process.exit(1);
}
const payer = privateKeyToAccount(PRIVATE_KEY as `0x${string}`);
const client = createPublicClient({
chain: {
id: 42431,
name: 'Tempo Testnet',
nativeCurrency: { name: 'ETH', symbol: 'ETH', decimals: 18 },
rpcUrls: { default: { http: ['https://rpc.moderato.tempo.xyz'] } },
},
transport: http(),
});
const balanceOfAbi = [
{
type: 'function',
name: 'balanceOf',
inputs: [{ name: 'account', type: 'address' }],
outputs: [{ name: '', type: 'uint256' }],
stateMutability: 'view',
},
] as const;
async function getPathUsdBalance(address: `0x${string}`): Promise<bigint> {
return client.readContract({
address: PATHUSD,
abi: balanceOfAbi,
functionName: 'balanceOf',
args: [address],
});
}
function fmtBalance(raw: bigint): string {
return `${formatUnits(raw, PATHUSD_DECIMALS)} PathUSD`;
}
async function getRecipientFromChallenge(url: string): Promise<`0x${string}`> {
const res = await fetch(url);
const wwwAuth = res.headers.get('www-authenticate') || '';
const requestMatch = wwwAuth.match(/request="([^"]*)"/);
if (requestMatch) {
const decoded = JSON.parse(Buffer.from(requestMatch[1], 'base64').toString());
return decoded.recipient;
}
throw new Error('Could not parse recipient from challenge');
}
function mppxRequest(endpoint: string): string {
const { execSync } = require('child_process');
const result = execSync(`MPPX_PRIVATE_KEY=${PRIVATE_KEY} bunx mppx "${endpoint}" -v`, {
encoding: 'utf-8',
cwd: process.cwd(),
timeout: 60_000,
});
return result;
}
const subscribeUrl = `${API_URL}/agent/mpp/subscribe?plan=${encodeURIComponent(PLAN)}&payment_frequency=${encodeURIComponent(PAYMENT_FREQUENCY)}`;
const recipient = await getRecipientFromChallenge(subscribeUrl);
console.log('\n--- Addresses ---');
console.log(` Payer: ${payer.address}`);
console.log(` Recipient: ${recipient}`);
console.log('\n--- Step 1: Balances BEFORE payment ---\n');
const payerBefore = await getPathUsdBalance(payer.address);
const recipientBefore = await getPathUsdBalance(recipient);
console.log(` Payer: ${fmtBalance(payerBefore)}`);
console.log(` Recipient: ${fmtBalance(recipientBefore)}`);
console.log(`\n--- Step 2: Subscribe — Plan: ${PLAN}, Frequency: ${PAYMENT_FREQUENCY} ---\n`);
try {
const result = mppxRequest(subscribeUrl);
console.log(result);
} catch (err: unknown) {
const execErr = err as { stdout?: string; stderr?: string };
console.error('mppx CLI failed:');
if (execErr.stdout) console.log(execErr.stdout);
if (execErr.stderr) console.error(execErr.stderr);
process.exit(1);
}
console.log('--- Step 3: Balances AFTER payment ---\n');
const payerAfter = await getPathUsdBalance(payer.address);
const recipientAfter = await getPathUsdBalance(recipient);
console.log(` Payer: ${fmtBalance(payerAfter)}`);
console.log(` Recipient: ${fmtBalance(recipientAfter)}`);
console.log('\n--- Balance changes ---\n');
console.log(
` Payer: ${fmtBalance(payerBefore)} → ${fmtBalance(payerAfter)} (${fmtBalance(payerAfter - payerBefore)})`,
);
console.log(
` Recipient: ${fmtBalance(recipientBefore)} → ${fmtBalance(recipientAfter)} (+${fmtBalance(recipientAfter - recipientBefore)})`,
);
process.exit(0);