.do
Use Cases

Marketplace Business

Build autonomous two-sided marketplace platforms with Business-as-Code

Build a two-sided marketplace platform that connects buyers and sellers autonomously.

Overview

Marketplace businesses handle:

  • Seller onboarding and verification
  • Listing management
  • Intelligent matching
  • Transaction facilitation
  • Trust and safety
  • Dispute resolution
  • Commission processing

Core Implementation

1. Platform Setup

import $, { db, on, send, ai } from 'sdk.do'

const marketplace = await $.WebSite.create({
  $type: 'WebSite',
  name: 'FreelanceHub',
  description: 'Connect businesses with freelance professionals',
  url: 'https://freelancehub.com',
})

2. Seller Onboarding

on($.Seller.registered, async (seller) => {
  // Verify seller identity
  const verification = await ai.analyze('identity-verification', {
    seller,
    documents: seller.documents,
    socialProfiles: seller.socialProfiles,
  })

  if (verification.confidence > 0.9) {
    // Auto-approve
    await db.update($.Person, seller.$id, {
      verificationStatus: 'verified',
      verifiedAt: new Date(),
    })

    await send($.Seller.verified, seller)
  } else {
    // Manual review required
    await send($.Review.request, {
      type: 'seller-verification',
      seller,
      verification,
    })
  }
})

// Create seller profile
on($.Seller.verified, async (seller) => {
  // AI generates optimized profile
  const profile = await ai.generate('seller-profile', {
    seller,
    skills: seller.skills,
    experience: seller.experience,
  })

  await db.update($.Person, seller.$id, {
    description: profile.description,
    headline: profile.headline,
    profileComplete: true,
  })

  await send($.Email.send, {
    to: seller.email,
    template: 'seller-approved',
    data: { seller },
  })
})

3. Listing Creation

on($.Offer.created, async (offer) => {
  // AI enhances listing
  const enhancements = await ai.generate('listing-optimization', {
    offer,
    category: offer.category,
    seller: offer.seller,
    market: await analyzeMarket(offer.category),
  })

  await db.update($.Offer, offer.$id, {
    name: enhancements.title,
    description: enhancements.description,
    keywords: enhancements.keywords,
  })

  // AI suggests pricing
  const pricing = await ai.decide('marketplace-pricing', {
    offer,
    category: offer.category,
    competition: await db.list($.Offer, {
      where: { category: offer.category },
    }),
  })

  if (Math.abs(pricing.recommendedPrice - offer.price) / offer.price > 0.2) {
    // Significant difference, notify seller
    await send($.Notification.send, {
      to: offer.seller,
      type: 'pricing-suggestion',
      data: {
        currentPrice: offer.price,
        suggestedPrice: pricing.recommendedPrice,
        reasoning: pricing.explanation,
      },
    })
  }

  await send($.Offer.published, offer)
})

4. Intelligent Matching

// @errors: 7006
// @filename: sdk.do.d.ts
declare const $: any
declare const ai: any
declare function on(event: any, handler: Function): any
declare function send(event: any, data: any): Promise<void>

// @filename: example.ts
// ---cut---
import { $, ai, on, send } from 'sdk.do'

// AI-powered marketplace matching
on($.Request.created, async (request) => {
  // ^^
  // AI analyzes multiple factors to find best matches
  const matches = await ai.recommend({
    //              ^?
    type: $.Offer,
    for: request,
    strategy: 'best-fit',
    factors: ['skills-match', 'price-fit', 'availability', 'reputation', 'past-performance'],
    //           ^^^^^^^^^^^^^^
    limit: 10,
  })

  // Notify top 5 sellers of opportunity
  for (const match of matches.slice(0, 5)) {
    await send($.Notification.send, {
      to: match.seller,
      type: 'new-opportunity',
      data: {
        request,
        fitScore: match.score,
        reasoning: match.explanation,
        //                ^^^^^^^^^^^^^^^^^^^
      },
    })
  }

  // Auto-match if confidence exceeds threshold
  if (matches[0].score > 0.95) {
    //              ^^^^^
    await send($.Match.create, {
      request,
      offer: matches[0],
      confidence: matches[0].score,
      auto: true,
      //    ^^^^^^^^^^^
    })
  }

  // Show matches to buyer
  await send($.UI.showMatches, {
    buyer: request.buyer,
    matches,
  })
})

