Milestone-Based Advisory Escrow: Combining On-Chain Payment Locks with Encrypted Deliverable Proofs

In high-end technical consulting, smart-contract security audits, and independent strategic research, advisors and enterprise clients often face a fragile trust impasse:

  • The advisor’s concern: send the full plaintext of a hard-earned 60-page vulnerability report or architecture proposal first, and the client may claim it did not meet expectations to delay or refuse the final 50% payment;
  • The client’s concern: pay in full before acceptance, and staff turnover may derail the engagement or the advisor may deliver a poor-quality patchwork document. The client then bears substantial losses and expensive enforcement costs.

Traditional contracts use legal clauses and international arbitration to constrain both parties. Yet for technical consulting and decentralized Web3 engagements worth tens of thousands of dollars, cross-border litigation time and legal fees can exceed the project value. Both sides spend weeks negotiating 30%-40%-30% installments, and final settlement still brings distrust and prolonged bargaining.

Resolving this impasse requires an engineered zero-trust deliver-and-pay handshake. This article examines Fone ProofDesk: using a Solidity milestone advisory escrow and a client-side WebCrypto ciphertext hash anchor for non-repudiable deliverable submission and atomic payment-and-decryption settlement.


1. Timing Asymmetry and the Traditional Consulting Delivery Trap

Milestone-Based Advisory Escrow: Combining On-Chain Payment Locks with Encrypted Deliverable Proofs

Without cryptographic or smart-contract constraints, the imbalance comes from the timing mismatch between delivery and payment:

+----------------------------------------------------------------------------------------------------+
|                         Traditional Consulting: Final-Payment Negotiation Timeline                  |
+----------------------------------------------------------------------------------------------------+

   [ Advisor / Auditor ]                                            [ Enterprise Client ]
                 │                                                                 │
   (1) Spend 4 weeks on a deep security audit / architecture design                   │
                 │                                                                 │
   (2) Face a critical choice:                                                       │
       ┌─────────┴───────────────────────────────────────┐                         │
       │ Branch A: send the complete plaintext PDF first  │                         │
       │         │                                       │                         │
       │         ├────── Send final report (balance unpaid)────────────────────────>│
       │         │                                       │                         │
       │         │                                       │           (3) Client now has all knowledge assets
       │         │                                       │               - Starts finding faults to reduce price
       │         │<───── "Not detailed enough; cut balance 50%"──────────┤ (Advisor has little leverage)
       │                                                 │                         │
       │ Branch B: insist on final payment before delivery│                         │
       │         │                                       │                         │
       │         ├────── "Pay the $20,000 balance first"──┼────────────────────────>│
       │         │                                       │                         │
       │         │                                       │           (4) Client refuses
       │         │<───── "No final payment before seeing it"────────────┤ (Indefinite stalemate)
+----------------------------------------------------------------------------------------------------+

The core problem is that plaintext cannot be recalled once disclosed, and traditional payment systems cannot condition release on the immutability of deliverable content.


2. Two-Phase Deliverable Hash Anchoring and Escrow

In the production Fone ProofDesk implementation, delivery and settlement form a four-stage state machine in which stages depend on one another:

+----------------------------------------------------------------------------------------------------+
|                          ProofDesk Two-Phase Hash Anchoring and Atomic Delivery                     |
+----------------------------------------------------------------------------------------------------+

   [ Stage 1: Lock funds on-chain ]
   Client confirms scope and locks full payment (e.g. 50,000 USDC) in AdvisoryEscrow.sol.
   Funds enter `DEPOSIT_LOCKED`; neither party may withdraw them at will.
            │
            ▼
   [ Stage 2: Commit the ciphertext hash on-chain (Commitment Phase) ]
   Advisor encrypts the report locally with WebCrypto as `Ciphertext`; calculates `ciphertextHash = keccak256(Ciphertext)`.
   Advisor uploads ciphertext to decentralized storage (IPFS / S3) and writes `ciphertextHash` to the escrow.
   State advances to `DELIVERABLE_COMMITTED`.
   [Non-repudiation]: advisor proves completion before the deadline, and report content cannot be altered.
            │
            ▼
   [ Stage 3: Client preflight and payment authorization (Authorization Phase) ]
   Client downloads ciphertext and verifies local `sha256/keccak256` exactly matches on-chain `ciphertextHash`.
   Client clicks "Accept" and sends `releasePaymentAndRequestKey()` to the contract.
   Escrow transfers final payment to the advisor; state advances to `FUNDS_RELEASED`.
            │
            ▼
   [ Stage 4: Publish key envelope on-chain and restore locally (Decryption Handshake) ]
   In the payment-release transaction or callback, advisor submits a key envelope encrypted for the client's public key.
   Client decrypts the envelope with their local private key, restores the data encryption key (DEK), and reads the report.
