diff --git a/.gitignore b/.gitignore
index 6104937a..1c097e65 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,23 +1,23 @@
-# ── Dependencies ──────────────────────────────────────────────────────────
+# Dependencies
node_modules/
-# ── Next.js ───────────────────────────────────────────────────────────────
+# Next.js
.next/
out/
-# ── Build outputs ─────────────────────────────────────────────────────────
+# Build outputs
dist/
-# ── Environment variables ─────────────────────────────────────────────────
+# Environment variables
.env
.env.local
.env.*.local
-# ── TypeScript ────────────────────────────────────────────────────────────
+# TypeScript
*.tsbuildinfo
next-env.d.ts
-# ── Test artifacts ────────────────────────────────────────────────────────
+# Test artifacts
coverage/
**/__snapshots__/
*.snap
@@ -26,21 +26,11 @@ test-results/
junit.xml
*.lcov
-# ── OS files ──────────────────────────────────────────────────────────────
+# OS files
.DS_Store
Thumbs.db
-*.DS_Store
-# Test artifacts
-**/__snapshots__/
-*.snap
-coverage/
-playwright-report/
-test-results/
-junit.xml
-*.lcov
-
-# ── Logs ──────────────────────────────────────────────────────────────────
+# Logs
*.log
npm-debug.log*
yarn-debug.log*
@@ -57,4 +47,3 @@ yarn-error.log*
.vercel/
.cache/
*.tgz
-dist/
diff --git a/src/components/MultiSigApprovalPanel.tsx b/src/components/MultiSigApprovalPanel.tsx
new file mode 100644
index 00000000..4c9529e2
--- /dev/null
+++ b/src/components/MultiSigApprovalPanel.tsx
@@ -0,0 +1,124 @@
+"use client";
+
+import { useState } from "react";
+import {
+ type MultiSigApprovalRecord,
+ getApprovalProgress,
+} from "@/services/multiSigApproval";
+
+interface Props {
+ record: MultiSigApprovalRecord;
+ connectedAddress?: string;
+ onApprove?: (signer: string, signature: string) => void;
+}
+
+export default function MultiSigApprovalPanel({
+ record,
+ connectedAddress,
+ onApprove,
+}: Props) {
+ const [signing, setSigning] = useState(false);
+ const progress = getApprovalProgress(record);
+ const { approved, required, isComplete } = progress;
+
+ const signers = record.config.signers;
+ const approvedSet = new Set(record.approvals.filter((a) => a.verified).map((a) => a.signer));
+
+ const canSign =
+ connectedAddress !== undefined &&
+ signers.includes(connectedAddress) &&
+ !approvedSet.has(connectedAddress) &&
+ !isComplete &&
+ record.status === "pending";
+
+ function handleSign() {
+ if (!connectedAddress || !onApprove) return;
+ setSigning(true);
+ // In a real implementation, this would trigger a wallet signature request.
+ // For now we produce a stub signature derived from the address.
+ const stubSignature = `sig-${connectedAddress}-${Date.now()}`;
+ onApprove(connectedAddress, stubSignature);
+ setSigning(false);
+ }
+
+ const progressPercent = required === 0 ? 100 : Math.min(100, (approved / required) * 100);
+
+ return (
+
+
+
Multi-Signature Approval
+
+ {isComplete ? "Threshold Met" : "Pending Approvals"}
+
+
+
+
+ {approved} of {required} required approvals
+
+
+ {/* Progress bar */}
+
+
+ {/* Signer list */}
+ {signers.length === 0 ? (
+
No signers configured.
+ ) : (
+
+ {signers.map((addr) => {
+ const hasApproved = approvedSet.has(addr);
+ return (
+ -
+
+
+ {addr}
+
+
+ {hasApproved ? "✓ approved" : "pending"}
+
+
+ );
+ })}
+
+ )}
+
+ {canSign && (
+
+ )}
+
+ );
+}
diff --git a/src/lib/invoiceApprovals.ts b/src/lib/invoiceApprovals.ts
index f443320b..1422c075 100644
--- a/src/lib/invoiceApprovals.ts
+++ b/src/lib/invoiceApprovals.ts
@@ -4,65 +4,153 @@ export interface ApprovalPolicy {
levels: string[][];
}
-export interface InvoiceApprovalRequest {
+export interface ApprovalRequest {
id: string;
invoiceId: string;
status: "pending" | "approved" | "rejected";
- amount?: number;
- createdAt?: number;
- updatedAt?: number;
- owner?: string;
- currentLevel?: number;
- levels?: Array<{ approvers: string[]; decisions?: Array<{ approver: string; decision: string }> }>;
- address?: string;
- [key: string]: any;
+ amount: number;
+ owner: string;
+ title: string;
+ payload: { recipients: unknown[]; token: string; deadline: number };
+ currentLevel: number;
+ levels: Array<{
+ approvers: string[];
+ decisions: Array<{ approver: string; decision: string; comment?: string; timestamp: number }>;
+ }>;
+ events: Array<{ approver: string; decision: string; comment?: string; timestamp: number; level: number }>;
+ createdAt: number;
+ updatedAt: number;
}
-export async function getApprovalRequests(): Promise {
- return [];
+export function shouldRequireApproval(amount: number, policy: ApprovalPolicy): boolean {
+ return policy.enabled && amount >= policy.minimumAmount;
}
-export async function saveApprovalRequests(requests: InvoiceApprovalRequest[]): Promise {}
-
-export async function getApprovalPolicy(): Promise {
- return { enabled: false, minimumAmount: 0, levels: [] };
+export function createApprovalRequest(
+ invoiceData: {
+ owner: string;
+ title: string;
+ amount: number;
+ payload: { recipients: unknown[]; token: string; deadline: number };
+ },
+ policy: ApprovalPolicy,
+ timestamp: number,
+): ApprovalRequest {
+ return {
+ id: Math.random().toString(36).slice(2),
+ invoiceId: Math.random().toString(36).slice(2),
+ status: "pending",
+ amount: invoiceData.amount,
+ owner: invoiceData.owner,
+ title: invoiceData.title,
+ payload: invoiceData.payload,
+ currentLevel: 0,
+ levels: policy.levels.map((approvers) => ({ approvers, decisions: [] })),
+ events: [],
+ createdAt: timestamp,
+ updatedAt: timestamp,
+ };
}
-export async function saveApprovalPolicy(walletOrPolicy: string | ApprovalPolicy, policy?: ApprovalPolicy): Promise {}
+export function recordApprovalDecision(
+ request: ApprovalRequest,
+ wallet: string,
+ decision: "approved" | "rejected",
+ comment?: string,
+ timestamp?: number,
+): ApprovalRequest {
+ if (wallet === request.owner) {
+ throw new Error("cannot approve their own");
+ }
-export async function notifyApprovalUsers(request: InvoiceApprovalRequest, users?: string[], message?: string): Promise {}
+ const ts = timestamp ?? Date.now();
+ const level = request.currentLevel;
+ const currentLevelData = request.levels[level];
-export function recordApprovalDecision(request: InvoiceApprovalRequest, wallet: string, decision: string, comment?: string): InvoiceApprovalRequest {
- return { ...request, status: decision as any };
-}
+ if (!currentLevelData || !currentLevelData.approvers.includes(wallet)) {
+ throw new Error("not assigned");
+ }
+
+ const newDecision = { approver: wallet, decision, comment, timestamp: ts };
+ const newEvent = { approver: wallet, decision, comment, timestamp: ts, level };
+
+ const updatedLevels = request.levels.map((l, i) => {
+ if (i !== level) return l;
+ return { ...l, decisions: [...l.decisions, newDecision] };
+ });
+
+ const updatedEvents = [...request.events, newEvent];
+
+ if (decision === "rejected") {
+ return {
+ ...request,
+ status: "rejected",
+ levels: updatedLevels,
+ events: updatedEvents,
+ updatedAt: ts,
+ };
+ }
+
+ // All approvers at this level have decided
+ const updatedCurrentLevel = updatedLevels[level];
+ const allApproved =
+ updatedCurrentLevel.approvers.every((a) =>
+ updatedCurrentLevel.decisions.some((d) => d.approver === a && d.decision === "approved"),
+ );
+
+ if (!allApproved) {
+ return {
+ ...request,
+ levels: updatedLevels,
+ events: updatedEvents,
+ updatedAt: ts,
+ };
+ }
+
+ const nextLevel = level + 1;
+ if (nextLevel >= request.levels.length) {
+ return {
+ ...request,
+ status: "approved",
+ currentLevel: nextLevel,
+ levels: updatedLevels,
+ events: updatedEvents,
+ updatedAt: ts,
+ };
+ }
-export function summarizeApprovalAnalytics(requests?: InvoiceApprovalRequest[]): any {
return {
- total: 0,
- pending: 0,
- approved: 0,
- rejected: 0,
- averageDecisionHours: 0,
- approvalRate: 0,
+ ...request,
+ currentLevel: nextLevel,
+ levels: updatedLevels,
+ events: updatedEvents,
+ updatedAt: ts,
};
}
-export function completeApprovalRequest(request: InvoiceApprovalRequest, wallet: any, invoiceId: string, txHash: string): InvoiceApprovalRequest {
- return { ...request, status: "approved" };
-}
+export function summarizeApprovalAnalytics(requests: ApprovalRequest[]): {
+ total: number;
+ pending: number;
+ approved: number;
+ rejected: number;
+ averageDecisionHours: number;
+ approvalRate: number;
+} {
+ const total = requests.length;
+ const pending = requests.filter((r) => r.status === "pending").length;
+ const approved = requests.filter((r) => r.status === "approved").length;
+ const rejected = requests.filter((r) => r.status === "rejected").length;
-export function shouldRequireApproval(amount: number, policy: ApprovalPolicy): boolean {
- return policy.enabled && amount >= policy.minimumAmount;
-}
+ const decided = requests.filter((r) => r.status !== "pending" && r.events.length > 0);
+ const averageDecisionHours =
+ decided.length === 0
+ ? 0
+ : decided.reduce((sum, r) => {
+ const lastEvent = r.events[r.events.length - 1];
+ return sum + (lastEvent.timestamp - r.createdAt) / 1000 / 3600;
+ }, 0) / decided.length;
-export function createApprovalRequest(invoiceId: string, amount: number): InvoiceApprovalRequest {
- return {
- id: Math.random().toString(),
- invoiceId,
- status: "pending",
- amount,
- createdAt: Date.now(),
- updatedAt: Date.now(),
- levels: [],
- };
+ const approvalRate = total === 0 ? 0 : approved / total;
+
+ return { total, pending, approved, rejected, averageDecisionHours, approvalRate };
}
diff --git a/src/services/multiSigApproval.ts b/src/services/multiSigApproval.ts
new file mode 100644
index 00000000..158d5c79
--- /dev/null
+++ b/src/services/multiSigApproval.ts
@@ -0,0 +1,132 @@
+export interface MultiSigConfig {
+ invoiceId: string;
+ threshold: number;
+ signers: string[];
+ highValueThreshold: number;
+}
+
+export interface SignerApproval {
+ signer: string;
+ signature: string;
+ approvedAt: string;
+ verified: boolean;
+}
+
+export interface AuditEntry {
+ action: string;
+ actor: string;
+ timestamp: string;
+ details?: string;
+}
+
+export interface MultiSigApprovalRecord {
+ invoiceId: string;
+ config: MultiSigConfig;
+ approvals: SignerApproval[];
+ status: "pending" | "approved" | "rejected";
+ createdAt: string;
+ updatedAt: string;
+ auditTrail: AuditEntry[];
+}
+
+export function requiresMultiSig(amount: number, config: MultiSigConfig): boolean {
+ return amount >= config.highValueThreshold && config.signers.length > 0;
+}
+
+export function createMultiSigRecord(
+ invoiceId: string,
+ config: MultiSigConfig,
+): MultiSigApprovalRecord {
+ const now = new Date().toISOString();
+ return {
+ invoiceId,
+ config,
+ approvals: [],
+ status: "pending",
+ createdAt: now,
+ updatedAt: now,
+ auditTrail: [
+ {
+ action: "created",
+ actor: "system",
+ timestamp: now,
+ details: `Multi-sig record created for invoice ${invoiceId}`,
+ },
+ ],
+ };
+}
+
+export function addApproval(
+ record: MultiSigApprovalRecord,
+ signer: string,
+ signature: string,
+): MultiSigApprovalRecord {
+ if (!record.config.signers.includes(signer)) {
+ throw new Error("Signer not authorized");
+ }
+ if (record.approvals.some((a) => a.signer === signer)) {
+ throw new Error("Signer already approved");
+ }
+
+ const now = new Date().toISOString();
+ const verified = signature.length > 0;
+
+ const newApproval: SignerApproval = {
+ signer,
+ signature,
+ approvedAt: now,
+ verified,
+ };
+
+ const updatedApprovals = [...record.approvals, newApproval];
+ const isApproved = updatedApprovals.length >= record.config.threshold;
+
+ const auditEntry: AuditEntry = {
+ action: "approved",
+ actor: signer,
+ timestamp: now,
+ details: `Signer ${signer} approved invoice ${record.invoiceId}`,
+ };
+
+ return {
+ ...record,
+ approvals: updatedApprovals,
+ status: isApproved ? "approved" : "pending",
+ updatedAt: now,
+ auditTrail: [...record.auditTrail, auditEntry],
+ };
+}
+
+export function getApprovalProgress(record: MultiSigApprovalRecord): {
+ approved: number;
+ required: number;
+ remaining: number;
+ isComplete: boolean;
+} {
+ const approved = record.approvals.filter((a) => a.verified).length;
+ const required = record.config.threshold;
+ const remaining = Math.max(0, required - approved);
+ return { approved, required, remaining, isComplete: approved >= required };
+}
+
+export function getAuditTrail(record: MultiSigApprovalRecord): AuditEntry[] {
+ return record.auditTrail;
+}
+
+export function notifySigners(record: MultiSigApprovalRecord, pendingSigners: string[]): void {
+ for (const addr of pendingSigners) {
+ console.log(`Notifying signer ${addr} for invoice ${record.invoiceId}`);
+ }
+}
+
+export function configureThreshold(
+ invoiceId: string,
+ signers: string[],
+ threshold: number,
+ highValueThreshold = 0,
+): MultiSigConfig {
+ if (threshold > signers.length) {
+ throw new Error("Threshold cannot exceed number of signers");
+ }
+ return { invoiceId, threshold, signers, highValueThreshold };
+}