Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions scripts/check-cross-rail-v2.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -151,12 +151,12 @@ function encryptGrant({ prfBytes, sessionId, replyPubkey, index = 0, policy }) {
assert.ok(walletInst.includes("approval_url"));
assert.ok(!walletInst.includes("create_url"));
assert.ok(walletInst.includes("NEW request_id and a higher max_amount"));
assert.deepEqual(WALLET_TOOL.inputSchema.properties.action.enum, ["balance", "receive", "pay", "history"]);
assert.deepEqual(WALLET_TOOL.inputSchema.properties.action.enum, ["balance", "receive", "pay", "history", "lnurl"]);
const { outputSchema: _omitOut, ...wireWalletTool } = WALLET_TOOL;
const approxStaticTokens = Math.ceil((walletInst.length + JSON.stringify(wireWalletTool).length) / 4);
assert.ok(
approxStaticTokens / 64000 <= 0.0235,
`static MCP footprint ${((approxStaticTokens / 64000) * 100).toFixed(3)}% exceeds 2.35% of 64k`,
approxStaticTokens / 64000 <= 0.0245,
`static MCP footprint ${((approxStaticTokens / 64000) * 100).toFixed(3)}% exceeds 2.45% of 64k`,
);

// Host-aware origin resolution & inline script syntax
Expand Down
84 changes: 81 additions & 3 deletions scripts/check-prf-arkade-v2.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,15 @@ import {
BASE_CHAIN_ID,
BASE_USDC_ADDRESS,
PERMIT2_ADDRESS,
TEMPO_CHAIN_IDS,
computeSafeMessageHash,
computeSafeTxHash,
createAgentSafeRuntime,
deriveFallbackSecondRecoveryAddress,
predictAgentSafeAddress,
predictPasskeySignerAddress,
} from "../src/agent-safe-v2.mjs";
import { parseMppChallenges, selectMppOffer } from "../src/safe-pay-mpp.mjs";
import {
DEFAULT_ARKADE_SOLVER_PUBKEY,
NuriAgentVtxoScript,
Expand Down Expand Up @@ -182,6 +184,7 @@ function encryptGrantForTest({ prfBytes, sessionId, replyPubkey, index = 0, poli
"receive",
"pay",
"history",
"lnurl",
]);
assert.equal(DEFAULT_ARKADE_SOLVER_PUBKEY.length, 64);

Expand Down Expand Up @@ -908,6 +911,23 @@ const mppEvmChallenge = Challenge.from({
},
});

const PATHUSD_ADDRESS = "0x20c0000000000000000000000000000000000000";
const mppTempoChallenge = Challenge.from({
id: "chal-tempo-1",
realm: "tempo.example.com",
method: "tempo",
intent: "charge",
request: {
amount: "500000", // 0.50 PATHUSD
currency: PATHUSD_ADDRESS,
recipient: "0x7777777777777777777777777777777777777777",
methodDetails: {
chainId: 4217,
decimals: 6,
},
},
});

// Synthetic HTTPS merchant dispatcher (zero network)
async function syntheticMerchantFetch(url, { headers = {}, shape } = {}) {
const auth = headers.Authorization || headers.authorization || "";
Expand Down Expand Up @@ -1528,6 +1548,25 @@ try {
assert.equal(overCap.ok, false);
assert.match(overCap.error, /NEW request_id and a higher max_amount/);

// Tempo MPP offers (chain 4217/42431) must be selectable by the PRF payer
{
const tempoHeaders = new Headers({ "www-authenticate": Challenge.serialize(mppTempoChallenge) });
const tempoOffers = parseMppChallenges({ headers: tempoHeaders });
assert.equal(tempoOffers.length, 1);
assert.equal(tempoOffers[0].method, "tempo");
assert.equal(Number(tempoOffers[0].chainId), 4217);
const picked = selectMppOffer(tempoOffers, { chainIds: [BASE_CHAIN_ID, ...TEMPO_CHAIN_IDS] });
assert.equal(picked.method, "tempo");
assert.equal(Number(picked.chainId), 4217);
assert.equal(String(picked.asset).toLowerCase(), PATHUSD_ADDRESS.toLowerCase());
const dual = parseMppChallenges({
headers: new Headers({
"www-authenticate": `${Challenge.serialize(mppEvmChallenge)}, ${Challenge.serialize(mppTempoChallenge)}`,
}),
});
const dualPick = selectMppOffer(dual, { chainIds: [BASE_CHAIN_ID, ...TEMPO_CHAIN_IDS] });
assert.equal(dualPick.method, "evm"); // charge intent + lowest index first
}
// Step I: Pay HTTP 402 via EVM MPP (Safe -> Agent EOA hop + stock `mppx`)
const paidMppEvm = await walletTool.call({
action: "pay",
Expand All @@ -1536,12 +1575,51 @@ try {
max_amount: "0.25",
request_id: "pay-mppevm-1",
});

assert.equal(paidMppEvm.ok, true);
assert.equal(paidMppEvm.protocol, "mpp");
assert.equal(paidMppEvm.rail, "usdc");
assert.equal(JSON.parse(paidMppEvm.resource.body).compute, "mpp-evm-paid-ok");

// Step J: Direct BOLT11 invoice, Lightning Address (`alice@...`), Arkade native send (`ark1...`), and 0x Base USDC send
// Step I2: LNURL handle on nuriwallet.com — register, public serve, callback invoice
{
const registered = await walletTool.call({
action: "receive",
wallet_key: walletKey,
lnurl_username: "nuri-agents-rock",
});
assert.equal(registered.ok, true);
assert.equal(registered.rail, "lnurl");
assert.equal(registered.lnurl, "nuri-agents-rock@nuriwallet.com");

// Second wallet cannot take the same username; same wallet re-registers fine.
const taken = await walletTool.call({ action: "receive", wallet_key: walletKey, lnurl_username: "nuri-agents-rock" });
assert.equal(taken.ok, true);

const served = await walletTool.call({ action: "lnurl", lnurl_username: "nuri-agents-rock" });
assert.equal(served.ok, true);
assert.equal(served.payRequest.status, "OK");
assert.equal(served.payRequest.tag, "payRequest");
assert.equal(served.payRequest.callback, "https://nuriwallet.com/lnurl/callback/nuri-agents-rock");
assert.equal(served.payRequest.minSendable, 340000);
assert.match(served.payRequest.metadata, /nuri-agents-rock@nuriwallet\.com/);

const cb = await walletTool.call({ action: "lnurl", lnurl_username: "nuri-agents-rock", lnurl_op: "callback", amount_msat: 500000 });
assert.equal(cb.ok, true);
assert.ok(cb.pr.startsWith("lnbc"), `callback returned a BOLT11 invoice: ${String(cb.pr).slice(0, 24)}…`);
assert.equal(cb.amount_sats, 500);
assert.match(cb.request_id, /^lnurlp:nuri-agents-rock:/);

const unknown = await walletTool.call({ action: "lnurl", lnurl_username: "nobody" });
assert.equal(unknown.ok, false);
assert.equal(unknown.status, 404);

// Bad amounts rejected cleanly
const bad = await walletTool.call({ action: "lnurl", lnurl_username: "nuri-agents-rock", lnurl_op: "callback", amount_msat: 500 });
assert.equal(bad.ok, false);
assert.match(bad.error, /millisatoshis/);
}


const paidBolt = await walletTool.call({
action: "pay",
wallet_key: walletKey,
Expand Down Expand Up @@ -1816,7 +1894,7 @@ try {

walletTool.close();
console.log(
"prf arkade v2 check ok: frozen vectors, connect agent_grant, 2-of-4 Safe (x402 + MPP + 0x + payFee), 2-of-2 MuSig2 Arkade + Lightning Intents (L402 + Lightning MPP + BOLT11 + LNURL + pushClaim), and legacy v1 coexistence verified",
"prf arkade v2 check ok: frozen vectors, connect agent_grant, 2-of-4 Safe (x402 + MPP + 0x + payFee + Tempo MPP selection), 2-of-2 MuSig2 Arkade + Lightning Intents (L402 + Lightning MPP + BOLT11 + LNURL + pushClaim), nuriwallet.com LNURL handles, and legacy v1 coexistence verified",
);
} finally {
Object.keys(process.env).forEach((k) => {
Expand Down
23 changes: 18 additions & 5 deletions src/agent-lightning-pay.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,16 @@ import { BlockList, isIP } from "node:net";
import { decodePaymentResponseHeader } from "@x402/core/http";
import { Challenge, Credential, Receipt } from "mppx";
import { privateKeyToAccount } from "viem/accounts";
import { BASE_CHAIN_ID, BASE_USDC_ADDRESS } from "./agent-safe-v2.mjs";
import { BASE_CHAIN_ID, BASE_USDC_ADDRESS, TEMPO_CHAIN_IDS } from "./agent-safe-v2.mjs";
import { MERCHANT_HEADERS, requestShape } from "./agent-kernel-runtime.mjs";
import { parseChallenge, payWithSafe, quoteOffer, selectOffer } from "./safe-pay.mjs";
import { parseMppChallenges, payMppCharge, quoteMppOffer, selectMppOffer } from "./safe-pay-mpp.mjs";
import { parseSolanaChallenge, payWithSolana, quoteSolanaOffer, readSolanaUsdcBalance, solanaSignerFromAgentKey } from "./safe-pay-solana.mjs";

const denied = new BlockList();
// Tempo has no gas coin: the Agent EOA pays its transferWithMemo fee in the token
// itself, so a Tempo hop carries amount + this reserve (leftover stays on the EOA).
const TEMPO_HOP_FEE_RESERVE_UNITS = 2_000_000n;
for (const [ip, bits] of [
["0.0.0.0", 8],
["10.0.0.0", 8],
Expand Down Expand Up @@ -356,15 +359,15 @@ export function classifyHttp402Response({
prefer && ["mpp", "mpp:evm", "charge", "session"].includes(String(prefer))
? prefer
: undefined;
const offer = selectMppOffer(evmOffers, { chainIds: [BASE_CHAIN_ID], prefer: mppPrefer });
const offer = selectMppOffer(evmOffers, { chainIds: [BASE_CHAIN_ID, ...TEMPO_CHAIN_IDS], prefer: mppPrefer });
candidates.push({
kind: "mpp-evm",
rail: "usdc",
offer,
amountUnits: offer.amount,
});
} catch {
// Ignore if MPP challenges are non-Base or Lightning-only.
// Ignore if MPP challenges are for unsupported chains.
}
}

Expand Down Expand Up @@ -402,6 +405,11 @@ export function classifyHttp402Response({
if (c.rail === "lightning") {
return c.amountSats !== null && sats >= BigInt(c.amountSats);
}
// A Tempo MPP offer is paid from the Safe's token balance on Tempo, which the
// caller's Base-USDC balance snapshot does not know: never exclude it here.
if (c.kind === "mpp-evm" && TEMPO_CHAIN_IDS.includes(Number(c.offer?.chainId))) {
return true;
}
const available = c.rail === "solana-usdc" ? BigInt(balances.solanaUsdcUnits ?? 0n) : usdcUnits;
return c.amountUnits !== undefined && available >= BigInt(c.amountUnits);
});
Expand Down Expand Up @@ -787,6 +795,8 @@ export function createPrfHttp402Payer({
? secrets.agentEthPrivHex
: `0x${secrets.agentEthPrivHex}`,
);
const offerChainId = Number(selected.offer.chainId);
const offerIsTempo = TEMPO_CHAIN_IDS.includes(offerChainId);
let hopTxHash = null;
let secondRaw = null;
const { response: second, receipt } = await payMppCharge({
Expand All @@ -796,17 +806,20 @@ export function createPrfHttp402Payer({
selected.offer.asset?.toLowerCase() === BASE_USDC_ADDRESS.toLowerCase()
? { name: "USD Coin", version: "2" }
: undefined,
feeReserve: offerIsTempo ? TEMPO_HOP_FEE_RESERVE_UNITS : 0n,
hop: async (_token, amount) => {
const hopped = await safeRuntime.transferUsdc({
const hopped = await safeRuntime.transferToken({
walletRecord: safeWalletRow,
agentEthPrivateKeyHex: secrets.agentEthPrivHex,
to: agentAccount.address,
amountUnits: amount,
opId: `${opId}:mpp-hop`,
chainId: offerChainId,
token: selected.offer.asset,
});
hopTxHash = hopped.txHash;
},
getClient: () => safeRuntime.publicClient,
getClient: (chainId) => safeRuntime.clientForChain(chainId),
fetchPaid: async (credentialHeader) => {
const res = await merchantFetch(url, {
headers: credentialHeader ? { Authorization: credentialHeader } : {},
Expand Down
Loading
Loading