+----------------------------------------------------------------------------------------------------+

3. The Core Solidity Escrow Contract

The following ProofDesk production-grade Solidity contract implements milestone fund locking, deliverable hash anchoring, automatic payment release, and timeout dispute protection:

// proofdesk/contracts/src/AdvisoryMilestoneEscrow.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

error InvalidState(uint8 expected, uint8 actual);
error UnauthorizedCaller();
error DeadlinePassed();
error DeliverableHashAlreadyCommitted();

contract AdvisoryMilestoneEscrow is ReentrancyGuard {
    using SafeERC20 for IERC20;

    enum EscrowStatus {
        CREATED,
        DEPOSIT_LOCKED,
        DELIVERABLE_COMMITTED,
        FUNDS_RELEASED,
        DISPUTED,
        REFUNDED
    }

    struct AdvisoryOrder {
        address client;
        address advisor;
        IERC20 paymentToken;
        uint256 totalAmount;
        bytes32 deliverableCiphertextHash; // Evidence hash of the encrypted deliverable
        string deliverableStorageUri;      // Ciphertext storage location (IPFS CID or Arweave ID)
        uint64 deadlineTimestamp;          // Delivery deadline timestamp
        EscrowStatus status;
    }

    mapping(bytes32 => AdvisoryOrder) public orders;

    event OrderCreated(bytes32 indexed orderId, address indexed client, address indexed advisor, uint256 amount);
    event FundsDeposited(bytes32 indexed orderId, uint256 amount);
    event DeliverableCommitted(bytes32 indexed orderId, bytes32 ciphertextHash, string storageUri);
    event PaymentReleased(bytes32 indexed orderId, uint256 amount);
    event OrderRefunded(bytes32 indexed orderId, uint256 amount);

    /**
     * @notice Client creates and fully funds the escrow
     */
    function createAndDepositOrder(
        bytes32 orderId,
        address advisor,
        IERC20 token,
        uint256 amount,
        uint64 deadlineTimestamp
    ) external nonReentrant {
        require(orders[orderId].client == address(0), "ORDER_EXISTS");
        require(amount > 0, "INVALID_AMOUNT");
        require(deadlineTimestamp > block.timestamp, "INVALID_DEADLINE");

        orders[orderId] = AdvisoryOrder({
            client: msg.sender,
            advisor: advisor,
            paymentToken: token,
            totalAmount: amount,
            deliverableCiphertextHash: bytes32(0),
            deliverableStorageUri: "",
            deadlineTimestamp: deadlineTimestamp,
            status: EscrowStatus.DEPOSIT_LOCKED
        });

        token.safeTransferFrom(msg.sender, address(this), amount);
        emit OrderCreated(orderId, msg.sender, advisor, amount);
        emit FundsDeposited(orderId, amount);
    }

    /**
     * @notice Advisor commits the encrypted deliverable hash (non-repudiable anchor)
     */
    function commitDeliverable(
        bytes32 orderId,
        bytes32 ciphertextHash,
        string calldata storageUri
    ) external nonReentrant {
        AdvisoryOrder storage order = orders[orderId];
        if (msg.sender != order.advisor) revert UnauthorizedCaller();
        if (order.status != EscrowStatus.DEPOSIT_LOCKED) {
            revert InvalidState(uint8(EscrowStatus.DEPOSIT_LOCKED), uint8(order.status));
        }
        if (block.timestamp > order.deadlineTimestamp) revert DeadlinePassed();

        order.deliverableCiphertextHash = ciphertextHash;
        order.deliverableStorageUri = storageUri;
        order.status = EscrowStatus.DELIVERABLE_COMMITTED;

        emit DeliverableCommitted(orderId, ciphertextHash, storageUri);
    }

    /**
     * @notice Client verifies ciphertext and triggers payment to the advisor
     */
    function releasePayment(bytes32 orderId) external nonReentrant {
        AdvisoryOrder storage order = orders[orderId];
        if (msg.sender != order.client) revert UnauthorizedCaller();
        if (order.status != EscrowStatus.DELIVERABLE_COMMITTED) {
            revert InvalidState(uint8(EscrowStatus.DELIVERABLE_COMMITTED), uint8(order.status));
        }

        order.status = EscrowStatus.FUNDS_RELEASED;
        order.paymentToken.safeTransfer(order.advisor, order.totalAmount);

        emit PaymentReleased(orderId, order.totalAmount);
    }

    /**
     * @notice Timeout protection: client can claim full refund if advisor has not committed a hash by the deadline
     */
    function claimClientTimeoutRefund(bytes32 orderId) external nonReentrant {
        AdvisoryOrder storage order = orders[orderId];
        if (msg.sender != order.client) revert UnauthorizedCaller();
        if (order.status != EscrowStatus.DEPOSIT_LOCKED) {
            revert InvalidState(uint8(EscrowStatus.DEPOSIT_LOCKED), uint8(order.status));
        }
        if (block.timestamp <= order.deadlineTimestamp) {
            revert("DEADLINE_NOT_REACHED");
        }

        order.status = EscrowStatus.REFUNDED;
        order.paymentToken.safeTransfer(order.client, order.totalAmount);

        emit OrderRefunded(orderId, order.totalAmount);
    }
}

