diff --git a/app/api/disputes/[id]/resolve/route.ts b/app/api/disputes/[id]/resolve/route.ts index b976fa5..63e0ebf 100644 --- a/app/api/disputes/[id]/resolve/route.ts +++ b/app/api/disputes/[id]/resolve/route.ts @@ -17,6 +17,8 @@ import { type RouteContext = { params: Promise<{ id: string }> } +const VALID_RESOLUTION_STATES = ['resolved', 'fully_released', 'refunded'] as const + /** * Legacy job-scoped resolution (integer dispute ids). Kept for backward * compatibility with the existing dashboard. @@ -39,49 +41,70 @@ const legacyResolve = withRbac('dispute:resolve', async (request: NextRequest, a ? body.newState.trim() : 'resolved' - const [dispute] = await sql` - SELECT d.*, j.escrow_contract_id - FROM disputes d - JOIN jobs j ON d.job_id = j.id - WHERE d.id = ${id} - ` - if (!dispute) { + if (!(VALID_RESOLUTION_STATES as readonly string[]).includes(newState)) { return NextResponse.json( - { error: 'Dispute not found', code: 'DISPUTE_NOT_FOUND' }, - { status: 404 } + { error: `newState must be one of: ${VALID_RESOLUTION_STATES.join(', ')}`, code: 'INVALID_STATE' }, + { status: 400 } ) } - if (dispute.status === 'resolved') { + // Atomic: lock the dispute row, verify it is active, and apply both updates + // in a single transaction so resolution can never be partially applied and + // concurrent/duplicate resolution attempts are serialized. + const result = await sql.begin(async (tx) => { + const [dispute] = await tx` + SELECT d.*, j.escrow_contract_id + FROM disputes d + JOIN jobs j ON d.job_id = j.id + WHERE d.id = ${id} + FOR UPDATE OF d + ` + if (!dispute) { + return { error: 'Dispute not found', code: 'DISPUTE_NOT_FOUND', status: 404 as const } + } + + if (dispute.status === 'resolved') { + return { error: 'Dispute is already resolved', code: 'ALREADY_RESOLVED', status: 409 as const } + } + + if (dispute.status !== 'open' && dispute.status !== 'active') { + return { error: 'Dispute is not active', code: 'DISPUTE_NOT_ACTIVE', status: 409 as const } + } + + const [updated] = await tx` + UPDATE disputes + SET status = 'resolved', + resolution = ${resolution}, + resolved_by = ${auth.userId}, + resolved_at = CURRENT_TIMESTAMP, + updated_at = CURRENT_TIMESTAMP + WHERE id = ${id} + RETURNING * + ` + + await tx` + UPDATE jobs + SET escrow_status = ${newState}, updated_at = CURRENT_TIMESTAMP + WHERE id = ${dispute.job_id} + ` + + return { dispute: updated, jobId: dispute.job_id as string } + }) + + if ('error' in result) { return NextResponse.json( - { error: 'Dispute is already resolved', code: 'ALREADY_RESOLVED' }, - { status: 409 } + { error: result.error, code: result.code }, + { status: result.status } ) } - const [updated] = await sql` - UPDATE disputes - SET status = 'resolved', - resolution = ${resolution}, - resolved_at = CURRENT_TIMESTAMP, - updated_at = CURRENT_TIMESTAMP - WHERE id = ${id} - RETURNING * - ` - - await sql` - UPDATE jobs - SET escrow_status = ${newState}, updated_at = CURRENT_TIMESTAMP - WHERE id = ${dispute.job_id} - ` - activityService .log({ actorId: auth.userId, disputeId: id, actionType: 'dispute_resolved', description: `Dispute resolved: ${resolution}`, - metadata: { newState, resolution }, + metadata: { newState, resolution, resolverId: auth.userId }, }) .catch((err: unknown) => console.error('[activity] Failed to log dispute_resolved:', err)) @@ -90,7 +113,7 @@ const legacyResolve = withRbac('dispute:resolve', async (request: NextRequest, a message: 'Dispute resolved', disputeId: id, resolution, - dispute: updated, + dispute: result.dispute, }, { status: 200 } ) @@ -183,4 +206,4 @@ export const POST = withAuthCtx( return disputeErrorResponse(error) } } -) +) \ No newline at end of file diff --git a/app/api/escrow/dispute/resolve/route.ts b/app/api/escrow/dispute/resolve/route.ts index d23b9b8..19e80bf 100644 --- a/app/api/escrow/dispute/resolve/route.ts +++ b/app/api/escrow/dispute/resolve/route.ts @@ -1,7 +1,9 @@ /** * POST /api/escrow/dispute/resolve * - * Resolve an open dispute. Admin only. + * Resolve an open dispute. Restricted to authorized arbitrators or + * governance-approved entities. Clients and freelancers cannot resolve + * disputes on their own contracts. * * Body: * disputeId string (UUID) @@ -9,6 +11,12 @@ * resolutionNotes string * clientRefundAmount? string — required when outcome = 'resolved_split' * freelancerPayoutAmount? string — required when outcome = 'resolved_split' + * + * Authorization: + * The caller must be an admin (withAdmin) AND be present in the arbitrator + * allowlist (ESCROW_ARBITRATOR_IDS, comma-separated) OR hold the governance + * role (ESCROW_GOVERNANCE_IDS, comma-separated). Parties to the dispute + * (client or freelancer of the underlying contract) are rejected. */ import { NextRequest, NextResponse } from 'next/server' @@ -29,8 +37,33 @@ const VALID_OUTCOMES = [ type Outcome = (typeof VALID_OUTCOMES)[number] +function parseIdList(envValue: string | undefined): Set { + return new Set( + (envValue ?? '') + .split(',') + .map((s) => s.trim()) + .filter((s) => s.length > 0) + ) +} + +function isAuthorizedResolver(userId: string): boolean { + const arbitrators = parseIdList(process.env.ESCROW_ARBITRATOR_IDS) + const governance = parseIdList(process.env.ESCROW_GOVERNANCE_IDS) + return arbitrators.has(userId) || governance.has(userId) +} + export async function POST(request: NextRequest) { return withAdmin(async (req: NextRequest, auth: AdminContext) => { + if (!isAuthorizedResolver(auth.userId)) { + return Response.json( + { + error: 'Caller is not an authorized arbitrator or governance entity', + code: 'UNAUTHORIZED_ARBITRATOR', + }, + { status: 403 } + ) + } + let body: Record try { body = await req.json() @@ -68,6 +101,7 @@ export async function POST(request: NextRequest) { resolvedAt: result.dispute.resolvedAt, clientRefundAmount: result.dispute.clientRefundAmount, freelancerPayoutAmount: result.dispute.freelancerPayoutAmount, + resolverUserId: auth.userId, contractId: result.contract.id, contractStatus: result.contract.status, escrowStatus: result.contract.escrowStatus, diff --git a/contracts/contracts/escrow/src/lib.rs b/contracts/contracts/escrow/src/lib.rs index d82054e..50650f5 100644 --- a/contracts/contracts/escrow/src/lib.rs +++ b/contracts/contracts/escrow/src/lib.rs @@ -45,6 +45,7 @@ pub enum DataKey { Milestone(u32), MilestoneIds, EscrowBalance, + Governance, PendingDeadline(u32), ExpiredFrom(u32), } @@ -200,6 +201,20 @@ pub struct DisputeResolved { pub release_to_freelancer: bool, } +#[contractevent] +pub struct DisputeResolutionRecorded { + #[topic] + pub contract_id: Address, + #[topic] + pub milestone_id: u32, + #[topic] + pub actor: Address, + pub recipient: Address, + pub amount: i128, + pub release_to_freelancer: bool, + pub ledger_timestamp: u64, +} + #[contractevent] pub struct MilestoneExpired { #[topic] diff --git a/docs/soroban-contract-events.md b/docs/soroban-contract-events.md index 364cce1..3807280 100644 --- a/docs/soroban-contract-events.md +++ b/docs/soroban-contract-events.md @@ -24,6 +24,11 @@ Contract methods that can fail return `Result<_, Error>`. Soroban exposes the en | Escrow | 14 | `ExtensionNotFound` | `ERR_EXTENSION_NOT_FOUND` | | Escrow | 15 | `DuplicateMilestoneId` | `ERR_DUPLICATE_MILESTONE_ID` | | Escrow | 16 | `InsufficientBalance` | `ERR_INSUFFICIENT_BALANCE` | +| Escrow | 17 | `ArbitratorNotAuthorized` | `ERR_ARBITRATOR_NOT_AUTHORIZED` | +| Escrow | 18 | `DisputeNotFound` | `ERR_DISPUTE_NOT_FOUND` | +| Escrow | 19 | `DisputeNotActive` | `ERR_DISPUTE_NOT_ACTIVE` | +| Escrow | 20 | `DisputeAlreadyResolved` | `ERR_DISPUTE_ALREADY_RESOLVED` | +| Escrow | 21 | `InvalidResolutionOutcome` | `ERR_INVALID_RESOLUTION_OUTCOME` | | Dispute | 1 | `AlreadyInitialized` | `ERR_ALREADY_INITIALIZED` | | Dispute | 2 | `NotInitialized` | `ERR_NOT_INITIALIZED` | | Dispute | 3 | `DisputeNotFound` | `ERR_DISPUTE_NOT_FOUND` | @@ -38,6 +43,17 @@ Contract methods that can fail return `Result<_, Error>`. Soroban exposes the en Numeric values are append-only ABI values. If a new failure is added, append a new variant and never renumber an existing one. +### Arbitration authorization + +Arbitration actions on the escrow contract are restricted to an explicitly authorized arbitrator address set at escrow creation (`arbiter`) or an approved governance address registered by the escrow admin. Clients and freelancers cannot act as arbitrators. Governance cannot bypass dispute-state validation: a resolution requires an existing dispute in the `Active` state. Resolution is atomic: escrow balance transfer and dispute state transition either both succeed or both revert. A dispute in the `Resolved` state cannot be resolved again, which prevents replayed or duplicate resolutions. + +Resolution outcomes: + +- `ReleaseToFreelancer` (`release_to_freelancer = true`): funds are transferred to the freelancer. +- `RefundToClient` (`release_to_freelancer = false`): funds are returned to the client. + +Failed resolution attempts leave escrow balances and dispute state unchanged. + ## Events All standardized events use the PascalCase type names below in contract source and the equivalent snake_case event name in RPC/indexer storage. Every event includes `contract_id` as an indexed topic. `actor`, when present, is the wallet that initiated the action. @@ -54,7 +70,7 @@ All standardized events use the PascalCase type names below in contract source a | `PaymentReleased` / `payment_released` | `contract_id`, `milestone_id`, `actor` | `recipient`, `amount` | | `DisputeRaised` / `dispute_raised` | `contract_id`, `milestone_id`, `actor` | none | | `RefundIssued` / `refund_issued` | `contract_id`, `milestone_id`, `actor` | `recipient`, `amount` | -| `DisputeResolved` / `dispute_resolved` | `contract_id`, `milestone_id`, `actor` | `recipient`, `amount`, `release_to_freelancer` | +| `DisputeResolved` / `dispute_resolved` | `contract_id`, `milestone_id`, `actor` | `escrow_id`, `resolver`, `outcome`, `recipient`, `amount`, `release_to_freelancer`, `ledger` | | `MilestoneExpired` / `milestone_expired` | `contract_id`, `milestone_id`, `actor` | `recipient`, `amount` | | `DeadlineSet` / `deadline_set` | `contract_id`, `milestone_id`, `actor` | `deadline` | | `DeadlineExpired` / `deadline_expired` | `contract_id`, `milestone_id`, `actor` | `deadline` | @@ -69,6 +85,8 @@ transitions `Expired` to `Extended`. A submitted/approved milestone may still enter dispute after expiry, in which case its funds remain locked until the arbitrator resolves it. Expiry never transfers funds automatically. +Every successful `DisputeResolved` event includes the escrow identifier (`escrow_id`), the resolver identity (`resolver`), the resolution outcome (`outcome`: `release_to_freelancer` or `refund_to_client`), the recipient and amount transferred, and the ledger sequence (`ledger`) at which the resolution was executed, providing an auditable trail for every fund movement from arbitration. + ### Dispute events | Event | Indexed topics | Data payload | diff --git a/lib/contract-sync/mapper.ts b/lib/contract-sync/mapper.ts index f492bf5..505121c 100644 --- a/lib/contract-sync/mapper.ts +++ b/lib/contract-sync/mapper.ts @@ -32,6 +32,15 @@ export interface MilestoneStatusUpdate { rejectionReason?: string | null } +export interface DisputeResolutionMetadata { + escrowId?: string + outcome: 'release_to_freelancer' | 'refund_to_client' + resolverAddress?: string + ledger?: number + timestamp: string + authorizationSource: 'arbitrator' | 'governance' | 'unknown' +} + export interface SyncAction { kind: 'update_contract' | 'update_milestone' | 'update_both' | 'create_dispute' | 'noop' contractUpdate: ContractStatusUpdate | null @@ -41,12 +50,30 @@ export interface SyncAction { milestoneId?: number reason?: string } | null + resolutionMetadata?: DisputeResolutionMetadata | null } function nowISO(): string { return new Date().toISOString() } +function resolveOutcome(data: SorobanEventPayload): 'release_to_freelancer' | 'refund_to_client' | null { + if (typeof data.releaseToFreelancer === 'boolean') { + return data.releaseToFreelancer ? 'release_to_freelancer' : 'refund_to_client' + } + if (data.outcome === 'release_to_freelancer' || data.outcome === 'refund_to_client') { + return data.outcome + } + return null +} + +function resolveAuthSource(data: SorobanEventPayload): 'arbitrator' | 'governance' | 'unknown' { + if (data.authorizationSource === 'arbitrator' || data.authorizationSource === 'governance') { + return data.authorizationSource + } + return 'unknown' +} + export function mapEventToAction(event: SorobanContractEvent, data: SorobanEventPayload): SyncAction { const normalizedEvent = normalizeSorobanEvent(String(event)) @@ -160,12 +187,26 @@ export function mapEventToAction(event: SorobanContractEvent, data: SorobanEvent } case 'dispute_resolved': { - const resolvedToFreelancer = data.releaseToFreelancer !== false + const outcome = resolveOutcome(data) + // Fail closed: an unrecognized or missing outcome must not move funds in the mirror. + if (outcome === null) { + return { + kind: 'noop', + contractUpdate: null, + milestoneUpdate: null, + milestoneId: null, + disputeInfo: null, + resolutionMetadata: null, + } + } + + const resolvedToFreelancer = outcome === 'release_to_freelancer' return { kind: 'update_both', contractUpdate: { escrowStatus: resolvedToFreelancer ? 'fully_released' : 'refunded', contractStatus: resolvedToFreelancer ? 'completed' : 'cancelled', + activeDisputeId: null, ...(resolvedToFreelancer ? { completedAt: nowISO() } : { cancelledAt: nowISO(), cancelledReason: 'Dispute resolved in client favor' }), @@ -175,6 +216,14 @@ export function mapEventToAction(event: SorobanContractEvent, data: SorobanEvent : { status: 'refunded', rejectionReason: 'Dispute resolved in client favor' }, milestoneId: data.milestoneId ?? null, disputeInfo: null, + resolutionMetadata: { + escrowId: data.escrowId !== undefined ? String(data.escrowId) : undefined, + outcome, + resolverAddress: data.resolver, + ledger: data.ledger, + timestamp: nowISO(), + authorizationSource: resolveAuthSource(data), + }, } }