Skip to content
Open
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
85 changes: 54 additions & 31 deletions app/api/disputes/[id]/resolve/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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))

Expand All @@ -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 }
)
Expand Down Expand Up @@ -183,4 +206,4 @@ export const POST = withAuthCtx(
return disputeErrorResponse(error)
}
}
)
)
36 changes: 35 additions & 1 deletion app/api/escrow/dispute/resolve/route.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
/**
* 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)
* outcome 'resolved_client' | 'resolved_freelancer' | 'resolved_split' | 'withdrawn'
* 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'
Expand All @@ -29,8 +37,33 @@ const VALID_OUTCOMES = [

type Outcome = (typeof VALID_OUTCOMES)[number]

function parseIdList(envValue: string | undefined): Set<string> {
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<string, unknown>
try {
body = await req.json()
Expand Down Expand Up @@ -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,
Expand Down
15 changes: 15 additions & 0 deletions contracts/contracts/escrow/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ pub enum DataKey {
Milestone(u32),
MilestoneIds,
EscrowBalance,
Governance,
PendingDeadline(u32),
ExpiredFrom(u32),
}
Expand Down Expand Up @@ -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]
Expand Down
20 changes: 19 additions & 1 deletion docs/soroban-contract-events.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand All @@ -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.
Expand All @@ -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` |
Expand All @@ -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 |
Expand Down
51 changes: 50 additions & 1 deletion lib/contract-sync/mapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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))

Expand Down Expand Up @@ -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' }),
Expand All @@ -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),
},
}
}

Expand Down
Loading