4. Client-Side WebCrypto Ciphertext Hashing and Verification

In the Next.js client, the advisor’s browser performs document encryption and fingerprinting locally, keeping the entire process out of untrusted server memory:

// proofdesk/src/crypto/deliverable-hasher.ts
import { keccak256, toHex } from 'viem';

export interface EncryptedDeliverablePayload {
  ciphertextBuffer: ArrayBuffer;
  iv: Uint8Array;
  authTag: Uint8Array;
  computedKeccakHash: `0x${string}`;
}

export class DeliverableCryptoEngine {
  /**
   * @notice Advisor: encrypt the report with a random DEK and compute a tamper-resistant hash
   */
  public static async encryptAndAnchorDeliverable(
    plaintextReportUtf8: string,
    dataEncryptionKey: CryptoKey
  ): Promise<EncryptedDeliverablePayload> {
    const iv = window.crypto.getRandomValues(new Uint8Array(12)); // 96-bit AES-GCM IV
    const encoder = new TextEncoder();
    const encodedData = encoder.encode(plaintextReportUtf8);

    // Perform client-side WebCrypto AES-GCM-256 encryption
    const ciphertextWithTag = await window.crypto.subtle.encrypt(
      {
        name: 'AES-GCM',
        iv: iv,
        tagLength: 128,
      },
      dataEncryptionKey,
      encodedData
    );

    // Compute Keccak256 of the complete ciphertext payload as the on-chain anchor
    const uint8Payload = new Uint8Array(ciphertextWithTag);
    const computedKeccakHash = keccak256(toHex(uint8Payload));

    return {
      ciphertextBuffer: ciphertextWithTag,
      iv,
      authTag: uint8Payload.slice(uint8Payload.length - 16),
      computedKeccakHash,
    };
  }

  /**
   * @notice Client: preflight-check that downloaded ciphertext exactly matches the on-chain hash
   */
  public static verifyCiphertextIntegrity(
    downloadedCiphertext: ArrayBuffer,
    expectedOnChainHash: `0x${string}`
  ): boolean {
    const uint8Payload = new Uint8Array(downloadedCiphertext);
    const localHash = keccak256(toHex(uint8Payload));
    return localHash.toLowerCase() === expectedOnChainHash.toLowerCase();
  }
}

5. Comparing Traditional Contracts with On-Chain Escrow and Encrypted Delivery

The following table compares ProofDesk with conventional commercial delivery:

Delivery dimension Traditional: emailed PDF + bank wire Common third-party platform: Upwork / Escrow.com This approach: ProofDesk on-chain escrow and hash anchoring
Deposit and final-payment safety Very low (advisors face payment disputes; clients face abandonment) Moderate (platform holds funds but charges 10%~20%) Very high (funds locked by contract code, no centralized commission)
Deliverable version disputes Serious (client can claim the file differs from the agreed version) Human arbitrators must read plaintext, exposing business secrets Zero disputes (strict on-chain ciphertextHash evidence)
Confidentiality Plaintext remains on mail servers and employee computers Platform support can inspect plaintext, creating leakage risk End-to-end zero knowledge (platform and contract see only AES ciphertext)
Settlement speed International wire takes 3 ~ 7 business days Mandatory withdrawal holds, typically 5 ~ 14 days Sub-second receipt (client authorization triggers USDC transfer with one click)
Missed-deadline handling Legal demand letters; enforcement often costs more than the loss Lengthy support claims and disputes Built-in automatic timeout refunds; client can withdraw after missed delivery

6. Integrating Key Backups and Memory Hygiene

Across the confidential consulting lifecycle, deliverable hash anchoring establishes trust during fulfillment. It must work with the other two parts of secure delivery:

  1. Tamper-resistant key backups: After acceptance and payment release, the advisor’s decryption envelope uses the Tamper-Evident Key Backup Schema. Strong orderId binding and AAD prevent decryption failures caused by clients selecting the wrong key file.
  2. Client-side memory hygiene: After decryption, the browser must follow Browser Memory Hygiene for Decrypted Documents: never persist plaintext to LocalStorage or global state, and actively erase memory with ArrayBuffer.fill(0) when the page is destroyed.

Consulting and Source-Code Delivery

If you run a specialist security audit firm, strategic research organization, law firm, or independent full-stack team and need a modern delivery portal that eliminates final-payment disputes while protecting both parties’ intellectual property and funds: