agentcomply / tree / cre/screen-before-pay/main.ts · raw (this view has old GitHub links rewritten for the mirror; raw is byte-exact)
// AgentComply x Chainlink CRE: "screen before pay".
// A payment request (HTTP trigger, or a scheduled demo payment on cron) is screened by AgentComply's
// /v1/screen before any money moves. The DON reaches consensus on the verdict, the receipt hash and
// whether the receipt's Ed25519 signature + hash verify (/v1/verify), then produces a DON-signed report
// of {verdict, action, receiptHash, receiptId, approved} that a payment contract or treasury can gate on.
// Fail-closed: any upstream failure, bad JSON or an invalid receipt => approved = false, never "ok".
import {
  bytesToBase64,
  bytesToHex,
  ConsensusAggregationByFields,
  CronCapability,
  cre,
  decodeJson,
  handler,
  HTTPCapability,
  type HTTPPayload,
  type HTTPSendRequester,
  identical,
  median,
  prepareReportRequest,
  Runner,
  type Runtime,
} from "@chainlink/cre-sdk";
import { encodeAbiParameters, keccak256, toHex } from "viem";

export type Payment = {
  payTo: string;
  chain?: string;
  intent?: string;
  amount_usd?: number;
  token?: string;
  merchantDomain?: string;
  instructions?: string;
  agentId?: string;
  reference?: string;
};

export type Config = {
  schedule: string;
  agentcomplyUrl: string; // e.g. https://agentcomply.agentgate.workers.dev
  demoPayment: Payment; // what the cron trigger screens
};

export type Screening = {
  status: number; // HTTP status of /v1/screen
  verdict: string; // ok | caution | block (or "caution" when AgentComply was unreachable)
  action: string; // proceed | hold | do_not_pay
  receiptId: string;
  receiptHash: string; // sha256 of the canonical receipt (hex, no 0x)
  seq: number; // position in AgentComply's hash-chained ledger
  signatureValid: boolean; // AgentComply /v1/verify on the returned receipt
};

const enc = (s: string) => bytesToBase64(new TextEncoder().encode(s));
const FAIL = (status: number): Screening => ({ status, verdict: "caution", action: "hold", receiptId: "", receiptHash: "", seq: 0, signatureValid: false });

// Runs on each node. cacheSettings lets the nodes share one /v1/screen response, so a DON run
// issues one receipt (not one per node) and every node sees the same hash.
export const screenPayment = (sendRequester: HTTPSendRequester, config: Config, payment: Payment): Screening => {
  const res = sendRequester
    .sendRequest({
      url: `${config.agentcomplyUrl}/v1/screen`,
      method: "POST",
      headers: { "content-type": "application/json" },
      body: enc(JSON.stringify(payment)),
      cacheSettings: { store: true, maxAge: "60s" },
    })
    .result();
  let r: any;
  try { r = decodeJson(res.body); } catch { return FAIL(res.statusCode); }
  if (!r || !r.receipt || !r.receipt.integrity) return FAIL(res.statusCode);
  // Independently check the receipt's signature and hash before trusting it.
  const v = sendRequester
    .sendRequest({ url: `${config.agentcomplyUrl}/v1/verify`, method: "POST", headers: { "content-type": "application/json" }, body: enc(JSON.stringify(r.receipt)) })
    .result();
  let valid = false;
  try { valid = decodeJson(v.body).valid === true; } catch { valid = false; }
  return {
    status: res.statusCode,
    verdict: String(r.verdict ?? "caution"),
    action: String(r.action ?? "hold"),
    receiptId: String(r.receipt.receipt_id ?? ""),
    receiptHash: String(r.receipt.integrity.hash ?? ""),
    seq: Number(r.receipt.chain?.seq ?? 0),
    signatureValid: valid,
  };
};

export const decide = (runtime: Runtime<Config>, payment: Payment): string => {
  runtime.log(`Screening payment to ${payment.payTo} on ${payment.chain ?? "ethereum"} ($${payment.amount_usd ?? 0}) via AgentComply`);
  const http = new cre.capabilities.HTTPClient();
  const s = http
    .sendRequest(
      runtime,
      screenPayment,
      ConsensusAggregationByFields<Screening>({
        status: median,
        verdict: identical,
        action: identical,
        receiptId: identical,
        receiptHash: identical,
        seq: median,
        signatureValid: identical,
      }),
    )(runtime.config, payment)
    .result();

  // Fail-closed gate: pay only on ok + proceed + a receipt whose signature and hash verify.
  const approved = s.status === 200 && s.verdict === "ok" && s.action === "proceed" && s.signatureValid;
  runtime.log(`AgentComply verdict=${s.verdict} action=${s.action} receipt #${s.seq} ${s.receiptId} hash=${s.receiptHash.slice(0, 16)}… signatureValid=${s.signatureValid}`);

  // DON-signed report: what an on-chain payment gate / audit log would store.
  const receiptHash = (/^[0-9a-f]{64}$/.test(s.receiptHash) ? `0x${s.receiptHash}` : `0x${"0".repeat(64)}`) as `0x${string}`;
  const payload = encodeAbiParameters(
    [{ type: "bytes32" }, { type: "string" }, { type: "string" }, { type: "string" }, { type: "uint64" }, { type: "bool" }],
    [receiptHash, s.verdict, s.action, s.receiptId, BigInt(s.seq), approved],
  );
  const report = runtime.report(prepareReportRequest(payload)).result();
  const raw = report.rawReport();
  runtime.log(`DON report: ${raw.length} bytes, keccak ${keccak256(toHex(raw)).slice(0, 18)}…`);
  runtime.log(approved ? "DECISION: PAY (verdict ok, receipt verified)" : `DECISION: DO NOT PAY (${s.verdict}/${s.action}${s.signatureValid ? "" : ", receipt not verified"})`);

  return JSON.stringify({ approved, verdict: s.verdict, action: s.action, receiptId: s.receiptId, receiptHash: s.receiptHash, seq: s.seq, signatureValid: s.signatureValid, reportBytes: raw.length, reportHex: bytesToHex(raw).slice(0, 66) + "…" });
};

export const onCron = (runtime: Runtime<Config>): string => decide(runtime, runtime.config.demoPayment);

export const onHttp = (runtime: Runtime<Config>, payload: HTTPPayload): string => {
  let p: Payment;
  try { p = decodeJson(payload.input) as Payment; } catch { throw new Error("payload must be JSON: {payTo, chain?, amount_usd?, ...}"); }
  if (!p || typeof p.payTo !== "string") throw new Error("payload.payTo is required");
  return decide(runtime, p);
};

export const initWorkflow = (config: Config) => [
  handler(new CronCapability().trigger({ schedule: config.schedule }), onCron),
  handler(new HTTPCapability().trigger({}), onHttp),
];

export async function main() {
  const runner = await Runner.newRunner<Config>();
  await runner.run(initWorkflow);
}

agentgate-source: code mirror on Cloudflare Pages. All repos