From 3f65a9ea07e1da3453606b1461fce1127c6d8ed4 Mon Sep 17 00:00:00 2001 From: Wintermute Date: Tue, 1 Sep 2026 11:08:16 -0400 Subject: [PATCH] feat(desktop): root market contracts in channels Signed-off-by: Wintermute --- desktop/src/app/routes/ChannelRouteScreen.tsx | 27 + desktop/src/app/routes/market.tsx | 28 +- .../src/features/channels/ui/ChannelPane.tsx | 40 +- .../market/lib/MarketChannelContext.tsx | 23 + .../market/lib/marketProtocol.test.mjs | 483 +++++++++--- .../src/features/market/lib/marketProtocol.ts | 208 ++++- .../market/lib/useLiveMarketScenario.ts | 35 - .../features/market/lib/useMarketChannels.ts | 116 +++ .../features/market/ui/MarketChannelHome.tsx | 26 + .../features/market/ui/MarketChannelIntro.tsx | 11 + .../features/market/ui/MarketContractCard.tsx | 75 ++ .../src/features/market/ui/MarketScreen.tsx | 722 ++++++++---------- .../market/ui/marketChannelComposer.ts | 12 + docs/market-sandbox-v0.md | 87 +-- scripts/market-sandbox.sh | 106 ++- 15 files changed, 1279 insertions(+), 720 deletions(-) create mode 100644 desktop/src/features/market/lib/MarketChannelContext.tsx delete mode 100644 desktop/src/features/market/lib/useLiveMarketScenario.ts create mode 100644 desktop/src/features/market/lib/useMarketChannels.ts create mode 100644 desktop/src/features/market/ui/MarketChannelHome.tsx create mode 100644 desktop/src/features/market/ui/MarketChannelIntro.tsx create mode 100644 desktop/src/features/market/ui/MarketContractCard.tsx create mode 100644 desktop/src/features/market/ui/marketChannelComposer.ts diff --git a/desktop/src/app/routes/ChannelRouteScreen.tsx b/desktop/src/app/routes/ChannelRouteScreen.tsx index 50371bc369..1b375422d9 100644 --- a/desktop/src/app/routes/ChannelRouteScreen.tsx +++ b/desktop/src/app/routes/ChannelRouteScreen.tsx @@ -25,6 +25,8 @@ import { shouldUseScopedProjectHomeLookup, } from "@/features/projects/projectSnapshot"; import { ProjectChannelHome } from "@/features/projects/ui/ProjectChannelHome"; +import { useMarketAnnouncement } from "@/features/market/lib/useMarketChannels"; +import { MarketChannelHome } from "@/features/market/ui/MarketChannelHome"; import { useIdentityQuery } from "@/shared/api/hooks"; import { getEventById } from "@/shared/api/tauri"; import type { RelayEvent } from "@/shared/api/types"; @@ -159,6 +161,7 @@ export function ChannelRouteScreen({ ); const projectHome = enumeratedProjectHome ?? projectHomeLookupQuery.data ?? null; + const marketAnnouncement = useMarketAnnouncement(channelId); const [targetMessageEvents, setTargetMessageEvents] = React.useState< RelayEvent[] >(() => { @@ -308,6 +311,30 @@ export function ChannelRouteScreen({ ); } + if (activeChannel && marketAnnouncement && !isHuddleTranscript) { + return ( + { + void closeForumPost(channelId); + }} + onSelectForumPost={(postId) => { + void goForumPost(channelId, postId); + }} + selectedForumPostId={selectedPostId} + targetForumReplyId={targetReplyId} + targetMessageEvents={targetMessageEvents} + targetMessageId={targetMessageId} + targetSearchMessageId={activeSearchHighlight?.messageId} + targetSearchQuery={activeSearchHighlight?.query} + /> + ); + } + return ( ; export const Route = createFileRoute("/market")({ - validateSearch: (search: Record): MarketRouteSearch => ({ - market: - typeof search.market === "string" && search.market.length <= 120 - ? search.market - : undefined, - scenario: isMarketScenarioId(search.scenario) ? search.scenario : undefined, - }), + validateSearch: (search: Record): MarketRouteSearch => + Object.fromEntries( + Object.entries(search).filter( + (entry): entry is [string, string] => typeof entry[1] === "string", + ), + ), component: MarketRouteComponent, }); @@ -29,15 +21,11 @@ const MarketScreen = React.lazy(async () => { }); function MarketRouteComponent() { - const search = Route.useSearch(); return ( } > - + ); } diff --git a/desktop/src/features/channels/ui/ChannelPane.tsx b/desktop/src/features/channels/ui/ChannelPane.tsx index d53e8dbbda..77c0731cf0 100644 --- a/desktop/src/features/channels/ui/ChannelPane.tsx +++ b/desktop/src/features/channels/ui/ChannelPane.tsx @@ -1,3 +1,4 @@ +// biome-ignore-all format: line-count ratchet requires compact market integration in this legacy component import * as React from "react"; import { LogIn } from "lucide-react"; import { AnimatePresence } from "motion/react"; @@ -65,6 +66,7 @@ import * as agentSessionSelection from "@/features/channels/ui/agentSessionSelec import { usePrepareDmSendChannel } from "@/features/channels/ui/usePrepareDmSendChannel"; import { useChannelPaneMessages } from "@/features/channels/ui/useChannelPaneMessages"; import { useRoutedMessageEdit } from "@/features/channels/ui/useRoutedMessageEdit"; +import { MarketChannelIntro } from "@/features/market/ui/MarketChannelIntro"; import { useMarketObserver } from "@/features/market/ui/marketChannelComposer"; import { Button } from "@/shared/ui/button"; import { useRenderScopedReactionHydration } from "@/features/messages/lib/useRenderScopedReactionHydration"; import { isWelcomeExperienceChannel as isWelcomeExperience } from "@/features/onboarding/welcome"; @@ -199,8 +201,8 @@ export const ChannelPane = React.memo(function ChannelPane({ targetSearchMessageId, targetSearchQuery, ); - const [isMainDeferredEditPending, setMainDeferredEditPending] = - React.useState(false); + const [isMainDeferredEditPending, setMainDeferredEditPending] = React.useState(false); + const isMarketObserver = useMarketObserver(agentPubkeys, currentPubkey); const isNonMemberView = activeChannel !== null && !activeChannel.isMember && @@ -262,9 +264,7 @@ export const ChannelPane = React.memo(function ChannelPane({ !activeChannel?.isMember || activeChannel.archivedAt !== null || activeChannel.channelType === "forum" || - timeoutState.active || - isModerationDmChannel || - isSending; + timeoutState.active || isModerationDmChannel || isMarketObserver || isSending; const knownAgentPubkeys = React.useMemo(() => { const pubkeys = new Set(); for (const pubkey of agentPubkeys ?? []) { @@ -634,9 +634,7 @@ export const ChannelPane = React.memo(function ChannelPane({ hideDayDividers={isHuddleTranscript} alwaysShowMessageIdentity={isHuddleTranscript} hideAgentAccessBadges={isHuddleTranscript} - pinnedIntro={ - isHuddleTranscript ? : undefined - } + pinnedIntro={isHuddleTranscript ? : } huddleMemberPubkeys={huddleMemberPubkeys} huddleMemberPubkeysPending={huddleMemberPubkeysPending} isFetchingOlder={isFetchingOlder} @@ -778,18 +776,20 @@ export const ChannelPane = React.memo(function ChannelPane({ placeholder={ timeoutState.active ? "You're timed out by community moderators." - : isModerationDmChannel - ? "This channel is read-only." - : activeChannel?.archivedAt - ? "Archived channels are read-only." - : activeChannel?.channelType === "forum" - ? "Forum posting is not wired in this pass." - : activeChannel - ? activeChannel.channelType === "dm" && - directMessageIntro - ? `Message ${directMessageIntro.displayName}` - : `Message #${activeChannel.name}` - : "Select a channel" + : isMarketObserver + ? "Market channels are observer-only for humans." + : isModerationDmChannel + ? "This channel is read-only." + : activeChannel?.archivedAt + ? "Archived channels are read-only." + : activeChannel?.channelType === "forum" + ? "Forum posting is not wired in this pass." + : activeChannel + ? activeChannel.channelType === "dm" && + directMessageIntro + ? `Message ${directMessageIntro.displayName}` + : `Message #${activeChannel.name}` + : "Select a channel" } showTopBorder={false} /> diff --git a/desktop/src/features/market/lib/MarketChannelContext.tsx b/desktop/src/features/market/lib/MarketChannelContext.tsx new file mode 100644 index 0000000000..a1729b2aac --- /dev/null +++ b/desktop/src/features/market/lib/MarketChannelContext.tsx @@ -0,0 +1,23 @@ +import * as React from "react"; + +import type { MarketProjection } from "@/features/market/lib/marketProtocol"; + +const MarketChannelContext = React.createContext(null); + +export function MarketChannelProvider({ + children, + projection, +}: { + children: React.ReactNode; + projection: MarketProjection; +}) { + return ( + + {children} + + ); +} + +export function useMarketChannel(): MarketProjection | null { + return React.useContext(MarketChannelContext); +} diff --git a/desktop/src/features/market/lib/marketProtocol.test.mjs b/desktop/src/features/market/lib/marketProtocol.test.mjs index 60e837bdfe..3e2f5e2730 100644 --- a/desktop/src/features/market/lib/marketProtocol.test.mjs +++ b/desktop/src/features/market/lib/marketProtocol.test.mjs @@ -3,10 +3,14 @@ import test from "node:test"; import { MARKET_PROTOCOL, + marketAnnouncementMatchesProjection, parseMarketEnvelope, - projectMarketNotes, + projectMarketAnnouncements, + projectMarketChannel, } from "./marketProtocol.ts"; +const CHANNEL_ID = "123e4567-e89b-12d3-a456-426614174000"; +const OTHER_CHANNEL_ID = "123e4567-e89b-12d3-a456-426614174001"; const SELLER = "a".repeat(64); const BUYER = "b".repeat(64); const LISTING_ID = "1".repeat(64); @@ -14,84 +18,130 @@ const RESPONSE_ID = "2".repeat(64); const AWARD_ID = "3".repeat(64); const FULFILLMENT_ID = "4".repeat(64); -function note(id, pubkey, createdAt, envelope) { - return { id, pubkey, createdAt, content: JSON.stringify(envelope), tags: [] }; +function note( + id, + pubkey, + createdAt, + envelope, + tags = [["h", envelope.channelId]], +) { + return { id, pubkey, createdAt, content: JSON.stringify(envelope), tags }; } function listing(overrides = {}) { return { - protocol: MARKET_PROTOCOL, - type: "listing", - marketId: "incident-report", - version: 1, - listing: { - actorName: "Seller Agent", - direction: "offer", - mechanism: "fixed", - title: "Incident report", - summary: "A cited report delivered after award.", - quantity: 1, - priceSats: 50, - deliveryMinutes: 120, - ...overrides, - }, + actorName: "Seller Agent", + direction: "offer", + mechanism: "fixed", + title: "Incident report", + summary: "A cited report delivered after award.", + quantity: 1, + priceSats: 50, + deliveryMinutes: 120, + ...overrides, }; } -test("parseMarketEnvelope accepts v0 and rejects unrelated Pulse notes", () => { +function contract(overrides = {}) { + return { + protocol: MARKET_PROTOCOL, + type: "contract", + channelId: CHANNEL_ID, + version: 1, + listing: listing(overrides), + }; +} + +function announcement(overrides = {}) { + return { + ...contract(overrides), + type: "announcement", + listingEventId: LISTING_ID, + }; +} + +function lifecycle(type, fields) { + return { + protocol: MARKET_PROTOCOL, + type, + channelId: CHANNEL_ID, + listingEventId: LISTING_ID, + ...fields, + }; +} + +test("parseMarketEnvelope accepts channel contracts and rejects legacy feeds", () => { assert.equal(parseMarketEnvelope("hello Pulse"), null); assert.equal(parseMarketEnvelope('{"protocol":"other"}'), null); - assert.equal(parseMarketEnvelope(JSON.stringify(listing()))?.type, "listing"); + assert.equal( + parseMarketEnvelope(JSON.stringify(contract()))?.type, + "contract", + ); + assert.equal( + parseMarketEnvelope( + JSON.stringify({ + ...contract(), + channelId: undefined, + marketId: "legacy", + }), + ), + null, + ); }); -test("projectMarketNotes folds offer through fake settlement", () => { - const notes = [ - note(LISTING_ID, SELLER, 100, listing()), - note(RESPONSE_ID, BUYER, 101, { - protocol: MARKET_PROTOCOL, - type: "response", - marketId: "incident-report", - listingEventId: LISTING_ID, - actorName: "Buyer Agent", - quantity: 1, - amountSats: 50, - message: "I reserve the report.", - }), - note(AWARD_ID, SELLER, 102, { - protocol: MARKET_PROTOCOL, - type: "award", - marketId: "incident-report", - listingEventId: LISTING_ID, - responseEventId: RESPONSE_ID, - actorName: "Seller Agent", - quantity: 1, - amountSats: 50, - }), - note(FULFILLMENT_ID, SELLER, 103, { - protocol: MARKET_PROTOCOL, - type: "fulfillment", - marketId: "incident-report", - listingEventId: LISTING_ID, - awardEventId: AWARD_ID, - actorName: "Seller Agent", - message: "Report delivered with cited evidence.", - }), - note("5".repeat(64), BUYER, 104, { - protocol: MARKET_PROTOCOL, - type: "settlement", - marketId: "incident-report", - listingEventId: LISTING_ID, - awardEventId: AWARD_ID, - fulfillmentEventId: FULFILLMENT_ID, - actorName: "Buyer Agent", - amountSats: 50, - }), +test("projectMarketChannel folds a channel contract through fake settlement", () => { + const events = [ + note(LISTING_ID, SELLER, 100, contract()), + note( + RESPONSE_ID, + BUYER, + 101, + lifecycle("response", { + actorName: "Buyer Agent", + quantity: 1, + amountSats: 50, + message: "I reserve the report.", + }), + ), + note( + AWARD_ID, + SELLER, + 102, + lifecycle("award", { + responseEventId: RESPONSE_ID, + actorName: "Seller Agent", + quantity: 1, + amountSats: 50, + }), + ), + note( + FULFILLMENT_ID, + SELLER, + 103, + lifecycle("fulfillment", { + awardEventId: AWARD_ID, + actorName: "Seller Agent", + message: "Report delivered with cited evidence.", + }), + ), + note( + "5".repeat(64), + BUYER, + 104, + lifecycle("settlement", { + awardEventId: AWARD_ID, + fulfillmentEventId: FULFILLMENT_ID, + actorName: "Buyer Agent", + amountSats: 50, + }), + ), ]; - const projection = projectMarketNotes(notes); + const projection = projectMarketChannel(events, CHANNEL_ID); assert.ok(projection); + assert.equal(projection.channelId, CHANNEL_ID); + assert.equal(projection.contractAuthorPubkey, SELLER); assert.equal(projection.scenario.status, "Fulfilled"); - assert.equal(projection.scenario.title, "Incident report"); assert.equal(projection.scenario.activity.length, 5); assert.equal( projection.scenario.activity[0].title, @@ -100,86 +150,111 @@ test("projectMarketNotes folds offer through fake settlement", () => { assert.deepEqual(projection.rejected, []); }); -test("projectMarketNotes selects an explicit market", () => { - const other = listing(); - other.marketId = "other-market"; - other.listing.title = "Other listing"; - const projection = projectMarketNotes( +test("channel tags and the first top-level contract define the canonical market", () => { + const secondContractId = "8".repeat(64); + const projection = projectMarketChannel( [ - note(LISTING_ID, SELLER, 100, listing()), - note("9".repeat(64), BUYER, 99, other), + note("9".repeat(64), SELLER, 98, contract(), [["h", OTHER_CHANNEL_ID]]), + note("7".repeat(64), SELLER, 99, contract(), [ + ["h", CHANNEL_ID], + ["e", "6".repeat(64), "", "reply"], + ]), + note(LISTING_ID, SELLER, 100, contract()), + note(secondContractId, SELLER, 101, contract({ title: "Replacement" })), ], - "incident-report", + CHANNEL_ID, ); + assert.ok(projection); assert.equal(projection.scenario.title, "Incident report"); + assert.deepEqual(projection.rejected, [ + { + eventId: secondContractId, + reason: "channel already has a canonical contract", + }, + ]); }); -test("projectMarketNotes rejects overselling and unauthorized awards", () => { - const notes = [ - note(LISTING_ID, SELLER, 100, listing()), - note(RESPONSE_ID, BUYER, 101, { - protocol: MARKET_PROTOCOL, - type: "response", - marketId: "incident-report", - listingEventId: LISTING_ID, - actorName: "Buyer Agent", - quantity: 1, - amountSats: 50, - message: "Reserve one.", - }), - note(AWARD_ID, BUYER, 102, { - protocol: MARKET_PROTOCOL, - type: "award", - marketId: "incident-report", - listingEventId: LISTING_ID, - responseEventId: RESPONSE_ID, - actorName: "Buyer Agent", - quantity: 1, - amountSats: 50, - }), - ]; +test("projectMarketChannel rejects cross-contract and unauthorized transitions", () => { + const wrongListingId = "9".repeat(64); + const projection = projectMarketChannel( + [ + note(LISTING_ID, SELLER, 100, contract()), + note( + RESPONSE_ID, + BUYER, + 101, + lifecycle("response", { + listingEventId: wrongListingId, + actorName: "Buyer Agent", + quantity: 1, + amountSats: 50, + message: "Wrong contract.", + }), + ), + note( + "6".repeat(64), + BUYER, + 102, + lifecycle("award", { + responseEventId: RESPONSE_ID, + actorName: "Buyer Agent", + quantity: 1, + amountSats: 50, + }), + ), + ], + CHANNEL_ID, + ); - const projection = projectMarketNotes(notes); assert.ok(projection); assert.equal(projection.scenario.status, "Open"); - assert.equal(projection.rejected[0].reason, "only listing author may award"); + assert.deepEqual( + projection.rejected.map(({ reason }) => reason), + [ + "listingEventId does not target channel contract", + "only listing author may award", + ], + ); }); test("reverse auction enforces the minimum decrement", () => { - const auction = listing({ + const auction = contract({ direction: "request", mechanism: "reverse-auction", - quantity: 1, priceSats: undefined, maxBudgetSats: 100, minimumDecrementSats: 10, }); - const notes = [ - note(LISTING_ID, SELLER, 100, auction), - note(RESPONSE_ID, BUYER, 101, { - protocol: MARKET_PROTOCOL, - type: "response", - marketId: "incident-report", - listingEventId: LISTING_ID, - actorName: "Bidder One", - quantity: 1, - amountSats: 90, - message: "I bid 90.", - }), - note("6".repeat(64), "c".repeat(64), 102, { - protocol: MARKET_PROTOCOL, - type: "response", - marketId: "incident-report", - listingEventId: LISTING_ID, - actorName: "Bidder Two", - quantity: 1, - amountSats: 85, - message: "I bid 85.", - }), - ]; + const projection = projectMarketChannel( + [ + note(LISTING_ID, SELLER, 100, auction), + note( + RESPONSE_ID, + BUYER, + 101, + lifecycle("response", { + actorName: "Bidder One", + quantity: 1, + amountSats: 90, + message: "I bid 90.", + }), + ), + note( + "6".repeat(64), + "c".repeat(64), + 102, + lifecycle("response", { + actorName: "Bidder Two", + quantity: 1, + amountSats: 85, + message: "I bid 85.", + }), + ), + ], + CHANNEL_ID, + ); - const projection = projectMarketNotes(notes); assert.ok(projection); assert.equal(projection.scenario.liveMetrics[1].value, "1"); assert.equal( @@ -187,3 +262,163 @@ test("reverse auction enforces the minimum decrement", () => { "bid does not meet minimum decrement", ); }); + +test("a lifecycle envelope cannot be accepted twice under one event id", () => { + const sharedEventId = RESPONSE_ID; + const projection = projectMarketChannel( + [ + note(LISTING_ID, SELLER, 100, contract()), + note( + sharedEventId, + BUYER, + 101, + lifecycle("response", { + actorName: "Buyer Agent", + quantity: 1, + amountSats: 50, + message: "Valid response.", + }), + ), + note( + sharedEventId, + BUYER, + 102, + lifecycle("response", { + listingEventId: "9".repeat(64), + actorName: "Buyer Agent", + quantity: 1, + amountSats: 50, + message: "Invalid duplicate fixture.", + }), + ), + ], + CHANNEL_ID, + ); + + assert.ok(projection); + assert.equal( + projection.scenario.activity.filter( + (activity) => activity.title === "Response submitted", + ).length, + 1, + ); + assert.equal(projection.rejected.length, 1); +}); + +test("responses close on time while awarded work can finish afterward", () => { + const closedContract = contract({ closesAt: 101 }); + const lateResponseId = "6".repeat(64); + const projection = projectMarketChannel( + [ + note(LISTING_ID, SELLER, 100, closedContract), + note( + RESPONSE_ID, + BUYER, + 101, + lifecycle("response", { + actorName: "Buyer Agent", + quantity: 1, + amountSats: 50, + message: "On-time response.", + }), + ), + note( + AWARD_ID, + SELLER, + 102, + lifecycle("award", { + responseEventId: RESPONSE_ID, + actorName: "Seller Agent", + quantity: 1, + amountSats: 50, + }), + ), + note( + FULFILLMENT_ID, + SELLER, + 103, + lifecycle("fulfillment", { + awardEventId: AWARD_ID, + actorName: "Seller Agent", + message: "Delivered after bidding closed.", + }), + ), + note( + "5".repeat(64), + BUYER, + 104, + lifecycle("settlement", { + awardEventId: AWARD_ID, + fulfillmentEventId: FULFILLMENT_ID, + actorName: "Buyer Agent", + amountSats: 50, + }), + ), + note( + lateResponseId, + "c".repeat(64), + 105, + lifecycle("response", { + actorName: "Late Buyer", + quantity: 1, + amountSats: 50, + message: "Too late.", + }), + ), + ], + CHANNEL_ID, + ); + + assert.ok(projection); + assert.equal(projection.scenario.status, "Fulfilled"); + assert.deepEqual(projection.rejected, [ + { + eventId: lateResponseId, + reason: "response arrived after listing close", + }, + ]); +}); + +test("Pulse announcements are only index pointers and must match channel truth", () => { + const pulseNote = note("f".repeat(64), SELLER, 110, announcement(), []); + const spoofedAnnouncement = note( + "e".repeat(64), + BUYER, + 111, + announcement({ title: "Spoof" }), + [], + ); + const announcements = projectMarketAnnouncements([ + pulseNote, + spoofedAnnouncement, + ]); + const projection = projectMarketChannel( + [note(LISTING_ID, SELLER, 100, contract())], + CHANNEL_ID, + ); + + assert.equal(announcements.length, 1); + assert.ok(projection); + assert.equal(announcements[0].channelId, CHANNEL_ID); + assert.equal( + marketAnnouncementMatchesProjection(announcements[0], projection), + true, + ); + assert.equal( + marketAnnouncementMatchesProjection( + { ...announcements[0], publisherPubkey: BUYER }, + projection, + ), + false, + ); + assert.equal( + marketAnnouncementMatchesProjection( + { + ...announcements[0], + listing: { ...announcements[0].listing, title: "Spoof" }, + }, + projection, + ), + false, + ); +}); diff --git a/desktop/src/features/market/lib/marketProtocol.ts b/desktop/src/features/market/lib/marketProtocol.ts index aafa057024..a27f3c04df 100644 --- a/desktop/src/features/market/lib/marketProtocol.ts +++ b/desktop/src/features/market/lib/marketProtocol.ts @@ -11,19 +11,19 @@ import { truncatePubkey } from "@/shared/lib/pubkey"; export const MARKET_PROTOCOL = "buzz-market/v0" as const; const EventId = z.string().regex(/^[0-9a-f]{64}$/); -const MarketId = z.string().min(1).max(120); +const ChannelId = z.string().uuid(); const ActorName = z.string().min(1).max(80); const PositiveInteger = z.number().int().positive(); -const NonnegativeInteger = z.number().int().nonnegative(); const BaseEnvelope = z.object({ protocol: z.literal(MARKET_PROTOCOL), - marketId: MarketId, + channelId: ChannelId, }); -const ListingEnvelope = BaseEnvelope.extend({ - type: z.literal("listing"), +const AnnouncementEnvelope = BaseEnvelope.extend({ + type: z.literal("announcement"), version: z.literal(1), + listingEventId: EventId, listing: z.object({ actorName: ActorName, direction: z.enum(["offer", "request"]), @@ -33,12 +33,18 @@ const ListingEnvelope = BaseEnvelope.extend({ quantity: z.union([PositiveInteger, z.literal("unlimited")]), priceSats: PositiveInteger.optional(), maxBudgetSats: PositiveInteger.optional(), - closesAt: NonnegativeInteger.optional(), + closesAt: PositiveInteger.optional(), deliveryMinutes: PositiveInteger.optional(), minimumDecrementSats: PositiveInteger.optional(), }), }); +const ContractEnvelope = BaseEnvelope.extend({ + type: z.literal("contract"), + version: z.literal(1), + listing: AnnouncementEnvelope.shape.listing, +}); + const ResponseEnvelope = BaseEnvelope.extend({ type: z.literal("response"), listingEventId: EventId, @@ -75,7 +81,8 @@ const SettlementEnvelope = BaseEnvelope.extend({ }); export const MarketEnvelopeSchema = z.discriminatedUnion("type", [ - ListingEnvelope, + AnnouncementEnvelope, + ContractEnvelope, ResponseEnvelope, AwardEnvelope, FulfillmentEnvelope, @@ -83,9 +90,14 @@ export const MarketEnvelopeSchema = z.discriminatedUnion("type", [ ]); export type MarketEnvelope = z.infer; -export type MarketListingEnvelope = z.infer; +export type MarketAnnouncementEnvelope = z.infer; +export type MarketContractEnvelope = z.infer; +export type MarketListing = MarketContractEnvelope["listing"]; export type MarketProjection = { + channelId: string; + contract: MarketContractEnvelope; + contractAuthorPubkey: string; listingEventId: string; scenario: MarketScenario; rejected: Array<{ eventId: string; reason: string }>; @@ -103,7 +115,7 @@ export function parseMarketEnvelope(content: string): MarketEnvelope | null { } function scenarioIdForListing( - listing: MarketListingEnvelope["listing"], + listing: MarketListing, settled: boolean, ): MarketScenarioId { if (settled) return "awarded"; @@ -125,7 +137,7 @@ function actorDetail(pubkey: string): string { return `agent · ${truncatePubkey(pubkey)}`; } -function listingPrice(listing: MarketListingEnvelope["listing"]): string { +function listingPrice(listing: MarketListing): string { if (listing.mechanism === "fixed") { return `${listing.priceSats ?? 0} sats per unit`; } @@ -137,20 +149,34 @@ function listingPrice(listing: MarketListingEnvelope["listing"]): string { : "Judged on published criteria"; } -function validateListing( - listing: MarketListingEnvelope["listing"], -): string | null { +function validateListing(listing: MarketListing): string | null { if (listing.mechanism === "fixed" && !listing.priceSats) { return "fixed listing requires priceSats"; } + if (listing.mechanism === "fixed" && listing.maxBudgetSats) { + return "fixed listing cannot declare maxBudgetSats"; + } + if (listing.mechanism !== "reverse-auction" && listing.minimumDecrementSats) { + return "minimumDecrementSats is only valid for reverse auctions"; + } if (listing.mechanism === "reverse-auction" && !listing.maxBudgetSats) { return "reverse auction requires maxBudgetSats"; } + if (listing.mechanism === "reverse-auction" && listing.priceSats) { + return "reverse auction cannot declare priceSats"; + } + if ( + listing.mechanism === "reverse-auction" && + listing.minimumDecrementSats && + listing.minimumDecrementSats > (listing.maxBudgetSats ?? 0) + ) { + return "minimum decrement exceeds maximum budget"; + } return null; } function responseIsValid( - listing: MarketListingEnvelope["listing"], + listing: MarketListing, response: Extract, bestAuctionBid: number | null, ): string | null { @@ -185,7 +211,9 @@ function responseIsValid( function envelopePhase(envelope: MarketEnvelope): number { switch (envelope.type) { - case "listing": + case "announcement": + return -1; + case "contract": return 0; case "response": return 1; @@ -198,16 +226,28 @@ function envelopePhase(envelope: MarketEnvelope): number { } } -export function projectMarketNotes( - notes: UserNote[], - marketId?: string, +function hasChannelTag(note: UserNote, channelId: string): boolean { + return note.tags.some( + (tag) => + tag[0] === "h" && tag[1]?.toLowerCase() === channelId.toLowerCase(), + ); +} + +function isTopLevelChannelEvent(note: UserNote): boolean { + return !note.tags.some((tag) => tag[0] === "e"); +} + +export function projectMarketChannel( + events: UserNote[], + channelId: string, ): MarketProjection | null { - const parsed = notes + const parsed = events .map((note) => ({ note, envelope: parseMarketEnvelope(note.content) })) .filter( (entry): entry is { note: UserNote; envelope: MarketEnvelope } => entry.envelope !== null && - (marketId === undefined || entry.envelope.marketId === marketId), + entry.envelope.channelId.toLowerCase() === channelId.toLowerCase() && + hasChannelTag(entry.note, channelId), ) .sort( (left, right) => @@ -217,18 +257,26 @@ export function projectMarketNotes( ); const listingEntry = parsed.find( (entry) => - entry.envelope.type === "listing" && + entry.envelope.type === "contract" && + isTopLevelChannelEvent(entry.note) && validateListing(entry.envelope.listing) === null, ); - if (listingEntry?.envelope.type !== "listing") return null; + if (listingEntry?.envelope.type !== "contract") return null; const listingEventId = listingEntry.note.id; const listing = listingEntry.envelope; const marketEvents = parsed.filter( (entry) => - entry.envelope.marketId === listing.marketId && + (entry.envelope.type === "contract" || + entry.envelope.type === "response" || + entry.envelope.type === "award" || + entry.envelope.type === "fulfillment" || + entry.envelope.type === "settlement") && entry.note.createdAt >= listingEntry.note.createdAt, - ); + ) as Array<{ + note: UserNote; + envelope: Exclude; + }>; const responses = new Map< string, { note: UserNote; envelope: Extract } @@ -245,24 +293,39 @@ export function projectMarketNotes( } >(); const settlements = new Map(); + const acceptedEventIds = new Set(); const rejected: MarketProjection["rejected"] = []; let awardedQuantity = 0; let bestAuctionBid: number | null = null; for (const entry of marketEvents) { const { envelope, note } = entry; - if (envelope.type === "listing") continue; + if (envelope.type === "contract") { + if (note.id !== listingEventId) { + rejected.push({ + eventId: note.id, + reason: "channel already has a canonical contract", + }); + } else { + acceptedEventIds.add(note.id); + } + continue; + } if (envelope.listingEventId !== listingEventId) { rejected.push({ eventId: note.id, - reason: "listingEventId does not target current listing", + reason: "listingEventId does not target channel contract", }); continue; } - if (listing.listing.closesAt && note.createdAt > listing.listing.closesAt) { + if ( + envelope.type === "response" && + listing.listing.closesAt && + note.createdAt > listing.listing.closesAt + ) { rejected.push({ eventId: note.id, - reason: "event arrived after listing close", + reason: "response arrived after listing close", }); continue; } @@ -274,6 +337,7 @@ export function projectMarketNotes( continue; } responses.set(note.id, { note, envelope }); + acceptedEventIds.add(note.id); if (listing.listing.mechanism === "reverse-auction") { bestAuctionBid = envelope.amountSats ?? bestAuctionBid; } @@ -306,6 +370,7 @@ export function projectMarketNotes( continue; } awards.set(envelope.responseEventId, { note, envelope }); + acceptedEventIds.add(note.id); awardedQuantity += envelope.quantity; continue; } @@ -333,6 +398,7 @@ export function projectMarketNotes( continue; } fulfillments.set(envelope.awardEventId, { note, envelope }); + acceptedEventIds.add(note.id); continue; } @@ -365,20 +431,21 @@ export function projectMarketNotes( continue; } settlements.set(envelope.awardEventId, note); + acceptedEventIds.add(note.id); } const accepted = marketEvents.filter((entry) => { - if (entry.envelope.type === "listing") - return entry.note.id === listingEventId; - return !rejected.some((item) => item.eventId === entry.note.id); + if (!acceptedEventIds.has(entry.note.id)) return false; + acceptedEventIds.delete(entry.note.id); + return true; }); const activities: MarketActivity[] = accepted .map(({ note, envelope }): MarketActivity => { - if (envelope.type === "listing") { + if (envelope.type === "contract") { return { actor: envelope.listing.actorName, at: formatAt(note.createdAt), - detail: `Contract v${envelope.version} is signed and open on Pulse.`, + detail: `Contract v${envelope.version} is signed in this Buzz channel and announced on Pulse.`, state: "accepted", title: "Market opened", }; @@ -445,6 +512,9 @@ export function projectMarketNotes( : "Open"; return { + channelId, + contract: listing, + contractAuthorPubkey: listingEntry.note.pubkey, listingEventId, rejected, scenario: { @@ -463,9 +533,9 @@ export function projectMarketNotes( ? "Reverse auction" : "Qualitative tender", status, - statusDetail: `Pulse state ${accepted.at(-1)?.note.id.slice(0, 8) ?? listingEventId.slice(0, 8)} · ${formatAt(accepted.at(-1)?.note.createdAt ?? listingEntry.note.createdAt)}`, + statusDetail: `Channel state ${accepted.at(-1)?.note.id.slice(0, 8) ?? listingEventId.slice(0, 8)} · ${formatAt(accepted.at(-1)?.note.createdAt ?? listingEntry.note.createdAt)}`, closeAt, - contractId: `${MARKET_PROTOCOL}:${listing.marketId}:v${listing.version}`, + contractId: `${MARKET_PROTOCOL}:${channelId}:v${listing.version}`, primaryAction: listing.listing.mechanism === "reverse-auction" ? `Bid below ${bestAuctionBid ?? listing.listing.maxBudgetSats ?? 0} sats` @@ -509,3 +579,71 @@ export function projectMarketNotes( }, }; } + +export function projectMarketAnnouncements( + notes: UserNote[], +): MarketAnnouncement[] { + const announcements = notes.flatMap((note) => { + const envelope = parseMarketEnvelope(note.content); + if (envelope?.type !== "announcement") return []; + const listingReason = validateListing(envelope.listing); + if (listingReason) return []; + return [{ note, envelope }]; + }); + const seenChannels = new Set(); + return announcements + .sort( + (left, right) => + left.note.createdAt - right.note.createdAt || + left.note.id.localeCompare(right.note.id), + ) + .flatMap(({ note, envelope }) => { + const channelKey = envelope.channelId.toLowerCase(); + if (seenChannels.has(channelKey)) return []; + seenChannels.add(channelKey); + return [ + { + announcementEventId: note.id, + channelId: envelope.channelId, + createdAt: note.createdAt, + listingEventId: envelope.listingEventId, + listing: envelope.listing, + publisherPubkey: note.pubkey, + }, + ]; + }) + .sort( + (left, right) => + right.createdAt - left.createdAt || + right.announcementEventId.localeCompare(left.announcementEventId), + ); +} + +export function marketAnnouncementMatchesProjection( + announcement: MarketAnnouncement, + projection: MarketProjection, +): boolean { + return ( + announcement.channelId.toLowerCase() === + projection.channelId.toLowerCase() && + announcement.listingEventId === projection.listingEventId && + announcement.publisherPubkey.toLowerCase() === + projection.contractAuthorPubkey.toLowerCase() && + listingsMatch(announcement.listing, projection.contract.listing) + ); +} + +function listingsMatch(left: MarketListing, right: MarketListing): boolean { + return AnnouncementEnvelope.shape.listing + .keyof() + .options.every((key) => left[key] === right[key]); +} + +export type MarketAnnouncement = { + announcementEventId: string; + channelId: string; + createdAt: number; + listingEventId: string; + listing: MarketAnnouncementEnvelope["listing"]; + publisherPubkey: string; +}; diff --git a/desktop/src/features/market/lib/useLiveMarketScenario.ts b/desktop/src/features/market/lib/useLiveMarketScenario.ts deleted file mode 100644 index 5cd2938d9d..0000000000 --- a/desktop/src/features/market/lib/useLiveMarketScenario.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { useQuery } from "@tanstack/react-query"; -import * as React from "react"; - -import { projectMarketNotes } from "@/features/market/lib/marketProtocol"; -import type { MarketScenario } from "@/features/market/lib/marketPrototypeData"; -import { getGlobalNotes } from "@/shared/api/social"; -import { useFocusedRefetchInterval } from "@/shared/lib/useDocumentVisible"; - -const MARKET_REFETCH_INTERVAL_MS = 5_000; - -export function useLiveMarketScenario( - fallback: MarketScenario, - marketId?: string, -): { - scenario: MarketScenario; - live: boolean; - isLoading: boolean; -} { - const refetchInterval = useFocusedRefetchInterval(MARKET_REFETCH_INTERVAL_MS); - const query = useQuery({ - queryKey: ["market-notes", marketId ?? "latest"], - queryFn: () => getGlobalNotes({ limit: 200 }), - refetchInterval, - refetchOnWindowFocus: true, - }); - const projection = React.useMemo( - () => projectMarketNotes(query.data?.notes ?? [], marketId), - [marketId, query.data?.notes], - ); - return { - scenario: projection?.scenario ?? fallback, - live: projection !== null, - isLoading: query.isLoading, - }; -} diff --git a/desktop/src/features/market/lib/useMarketChannels.ts b/desktop/src/features/market/lib/useMarketChannels.ts new file mode 100644 index 0000000000..5d726197f9 --- /dev/null +++ b/desktop/src/features/market/lib/useMarketChannels.ts @@ -0,0 +1,116 @@ +import { useQueries, useQuery } from "@tanstack/react-query"; +import * as React from "react"; + +import { + marketAnnouncementMatchesProjection, + projectMarketAnnouncements, + projectMarketChannel, + type MarketAnnouncement, + type MarketProjection, +} from "@/features/market/lib/marketProtocol"; +import { useChannelMessagesQuery } from "@/features/messages/hooks"; +import { getChannelWindowEvents } from "@/shared/api/channelWindow"; +import { getGlobalNotes } from "@/shared/api/social"; +import type { Channel } from "@/shared/api/types"; +import { useFocusedRefetchInterval } from "@/shared/lib/useDocumentVisible"; + +const MARKET_REFETCH_INTERVAL_MS = 5_000; + +export function useMarketAnnouncements(): { + announcements: MarketAnnouncement[]; + isLoading: boolean; +} { + const refetchInterval = useFocusedRefetchInterval(MARKET_REFETCH_INTERVAL_MS); + const query = useQuery({ + queryKey: ["market-announcements"], + queryFn: () => getGlobalNotes({ limit: 500 }), + refetchInterval, + refetchOnWindowFocus: true, + }); + const announcements = React.useMemo( + () => projectMarketAnnouncements(query.data?.notes ?? []), + [query.data?.notes], + ); + return { announcements, isLoading: query.isLoading }; +} + +export function useVerifiedMarketAnnouncements(): { + announcements: MarketAnnouncement[]; + isLoading: boolean; +} { + const pulse = useMarketAnnouncements(); + const channelQueries = useQueries({ + queries: pulse.announcements.map((announcement) => ({ + queryKey: ["market-channel-contract", announcement.channelId], + queryFn: () => getChannelWindowEvents(announcement.channelId, null, 100), + staleTime: 30_000, + })), + }); + const announcements = React.useMemo( + () => + pulse.announcements.filter((announcement, index) => { + const events = channelQueries[index]?.data; + if (!events) return false; + const projection = projectMarketChannel( + events.map((event) => ({ + id: event.id, + pubkey: event.pubkey, + createdAt: event.created_at, + content: event.content, + tags: event.tags, + })), + announcement.channelId, + ); + return ( + projection !== null && + marketAnnouncementMatchesProjection(announcement, projection) + ); + }), + [channelQueries, pulse.announcements], + ); + return { + announcements, + isLoading: + pulse.isLoading || channelQueries.some((query) => query.isPending), + }; +} + +export function useMarketAnnouncement( + channelId: string | null, +): MarketAnnouncement | null { + const { announcements } = useMarketAnnouncements(); + if (!channelId) return null; + return ( + announcements.find( + (announcement) => + announcement.channelId.toLowerCase() === channelId.toLowerCase(), + ) ?? null + ); +} + +export function useMarketChannelProjection( + channel: Channel, + announcement?: MarketAnnouncement | null, +): MarketProjection | null { + const messagesQuery = useChannelMessagesQuery(channel); + return React.useMemo(() => { + const projection = projectMarketChannel( + (messagesQuery.data ?? []).map((event) => ({ + id: event.id, + pubkey: event.pubkey, + createdAt: event.created_at, + content: event.content, + tags: event.tags, + })), + channel.id, + ); + if ( + !projection || + (announcement && + !marketAnnouncementMatchesProjection(announcement, projection)) + ) { + return null; + } + return projection; + }, [announcement, channel.id, messagesQuery.data]); +} diff --git a/desktop/src/features/market/ui/MarketChannelHome.tsx b/desktop/src/features/market/ui/MarketChannelHome.tsx new file mode 100644 index 0000000000..dc2dc3f2b1 --- /dev/null +++ b/desktop/src/features/market/ui/MarketChannelHome.tsx @@ -0,0 +1,26 @@ +import type { ComponentProps } from "react"; + +import { ChannelScreen } from "@/features/channels/ui/ChannelScreen"; +import { MarketChannelProvider } from "@/features/market/lib/MarketChannelContext"; +import { useMarketChannelProjection } from "@/features/market/lib/useMarketChannels"; +import type { MarketAnnouncement } from "@/features/market/lib/marketProtocol"; +import type { Channel } from "@/shared/api/types"; + +export function MarketChannelHome({ + activeChannel, + announcement, + ...screenProps +}: ComponentProps & { + activeChannel: Channel; + announcement: MarketAnnouncement; +}) { + const projection = useMarketChannelProjection(activeChannel, announcement); + if (!projection) + return ; + + return ( + + + + ); +} diff --git a/desktop/src/features/market/ui/MarketChannelIntro.tsx b/desktop/src/features/market/ui/MarketChannelIntro.tsx new file mode 100644 index 0000000000..00cde8e92e --- /dev/null +++ b/desktop/src/features/market/ui/MarketChannelIntro.tsx @@ -0,0 +1,11 @@ +import type * as React from "react"; + +import { useMarketChannel } from "@/features/market/lib/MarketChannelContext"; +import { MarketContractCard } from "@/features/market/ui/MarketContractCard"; + +export function MarketChannelIntro(): React.ReactNode { + const projection = useMarketChannel(); + return projection ? ( + + ) : undefined; +} diff --git a/desktop/src/features/market/ui/MarketContractCard.tsx b/desktop/src/features/market/ui/MarketContractCard.tsx new file mode 100644 index 0000000000..d3da5555f3 --- /dev/null +++ b/desktop/src/features/market/ui/MarketContractCard.tsx @@ -0,0 +1,75 @@ +import { Bot, PackageCheck, Radio, Store } from "lucide-react"; + +import type { MarketScenario } from "@/features/market/lib/marketPrototypeData"; +import { Badge } from "@/shared/ui/badge"; + +const COMMERCIAL_TERM_LABELS = new Set(["Price", "Reward", "Initial quantity"]); + +export function MarketContractCard({ scenario }: { scenario: MarketScenario }) { + const commercial = scenario.terms.find((term) => + COMMERCIAL_TERM_LABELS.has(term.label), + ); + const author = + scenario.terms.find( + (term) => term.label === "Seller" || term.label === "Requester", + )?.value ?? "Market agent"; + + return ( +
+
+
+ +
+
+
+ {scenario.eyebrow} + {scenario.status} +
+

+ {scenario.title} +

+

+ {scenario.summary} +

+
+ + + +
+
+
+
+ ); +} + +function ContractDatum({ + icon: Icon, + label, + value, +}: { + icon: typeof Store; + label: string; + value: string; +}) { + return ( +
+

+ {label} +

+

+ {value} +

+
+ ); +} diff --git a/desktop/src/features/market/ui/MarketScreen.tsx b/desktop/src/features/market/ui/MarketScreen.tsx index 102d61f834..7f97ba17b6 100644 --- a/desktop/src/features/market/ui/MarketScreen.tsx +++ b/desktop/src/features/market/ui/MarketScreen.tsx @@ -1,24 +1,21 @@ -import { - Bot, - MessageSquareOff, - PackageCheck, - Radio, - Store, - TriangleAlert, -} from "lucide-react"; +import { useQueryClient } from "@tanstack/react-query"; +import { ArrowRight, Plus, Radio, Store } from "lucide-react"; import * as React from "react"; -import { ChatHeader } from "@/features/chat/ui/ChatHeader"; -import { AgentWalletPanel } from "@/features/market/ui/AgentWalletPanel"; -import { useLiveMarketScenario } from "@/features/market/lib/useLiveMarketScenario"; +import { useAppNavigation } from "@/app/navigation/useAppNavigation"; import { - MARKET_SCENARIOS, - type MarketActivity, - type MarketScenario, - type MarketScenarioId, -} from "@/features/market/lib/marketPrototypeData"; + channelsQueryKey, + upsertCachedChannel, + useCreateChannelMutation, +} from "@/features/channels/hooks"; +import { useIdentityQuery } from "@/shared/api/hooks"; +import { useKnownAgentPubkeys } from "@/features/agents/useKnownAgentPubkeys"; +import { useVerifiedMarketAnnouncements } from "@/features/market/lib/useMarketChannels"; +import type { MarketAnnouncement } from "@/features/market/lib/marketProtocol"; +import { publishNote } from "@/shared/api/social"; +import { sendChannelMessage } from "@/shared/api/tauriMessages"; +import type { Channel } from "@/shared/api/types"; import { cn } from "@/shared/lib/cn"; -import { UserAvatar } from "@/shared/ui/UserAvatar"; import { Badge } from "@/shared/ui/badge"; import { Button } from "@/shared/ui/button"; import { @@ -29,434 +26,389 @@ import { DialogHeader, DialogTitle, } from "@/shared/ui/dialog"; -import { DrawerPanelIcon } from "@/shared/ui/DrawerPanelIcon"; import { Input } from "@/shared/ui/input"; import { useOptionalSidebar } from "@/shared/ui/sidebar"; import { Textarea } from "@/shared/ui/textarea"; -const REPRESENTING_AGENTS = [ - { name: "Forensic Finch", role: "Research & incident analysis" }, - { name: "Cartograph", role: "Repository mapping" }, - { name: "Sentinel", role: "Operations & safety" }, -] as const; +const MARKET_PROTOCOL = "buzz-market/v0"; -const COMMERCIAL_TERM_LABELS = new Set([ - "Price", - "Initial quantity", - "Quantity", - "Reserve", - "Minimum decrement", - "Reward", - "Award count", -]); - -const ACTIVITY_STYLE: Record< - MarketActivity["state"], - { - icon: React.ComponentType<{ className?: string }>; - label: string; - } -> = { - accepted: { - icon: Radio, - label: "Accepted by relay", - }, - discussion: { - icon: Bot, - label: "Agent message", - }, - rejected: { - icon: TriangleAlert, - label: "Rejected by relay", - }, - terminal: { - icon: PackageCheck, - label: "Signed transition", - }, +type Draft = { + direction: "offer" | "request"; + title: string; + summary: string; + quantity: string; + price: string; }; -export function MarketScreen({ - marketId, - scenarioId, -}: { - marketId?: string; - scenarioId: MarketScenarioId; -}) { - const fallbackScenario = MARKET_SCENARIOS[scenarioId]; - const { scenario, live, isLoading } = useLiveMarketScenario( - fallbackScenario, - marketId, - ); +const EMPTY_DRAFT: Draft = { + direction: "offer", + title: "", + summary: "", + quantity: "1", + price: "50", +}; + +export function MarketScreen() { const sidebar = useOptionalSidebar(); + const { goChannel } = useAppNavigation(); + const { announcements, isLoading } = useVerifiedMarketAnnouncements(); + const identityQuery = useIdentityQuery(); + const agentPubkeys = useKnownAgentPubkeys(); + const currentPubkey = identityQuery.data?.pubkey.toLowerCase() ?? null; + const canCreate = currentPubkey !== null && agentPubkeys.has(currentPubkey); const [createOpen, setCreateOpen] = React.useState(false); - const [walletOpen, setWalletOpen] = React.useState(true); - const isTerminal = scenario.status !== "Open"; return (
-
- setWalletOpen((open) => !open)} - size="icon" - title={walletOpen ? "Hide agent wallet" : "Show agent wallet"} - type="button" - variant="ghost" - > - +
+
+ +

Market

+
+ +
+
+
+
+

+ Agent offers and requests +

+

+ Pulse announces opportunities. Each card opens its own Buzz + channel, where agents negotiate and deliver. +

+
+ {isLoading && announcements.length === 0 ? ( +

+ Listening on Pulse… +

+ ) : announcements.length === 0 ? ( + setCreateOpen(true)} /> - - } - channelType="stream" - description={scenario.summary} - leadingContent={} - title={scenario.title} - /> - -
-
- setCreateOpen(true)} - scenario={scenario} - /> - -
-
-
-

Agent market channel

-

- Participants bid, negotiate, clarify, accept, and deliver in - public. -

-
- - {isLoading - ? "Checking Pulse…" - : live - ? "Live · Pulse" - : `${scenario.activity.length} messages`} - -
-
- {scenario.activity.map((activity) => ( - + {announcements.map((announcement) => ( + void goChannel(announcement.channelId)} /> ))}
-
+ )}
- - - -
-
- -
-

- Human participation is disabled in Market channels -

-

- You can observe and follow. Only agents can post or respond. -

-
- -
-
- - + void goChannel(channelId)} + onOpenChange={setCreateOpen} + canCreate={canCreate} + open={createOpen} + />
); } -function OfferCard({ +function EmptyMarket({ + canCreate, onCreate, - scenario, }: { + canCreate: boolean; onCreate: () => void; - scenario: MarketScenario; }) { - const author = - scenario.terms.find( - (term) => term.label === "Seller" || term.label === "Requester", - )?.value ?? "Market agent"; - const commercial = scenario.terms.find((term) => - COMMERCIAL_TERM_LABELS.has(term.label), - ); - const listingKind = scenario.eyebrow.startsWith("Offer") - ? "Agent offer" - : "Agent request"; - return ( -
-
-
-
- - Product image -
-
-
- - {listingKind} · {scenario.mode} - -

- {scenario.title} -

-

- {scenario.summary} -

-
-

- {commercial?.value ?? scenario.direction} -

-

- {scenario.direction} -

-
-
-
- -
-

{author}

-

- Created this {listingKind.toLowerCase()} -

-
-
- -
-
-
-
+
+ +

No market channels announced yet

+

+ Create an offer or request channel, then Pulse will make it + discoverable. +

+ +
); } -function CreateMarketDialog({ +function MarketListingCard({ + announcement, + onOpen, +}: { + announcement: MarketAnnouncement; + onOpen: () => void; +}) { + const { listing } = announcement; + const amount = listing.priceSats ?? listing.maxBudgetSats; + return ( + + ); +} + +function CreateMarketChannelDialog({ + canCreate, + currentPubkey, + onCreated, onOpenChange, open, - scenario, }: { + canCreate: boolean; + currentPubkey: string | null; + onCreated: (channelId: string) => void; onOpenChange: (open: boolean) => void; open: boolean; - scenario: MarketScenario; }) { - const [selectedAgent, setSelectedAgent] = React.useState( - REPRESENTING_AGENTS[0].name, - ); + const queryClient = useQueryClient(); + const createMutation = useCreateChannelMutation(); + const [draft, setDraft] = React.useState(EMPTY_DRAFT); + const [error, setError] = React.useState(null); + + React.useEffect(() => { + if (open) { + setDraft(EMPTY_DRAFT); + setError(null); + } + }, [open]); + + const handleCreate = async () => { + if (!canCreate || !currentPubkey) { + setError("Only a registered agent identity may create a market."); + return; + } + const quantity = Number.parseInt(draft.quantity, 10); + const price = Number.parseInt(draft.price, 10); + if ( + !draft.title.trim() || + !draft.summary.trim() || + quantity < 1 || + price < 1 + ) { + setError("Add a title, description, positive quantity, and reward."); + return; + } + setError(null); + try { + const channel = await createMutation.mutateAsync({ + name: marketChannelName(draft.title), + channelType: "stream", + visibility: "open", + description: `${draft.direction === "offer" ? "Offer" : "Request"}: ${draft.summary.trim()}`, + }); + const contract = { + protocol: MARKET_PROTOCOL, + type: "contract", + channelId: channel.id, + version: 1, + listing: { + actorName: "Representing agent", + direction: draft.direction, + mechanism: "fixed", + title: draft.title.trim(), + summary: draft.summary.trim(), + quantity, + priceSats: price, + }, + } as const; + const contractResult = await sendChannelMessage( + channel.id, + JSON.stringify(contract), + ); + queryClient.setQueryData( + ["market-channel-contract", channel.id], + [ + { + id: contractResult.eventId, + pubkey: currentPubkey, + created_at: contractResult.createdAt, + kind: 9, + tags: [ + ["h", channel.id], + ["p", currentPubkey], + ], + content: JSON.stringify(contract), + sig: "", + }, + ], + ); + const announcement = { + ...contract, + type: "announcement", + listingEventId: contractResult.eventId, + } as const; + const announcementResult = await publishNote( + JSON.stringify(announcement), + ); + if (!announcementResult.accepted) { + throw new Error( + announcementResult.message || + "Pulse rejected the market announcement.", + ); + } + queryClient.setQueryData(channelsQueryKey, (current) => + upsertCachedChannel(current, channel), + ); + await queryClient.invalidateQueries({ + queryKey: ["market-announcements"], + }); + onOpenChange(false); + onCreated(channel.id); + } catch (cause) { + setError( + cause instanceof Error + ? cause.message + : "Could not create market channel.", + ); + } + }; return ( - + - Create a market + Create an offer or request channel - Publish an offer or request through an agent representing you. + Buzz creates the channel first, stores the signed contract inside + it, then announces that channel on Pulse. - -
-
- Market type -
- - -
-
- -
- - - - - - + {direction === "offer" + ? "Offer something" + : "Request something"} + + ))}
- -