5. Transaction Management

on($.Transaction.started, async (transaction) => {
  // Hold payment in escrow
  const escrow = await send($.Payment.escrow, {
    buyer: transaction.buyer,
    amount: transaction.agreedPrice,
    releaseConditions: {
      sellerDelivered: false,
      buyerApproved: false,
      timeoutDays: 14,
    },
  })

  await db.update($.Transaction, transaction.$id, {
    escrow: escrow.$id,
    status: 'in-progress',
  })

  // Create milestones if applicable
  if (transaction.milestones) {
    for (const milestone of transaction.milestones) {
      await $.Action.create({
        $type: 'Action',
        name: milestone.name,
        agent: transaction.seller,
        object: transaction,
        actionStatus: 'PotentialActionStatus',
        expectedDuration: milestone.duration,
      })
    }
  }
})

// Seller marks as complete
on($.Transaction.sellerCompleted, async (transaction) => {
  // Notify buyer for review
  await send($.Notification.send, {
    to: transaction.buyer,
    type: 'review-required',
    data: { transaction },
    cta: {
      text: 'Review Work',
      action: $.Transaction.review,
    },
  })

  // Auto-release after timeout
  await send($.Task.schedule, {
    action: async () => {
      const current = await db.get($.Transaction, transaction.$id)
      if (current.status === 'awaiting-review') {
        await send($.Transaction.autoApprove, { transaction: current })
      }
    },
    runAt: addDays(new Date(), 3), // 3-day auto-approval
  })
})

// Buyer approves
on($.Transaction.buyerApproved, async (transaction) => {
  // Release escrow to seller
  await send($.Payment.releaseEscrow, {
    escrow: transaction.escrow,
    to: transaction.seller,
    amount: transaction.agreedPrice,
  })

  // Calculate and collect commission
  const commission = transaction.agreedPrice * 0.15 // 15%
  await send($.Payment.collectCommission, {
    transaction,
    amount: commission,
  })

  // Update transaction
  await db.update($.Transaction, transaction.$id, {
    status: 'completed',
    completedAt: new Date(),
  })

  // Update reputation scores
  await send($.Reputation.update, {
    seller: transaction.seller,
    buyer: transaction.buyer,
    transaction,
  })

  await send($.Transaction.completed, transaction)
})

6. Trust & Safety

// Monitor transaction quality
on($.Transaction.completed, async (transaction) => {
  // AI analyzes transaction
  const analysis = await ai.analyze('transaction-quality', {
    transaction,
    communications: await db.related(transaction, $.includes, $.Message),
    timeline: transaction.timeline,
    reviews: transaction.reviews,
  })

  if (analysis.score < 0.6) {
    // Potential issue detected
    await send($.Transaction.flagged, {
      transaction,
      concerns: analysis.concerns,
      severity: analysis.severity,
    })

    if (analysis.severity === 'high') {
      // Immediate escalation
      await send($.Notification.send, {
        to: $.Role.TrustAndSafety,
        priority: 'urgent',
        message: 'High-risk transaction detected',
        data: { transaction, analysis },
      })
    }
  }

  // Update user reputation
  await db.increment(transaction.seller, $.reputation.score, analysis.sellerRating)
  await db.increment(transaction.buyer, $.reputation.score, analysis.buyerRating)
})

// Content moderation
on($.Message.sent, async (message) => {
  // AI screens for policy violations
  const screening = await ai.analyze('content-safety', {
    content: message.text,
    context: {
      sender: message.sender,
      recipient: message.recipient,
      transaction: message.transaction,
    },
  })

  if (screening.flagged) {
    // Hide message, send for review
    await db.update($.Message, message.$id, {
      hidden: true,
      flagReason: screening.concerns,
    })

    await send($.Review.request, {
      type: 'message-moderation',
      message,
      screening,
    })

    if (screening.severity === 'high') {
      // Immediate action
      await send($.Account.suspend, {
        user: message.sender,
        reason: screening.concerns,
      })
    }
  }
})

7. Dispute Resolution

on($.Dispute.opened, async (dispute) => {
  // AI analyzes dispute
  const analysis = await ai.analyze('dispute-assessment', {
    dispute,
    transaction: dispute.transaction,
    communications: await db.related(dispute.transaction, $.includes, $.Message),
    evidence: dispute.evidence,
  })

  if (analysis.canAutoResolve && analysis.confidence > 0.9) {
    // AI resolves automatically
    await send($.Dispute.resolve, {
      dispute,
      resolution: analysis.resolution,
      reasoning: analysis.explanation,
      method: 'automatic',
    })
  } else {
    // Assign to mediator
    const mediator = await ai.decide('mediator-assignment', {
      dispute,
      analysis,
      mediators: await db.list($.Person, {
        where: { role: 'mediator', status: 'available' },
      }),
    })

    await send($.Dispute.assigned, {
      dispute,
      mediator: mediator.selected,
    })
  }
})

on($.Dispute.resolved, async ({ dispute, resolution }) => {
  // Execute resolution
  if (resolution.action === 'refund-buyer') {
    await send($.Payment.refund, {
      escrow: dispute.transaction.escrow,
      to: dispute.transaction.buyer,
      amount: resolution.amount,
    })
  } else if (resolution.action === 'pay-seller') {
    await send($.Payment.releaseEscrow, {
      escrow: dispute.transaction.escrow,
      to: dispute.transaction.seller,
      amount: resolution.amount,
    })
  } else if (resolution.action === 'split') {
    await send($.Payment.split, {
      escrow: dispute.transaction.escrow,
      buyer: resolution.buyerAmount,
      seller: resolution.sellerAmount,
    })
  }

  await db.update($.Dispute, dispute.$id, {
    status: 'resolved',
    resolvedAt: new Date(),
  })

  // Notify parties
  await send($.Email.send, {
    to: [dispute.transaction.buyer.email, dispute.transaction.seller.email],
    template: 'dispute-resolved',
    data: { dispute, resolution },
  })
})

8. Marketplace Analytics

// Calculate marketplace health metrics
async function calculateMarketplaceMetrics() {
  return {
    // GMV (Gross Merchandise Volume)
    gmv: await db.aggregate($.Transaction, {
      where: {
        status: 'completed',
        completedAt: { $gte: subDays(new Date(), 30) },
      },
      aggregations: {
        total: { $sum: 'agreedPrice' },
      },
    }),

    // Take rate (commission percentage)
    takeRate: 0.15,

    // Active sellers
    activeSellers: await db.count($.Person, {
      where: {
        role: 'seller',
        lastActive: { $gte: subDays(new Date(), 30) },
      },
    }),

    // Active buyers
    activeBuyers: await db.count($.Person, {
      where: {
        role: 'buyer',
        lastPurchase: { $gte: subDays(new Date(), 30) },
      },
    }),

    // Match rate
    matchRate: await db.analyze('match-success-rate', {
      timeRange: '30d',
    }),

    // Average transaction value
    atv: await db.aggregate($.Transaction, {
      where: { status: 'completed' },
      aggregations: {
        avg: { $avg: 'agreedPrice' },
      },
    }),
  }
}

// Monitor and alert
setInterval(async () => {
  const metrics = await calculateMarketplaceMetrics()

  if (metrics.matchRate < 0.3) {
    await send($.Alert.send, {
      type: 'low-match-rate',
      severity: 'high',
      data: metrics,
    })
  }
}, 86400000) // Daily

Complete Example

Full code at:

Key Takeaways

  1. Trust is Critical: Verification, reputation, safety
  2. Matching is Key: AI-powered intelligent matching
  3. Fair Transactions: Escrow, dispute resolution
  4. Two-Sided Growth: Balance supply and demand
  5. Quality Control: Continuous monitoring

Next: Architecture →