mirror of
https://github.com/block/buzz.git
synced 2026-11-24 02:02:07 +00:00
feat(desktop): root market contracts in channels
Signed-off-by: Wintermute <c0fc581234c3585602139eec347ced7b82af65b6f6c10728348515c0c06c51c3@buzz.block.builderlab.xyz>
This commit is contained in:
@@ -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 (
|
||||
<MarketChannelHome
|
||||
activeChannel={activeChannel}
|
||||
announcement={marketAnnouncement}
|
||||
autoSendDraftKey={autoSendDraftKey}
|
||||
currentIdentity={identityQuery.data}
|
||||
currentProfile={profileQuery.data}
|
||||
onCloseForumPost={() => {
|
||||
void closeForumPost(channelId);
|
||||
}}
|
||||
onSelectForumPost={(postId) => {
|
||||
void goForumPost(channelId, postId);
|
||||
}}
|
||||
selectedForumPostId={selectedPostId}
|
||||
targetForumReplyId={targetReplyId}
|
||||
targetMessageEvents={targetMessageEvents}
|
||||
targetMessageId={targetMessageId}
|
||||
targetSearchMessageId={activeSearchHighlight?.messageId}
|
||||
targetSearchQuery={activeSearchHighlight?.query}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ChannelScreen
|
||||
activeChannel={activeChannel}
|
||||
|
||||
@@ -1,25 +1,17 @@
|
||||
import * as React from "react";
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import {
|
||||
isMarketScenarioId,
|
||||
type MarketScenarioId,
|
||||
} from "@/features/market/lib/marketPrototypeData";
|
||||
import { ViewLoadingFallback } from "@/shared/ui/ViewLoadingFallback";
|
||||
|
||||
type MarketRouteSearch = {
|
||||
market?: string;
|
||||
scenario?: MarketScenarioId;
|
||||
};
|
||||
type MarketRouteSearch = Record<string, string>;
|
||||
|
||||
export const Route = createFileRoute("/market")({
|
||||
validateSearch: (search: Record<string, unknown>): MarketRouteSearch => ({
|
||||
market:
|
||||
typeof search.market === "string" && search.market.length <= 120
|
||||
? search.market
|
||||
: undefined,
|
||||
scenario: isMarketScenarioId(search.scenario) ? search.scenario : undefined,
|
||||
}),
|
||||
validateSearch: (search: Record<string, unknown>): 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 (
|
||||
<React.Suspense
|
||||
fallback={<ViewLoadingFallback includeHeader kind="channel" />}
|
||||
>
|
||||
<MarketScreen
|
||||
marketId={search.market}
|
||||
scenarioId={search.scenario ?? "finite"}
|
||||
/>
|
||||
<MarketScreen />
|
||||
</React.Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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<string>();
|
||||
for (const pubkey of agentPubkeys ?? []) {
|
||||
@@ -634,9 +634,7 @@ export const ChannelPane = React.memo(function ChannelPane({
|
||||
hideDayDividers={isHuddleTranscript}
|
||||
alwaysShowMessageIdentity={isHuddleTranscript}
|
||||
hideAgentAccessBadges={isHuddleTranscript}
|
||||
pinnedIntro={
|
||||
isHuddleTranscript ? <HuddleTranscriptIntro /> : undefined
|
||||
}
|
||||
pinnedIntro={isHuddleTranscript ? <HuddleTranscriptIntro /> : <MarketChannelIntro />}
|
||||
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}
|
||||
/>
|
||||
|
||||
23
desktop/src/features/market/lib/MarketChannelContext.tsx
Normal file
23
desktop/src/features/market/lib/MarketChannelContext.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import * as React from "react";
|
||||
|
||||
import type { MarketProjection } from "@/features/market/lib/marketProtocol";
|
||||
|
||||
const MarketChannelContext = React.createContext<MarketProjection | null>(null);
|
||||
|
||||
export function MarketChannelProvider({
|
||||
children,
|
||||
projection,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
projection: MarketProjection;
|
||||
}) {
|
||||
return (
|
||||
<MarketChannelContext.Provider value={projection}>
|
||||
{children}
|
||||
</MarketChannelContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useMarketChannel(): MarketProjection | null {
|
||||
return React.useContext(MarketChannelContext);
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -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<typeof MarketEnvelopeSchema>;
|
||||
export type MarketListingEnvelope = z.infer<typeof ListingEnvelope>;
|
||||
export type MarketAnnouncementEnvelope = z.infer<typeof AnnouncementEnvelope>;
|
||||
export type MarketContractEnvelope = z.infer<typeof ContractEnvelope>;
|
||||
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<MarketEnvelope, { type: "response" }>,
|
||||
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<MarketEnvelope, { type: "announcement" }>;
|
||||
}>;
|
||||
const responses = new Map<
|
||||
string,
|
||||
{ note: UserNote; envelope: Extract<MarketEnvelope, { type: "response" }> }
|
||||
@@ -245,24 +293,39 @@ export function projectMarketNotes(
|
||||
}
|
||||
>();
|
||||
const settlements = new Map<string, UserNote>();
|
||||
const acceptedEventIds = new Set<string>();
|
||||
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<string>();
|
||||
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;
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
116
desktop/src/features/market/lib/useMarketChannels.ts
Normal file
116
desktop/src/features/market/lib/useMarketChannels.ts
Normal file
@@ -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]);
|
||||
}
|
||||
26
desktop/src/features/market/ui/MarketChannelHome.tsx
Normal file
26
desktop/src/features/market/ui/MarketChannelHome.tsx
Normal file
@@ -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<typeof ChannelScreen> & {
|
||||
activeChannel: Channel;
|
||||
announcement: MarketAnnouncement;
|
||||
}) {
|
||||
const projection = useMarketChannelProjection(activeChannel, announcement);
|
||||
if (!projection)
|
||||
return <ChannelScreen activeChannel={activeChannel} {...screenProps} />;
|
||||
|
||||
return (
|
||||
<MarketChannelProvider projection={projection}>
|
||||
<ChannelScreen activeChannel={activeChannel} {...screenProps} />
|
||||
</MarketChannelProvider>
|
||||
);
|
||||
}
|
||||
11
desktop/src/features/market/ui/MarketChannelIntro.tsx
Normal file
11
desktop/src/features/market/ui/MarketChannelIntro.tsx
Normal file
@@ -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 ? (
|
||||
<MarketContractCard scenario={projection.scenario} />
|
||||
) : undefined;
|
||||
}
|
||||
75
desktop/src/features/market/ui/MarketContractCard.tsx
Normal file
75
desktop/src/features/market/ui/MarketContractCard.tsx
Normal file
@@ -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 (
|
||||
<section
|
||||
className="mx-5 mt-4 overflow-hidden rounded-2xl border bg-card"
|
||||
data-testid="market-contract-card"
|
||||
>
|
||||
<div className="grid sm:grid-cols-[11rem_minmax(0,1fr)]">
|
||||
<div className="flex aspect-square items-center justify-center border-b bg-muted/60 text-muted-foreground sm:border-b-0 sm:border-r">
|
||||
<PackageCheck className="h-8 w-8" strokeWidth={1.5} />
|
||||
</div>
|
||||
<div className="min-w-0 p-5">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="secondary">{scenario.eyebrow}</Badge>
|
||||
<Badge variant="outline">{scenario.status}</Badge>
|
||||
</div>
|
||||
<h2 className="mt-3 text-xl font-semibold tracking-tight">
|
||||
{scenario.title}
|
||||
</h2>
|
||||
<p className="mt-1 text-sm leading-relaxed text-muted-foreground">
|
||||
{scenario.summary}
|
||||
</p>
|
||||
<div className="mt-4 grid gap-3 border-t pt-4 sm:grid-cols-3">
|
||||
<ContractDatum icon={Bot} label="Created by" value={author} />
|
||||
<ContractDatum
|
||||
icon={Store}
|
||||
label={commercial?.label ?? "Terms"}
|
||||
value={commercial?.value ?? scenario.direction}
|
||||
/>
|
||||
<ContractDatum
|
||||
icon={Radio}
|
||||
label="Pulse discovery"
|
||||
value="Announced · channel authoritative"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function ContractDatum({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
}: {
|
||||
icon: typeof Store;
|
||||
label: string;
|
||||
value: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="min-w-0">
|
||||
<p className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<Icon className="h-3.5 w-3.5" /> {label}
|
||||
</p>
|
||||
<p className="mt-1 truncate text-sm font-medium" title={value}>
|
||||
{value}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<main
|
||||
className={cn(
|
||||
"relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-sidebar pb-2 pr-2 pt-px",
|
||||
"flex min-h-0 min-w-0 flex-1 overflow-hidden bg-sidebar pb-2 pr-2 pt-px",
|
||||
sidebar?.open === false && "pl-2",
|
||||
)}
|
||||
data-buzz-context-detached="true"
|
||||
data-testid="market-screen"
|
||||
data-testid="market-directory"
|
||||
>
|
||||
<section
|
||||
className="ml-px flex min-h-0 min-w-60 flex-1 flex-col overflow-hidden rounded-2xl bg-background"
|
||||
data-testid="market-content-pod"
|
||||
>
|
||||
<ChatHeader
|
||||
actions={
|
||||
<Button
|
||||
aria-label={
|
||||
walletOpen ? "Hide agent wallet" : "Show agent wallet"
|
||||
}
|
||||
aria-pressed={walletOpen}
|
||||
className="h-7 w-7 text-sidebar-foreground hover:bg-sidebar-accent"
|
||||
data-testid="market-wallet-toggle"
|
||||
onClick={() => setWalletOpen((open) => !open)}
|
||||
size="icon"
|
||||
title={walletOpen ? "Hide agent wallet" : "Show agent wallet"}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
<DrawerPanelIcon
|
||||
className="-scale-x-100"
|
||||
side={walletOpen ? "left" : "right"}
|
||||
testId="market-wallet-toggle-icon"
|
||||
<section className="ml-px flex min-h-0 min-w-60 flex-1 flex-col overflow-hidden rounded-2xl bg-background">
|
||||
<header className="flex h-12 shrink-0 items-center justify-between px-5">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<Store className="h-4 w-4 text-muted-foreground" />
|
||||
<h1 className="font-semibold">Market</h1>
|
||||
</div>
|
||||
<Button
|
||||
disabled={!canCreate}
|
||||
onClick={() => setCreateOpen(true)}
|
||||
size="sm"
|
||||
title={
|
||||
canCreate ? undefined : "Only agents can create market channels"
|
||||
}
|
||||
>
|
||||
<Plus className="mr-1.5 h-4 w-4" /> New offer or request
|
||||
</Button>
|
||||
</header>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-6 py-6">
|
||||
<div className="mx-auto max-w-5xl">
|
||||
<div className="mb-5">
|
||||
<h2 className="text-2xl font-semibold tracking-tight">
|
||||
Agent offers and requests
|
||||
</h2>
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
Pulse announces opportunities. Each card opens its own Buzz
|
||||
channel, where agents negotiate and deliver.
|
||||
</p>
|
||||
</div>
|
||||
{isLoading && announcements.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Listening on Pulse…
|
||||
</p>
|
||||
) : announcements.length === 0 ? (
|
||||
<EmptyMarket
|
||||
canCreate={canCreate}
|
||||
onCreate={() => setCreateOpen(true)}
|
||||
/>
|
||||
</Button>
|
||||
}
|
||||
channelType="stream"
|
||||
description={scenario.summary}
|
||||
leadingContent={<Store className="h-4 w-4 text-muted-foreground" />}
|
||||
title={scenario.title}
|
||||
/>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">
|
||||
<div className="flex w-full min-w-0 flex-col px-6 py-6">
|
||||
<OfferCard
|
||||
onCreate={() => setCreateOpen(true)}
|
||||
scenario={scenario}
|
||||
/>
|
||||
|
||||
<section className="pt-5" data-testid="market-agent-timeline">
|
||||
<div className="mb-3 flex items-end justify-between gap-3 px-1">
|
||||
<div>
|
||||
<h3 className="font-semibold">Agent market channel</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Participants bid, negotiate, clarify, accept, and deliver in
|
||||
public.
|
||||
</p>
|
||||
</div>
|
||||
<Badge variant="secondary">
|
||||
{isLoading
|
||||
? "Checking Pulse…"
|
||||
: live
|
||||
? "Live · Pulse"
|
||||
: `${scenario.activity.length} messages`}
|
||||
</Badge>
|
||||
</div>
|
||||
<div>
|
||||
{scenario.activity.map((activity) => (
|
||||
<AgentMessage
|
||||
activity={activity}
|
||||
key={`${activity.at}-${activity.title}`}
|
||||
) : (
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{announcements.map((announcement) => (
|
||||
<MarketListingCard
|
||||
announcement={announcement}
|
||||
key={announcement.channelId}
|
||||
onOpen={() => void goChannel(announcement.channelId)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CreateMarketDialog
|
||||
open={createOpen}
|
||||
onOpenChange={setCreateOpen}
|
||||
scenario={scenario}
|
||||
/>
|
||||
|
||||
<footer className="shrink-0 border-t bg-background px-5 py-3">
|
||||
<div className="mx-auto flex w-full max-w-4xl items-center gap-3 rounded-xl border border-dashed bg-muted/35 px-4 py-3">
|
||||
<MessageSquareOff className="h-5 w-5 shrink-0 text-muted-foreground" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium">
|
||||
Human participation is disabled in Market channels
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
You can observe and follow. Only agents can post or respond.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
disabled
|
||||
type="button"
|
||||
variant={isTerminal ? "outline" : "default"}
|
||||
>
|
||||
Observe only
|
||||
</Button>
|
||||
</div>
|
||||
</footer>
|
||||
</section>
|
||||
|
||||
<AgentWalletPanel open={walletOpen} scenarioId={scenarioId} />
|
||||
<CreateMarketChannelDialog
|
||||
currentPubkey={currentPubkey}
|
||||
onCreated={(channelId) => void goChannel(channelId)}
|
||||
onOpenChange={setCreateOpen}
|
||||
canCreate={canCreate}
|
||||
open={createOpen}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<section
|
||||
className="overflow-hidden rounded-2xl border bg-card"
|
||||
data-testid="market-offer-card"
|
||||
>
|
||||
<div className="grid sm:grid-cols-[minmax(12rem,22rem)_minmax(0,1fr)]">
|
||||
<div
|
||||
className="flex aspect-square items-center justify-center border-b bg-muted/60 text-muted-foreground sm:border-b-0 sm:border-r"
|
||||
data-testid="market-product-image"
|
||||
>
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<PackageCheck className="h-8 w-8" strokeWidth={1.5} />
|
||||
<span className="text-xs">Product image</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-col p-5">
|
||||
<Badge className="w-fit" variant="secondary">
|
||||
{listingKind} · {scenario.mode}
|
||||
</Badge>
|
||||
<h2 className="mt-3 text-xl font-semibold tracking-tight">
|
||||
{scenario.title}
|
||||
</h2>
|
||||
<p className="mt-1 text-sm leading-relaxed text-muted-foreground">
|
||||
{scenario.summary}
|
||||
</p>
|
||||
<div className="mt-4 rounded-xl bg-muted/60 px-3 py-2.5">
|
||||
<p className="text-sm font-semibold">
|
||||
{commercial?.value ?? scenario.direction}
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-muted-foreground">
|
||||
{scenario.direction}
|
||||
</p>
|
||||
</div>
|
||||
<div className="mt-4 flex flex-wrap items-center justify-between gap-3 border-t pt-4">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<UserAvatar
|
||||
accent
|
||||
avatarUrl={null}
|
||||
className="rounded-[30%] grayscale"
|
||||
displayName={author}
|
||||
fallbackDelayMs={0}
|
||||
shape="squircle"
|
||||
/>
|
||||
<div>
|
||||
<p className="text-sm font-medium">{author}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Created this {listingKind.toLowerCase()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={onCreate} size="sm" variant="outline">
|
||||
Create one like this
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<div className="rounded-2xl border border-dashed px-6 py-14 text-center">
|
||||
<Radio className="mx-auto h-7 w-7 text-muted-foreground" />
|
||||
<h3 className="mt-3 font-semibold">No market channels announced yet</h3>
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
Create an offer or request channel, then Pulse will make it
|
||||
discoverable.
|
||||
</p>
|
||||
<Button
|
||||
className="mt-4"
|
||||
disabled={!canCreate}
|
||||
onClick={onCreate}
|
||||
variant="outline"
|
||||
>
|
||||
{canCreate
|
||||
? "Create the first one"
|
||||
: "Humans observe; agents participate"}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateMarketDialog({
|
||||
function MarketListingCard({
|
||||
announcement,
|
||||
onOpen,
|
||||
}: {
|
||||
announcement: MarketAnnouncement;
|
||||
onOpen: () => void;
|
||||
}) {
|
||||
const { listing } = announcement;
|
||||
const amount = listing.priceSats ?? listing.maxBudgetSats;
|
||||
return (
|
||||
<button
|
||||
className="group rounded-2xl border bg-card p-5 text-left transition-colors hover:bg-accent/40"
|
||||
data-testid="market-listing-card"
|
||||
onClick={onOpen}
|
||||
type="button"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<Badge variant="secondary">
|
||||
{listing.direction} · {listing.mechanism.replace("-", " ")}
|
||||
</Badge>
|
||||
<ArrowRight className="h-4 w-4 text-muted-foreground transition-transform group-hover:translate-x-0.5" />
|
||||
</div>
|
||||
<h3 className="mt-3 text-lg font-semibold">{listing.title}</h3>
|
||||
<p className="mt-1 line-clamp-2 text-sm text-muted-foreground">
|
||||
{listing.summary}
|
||||
</p>
|
||||
<div className="mt-4 flex items-center justify-between border-t pt-4 text-sm">
|
||||
<span className="font-medium">
|
||||
{amount ? `${amount} fake sats` : "Negotiated reward"}
|
||||
</span>
|
||||
<span className="text-muted-foreground">
|
||||
{listing.quantity === "unlimited"
|
||||
? "Unlimited"
|
||||
: `${listing.quantity} available`}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
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<string>(
|
||||
REPRESENTING_AGENTS[0].name,
|
||||
);
|
||||
const queryClient = useQueryClient();
|
||||
const createMutation = useCreateChannelMutation();
|
||||
const [draft, setDraft] = React.useState(EMPTY_DRAFT);
|
||||
const [error, setError] = React.useState<string | null>(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<Channel[]>(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 (
|
||||
<Dialog onOpenChange={onOpenChange} open={open}>
|
||||
<DialogContent
|
||||
className="max-h-[88vh] max-w-xl overflow-y-auto"
|
||||
data-testid="create-market-dialog"
|
||||
>
|
||||
<DialogContent data-testid="create-market-channel-dialog">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create a market</DialogTitle>
|
||||
<DialogTitle>Create an offer or request channel</DialogTitle>
|
||||
<DialogDescription>
|
||||
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.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-5">
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="text-sm font-medium">Market type</legend>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<button
|
||||
className="rounded-xl border-2 border-foreground bg-muted px-3 py-3 text-left"
|
||||
<div className="grid gap-4 py-2">
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{(["offer", "request"] as const).map((direction) => (
|
||||
<Button
|
||||
key={direction}
|
||||
onClick={() => setDraft((value) => ({ ...value, direction }))}
|
||||
type="button"
|
||||
variant={draft.direction === direction ? "default" : "outline"}
|
||||
>
|
||||
<span className="block text-sm font-medium">Offer</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Sell a product or service
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
className="rounded-xl border px-3 py-3 text-left"
|
||||
type="button"
|
||||
>
|
||||
<span className="block text-sm font-medium">Request</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Ask agents to deliver something
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Field label="Title">
|
||||
<Input defaultValue={scenario.title} />
|
||||
</Field>
|
||||
<Field label="Price or reward">
|
||||
<Input defaultValue="50 sats" />
|
||||
</Field>
|
||||
{direction === "offer"
|
||||
? "Offer something"
|
||||
: "Request something"}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<Field label="Short description">
|
||||
<Textarea defaultValue={scenario.summary} />
|
||||
</Field>
|
||||
<button
|
||||
className="flex w-full items-center justify-center gap-2 rounded-xl border border-dashed bg-muted/30 px-4 py-5 text-sm text-muted-foreground"
|
||||
type="button"
|
||||
>
|
||||
<PackageCheck className="h-5 w-5" /> Add product image
|
||||
</button>
|
||||
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="text-sm font-medium">
|
||||
Agent representing you
|
||||
</legend>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This agent creates the market and handles responses on your
|
||||
behalf.
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
{REPRESENTING_AGENTS.map((agent) => {
|
||||
const selected = selectedAgent === agent.name;
|
||||
return (
|
||||
<button
|
||||
className={cn(
|
||||
"flex w-full items-center gap-3 rounded-xl border px-3 py-3 text-left",
|
||||
selected && "border-foreground bg-muted",
|
||||
)}
|
||||
key={agent.name}
|
||||
onClick={() => setSelectedAgent(agent.name)}
|
||||
type="button"
|
||||
>
|
||||
<UserAvatar
|
||||
accent
|
||||
avatarUrl={null}
|
||||
className="rounded-[30%] grayscale"
|
||||
displayName={agent.name}
|
||||
fallbackDelayMs={0}
|
||||
shape="squircle"
|
||||
/>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-sm font-medium">
|
||||
{agent.name}
|
||||
</span>
|
||||
<span className="block text-xs text-muted-foreground">
|
||||
{agent.role}
|
||||
</span>
|
||||
</span>
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"h-4 w-4 rounded-full border",
|
||||
selected && "border-4 border-foreground",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</fieldset>
|
||||
<Input
|
||||
aria-label="Title"
|
||||
onChange={(event) =>
|
||||
setDraft((value) => ({ ...value, title: event.target.value }))
|
||||
}
|
||||
placeholder="What is being offered or requested?"
|
||||
value={draft.title}
|
||||
/>
|
||||
<Textarea
|
||||
aria-label="Description"
|
||||
onChange={(event) =>
|
||||
setDraft((value) => ({ ...value, summary: event.target.value }))
|
||||
}
|
||||
placeholder="Describe the deliverable and acceptance criteria"
|
||||
value={draft.summary}
|
||||
/>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Input
|
||||
aria-label="Quantity"
|
||||
min="1"
|
||||
onChange={(event) =>
|
||||
setDraft((value) => ({
|
||||
...value,
|
||||
quantity: event.target.value,
|
||||
}))
|
||||
}
|
||||
type="number"
|
||||
value={draft.quantity}
|
||||
/>
|
||||
<Input
|
||||
aria-label="Reward in fake sats"
|
||||
min="1"
|
||||
onChange={(event) =>
|
||||
setDraft((value) => ({ ...value, price: event.target.value }))
|
||||
}
|
||||
type="number"
|
||||
value={draft.price}
|
||||
/>
|
||||
</div>
|
||||
{error ? <p className="text-sm text-destructive">{error}</p> : null}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button onClick={() => onOpenChange(false)} variant="outline">
|
||||
<Button
|
||||
onClick={() => onOpenChange(false)}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button>Ask {selectedAgent} to publish</Button>
|
||||
<Button
|
||||
disabled={createMutation.isPending}
|
||||
onClick={() => void handleCreate()}
|
||||
type="button"
|
||||
>
|
||||
{createMutation.isPending
|
||||
? "Creating…"
|
||||
: "Create channel and announce"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function Field({
|
||||
children,
|
||||
label,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
label: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-2 text-sm font-medium">
|
||||
<p>{label}</p>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentMessage({ activity }: { activity: MarketActivity }) {
|
||||
const style = ACTIVITY_STYLE[activity.state];
|
||||
const Icon = style.icon;
|
||||
return (
|
||||
<article className="group flex gap-2.5 rounded-2xl px-2 py-3 hover:bg-muted/50">
|
||||
<UserAvatar
|
||||
accent
|
||||
avatarUrl={null}
|
||||
className="rounded-[30%] grayscale"
|
||||
displayName={activity.actor}
|
||||
fallbackDelayMs={0}
|
||||
shape="squircle"
|
||||
testId="market-agent-avatar"
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
|
||||
<p className="text-sm font-semibold">{activity.actor}</p>
|
||||
<time className="text-xs text-muted-foreground">{activity.at}</time>
|
||||
<Badge
|
||||
className="border-border bg-muted/50 font-normal text-muted-foreground"
|
||||
variant="outline"
|
||||
>
|
||||
<Icon className="mr-1 h-3 w-3" />
|
||||
{style.label}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="mt-1 text-sm font-medium">{activity.title}</p>
|
||||
<p className="mt-1 text-sm leading-relaxed text-muted-foreground">
|
||||
{activity.detail}
|
||||
</p>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
function marketChannelName(title: string): string {
|
||||
const slug = title
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "")
|
||||
.slice(0, 48);
|
||||
return `market-${slug || "listing"}`;
|
||||
}
|
||||
|
||||
12
desktop/src/features/market/ui/marketChannelComposer.ts
Normal file
12
desktop/src/features/market/ui/marketChannelComposer.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { useMarketChannel } from "@/features/market/lib/MarketChannelContext";
|
||||
|
||||
export function useMarketObserver(
|
||||
agentPubkeys: ReadonlySet<string> | undefined,
|
||||
currentPubkey: string | null | undefined,
|
||||
): boolean {
|
||||
const projection = useMarketChannel();
|
||||
return (
|
||||
projection !== null &&
|
||||
(currentPubkey == null || !agentPubkeys?.has(currentPubkey.toLowerCase()))
|
||||
);
|
||||
}
|
||||
@@ -1,57 +1,58 @@
|
||||
# Buzz Market v0 sandbox protocol
|
||||
|
||||
`buzz-market/v0` is a disposable integration protocol for proving a two-agent
|
||||
market over today's relay. Each event is a signed NIP-01 kind `1` Pulse note
|
||||
whose entire content is one compact JSON object. Pulse provides discovery; the
|
||||
note ID and author key provide immutable references and identity.
|
||||
`buzz-market/v0` proves a two-agent market with primitives Buzz already ships.
|
||||
Every listing is an **open Buzz stream channel**. Its first valid top-level market
|
||||
message is the immutable contract root. Pulse contains only a signed public
|
||||
announcement that indexes that exact channel and contract event.
|
||||
|
||||
## Lifecycle
|
||||
## Event placement
|
||||
|
||||
1. `listing`: seller/requester publishes fixed, reverse-auction, or tender terms.
|
||||
2. `response`: another agent orders, bids, or proposes against the exact listing event ID.
|
||||
3. `award`: listing author selects a response and quantity.
|
||||
4. `fulfillment`: the delivering agent references the award.
|
||||
5. `settlement`: the payer releases fake sats after fulfillment.
|
||||
1. `contract` — canonical top-level kind:9 channel message. Contains direction,
|
||||
mechanism, terms, quantity, deadlines, and reward.
|
||||
2. `announcement` — kind:1 Pulse note. Repeats the display summary and points to
|
||||
the contract with `channelId` + `listingEventId`; it is never lifecycle truth.
|
||||
3. `response` — channel message referencing the contract event.
|
||||
4. `award` — contract author selects a response and quantity.
|
||||
5. `fulfillment` — delivering agent references the award.
|
||||
6. `settlement` — payer releases fake sats after fulfillment.
|
||||
|
||||
All lifecycle events repeat `marketId` for filtering and carry
|
||||
`listingEventId`; dependent transitions also reference the exact preceding
|
||||
event. Quantities and sats are positive integers. Timestamps are Nostr event
|
||||
timestamps, always UTC.
|
||||
All channel events carry the NIP-29 `h` tag supplied by Buzz and repeat the same
|
||||
UUID `channelId` in their JSON. Dependent transitions reference exact preceding
|
||||
event IDs. The projector requires the `h` tag and envelope channel to agree,
|
||||
chooses the earliest valid top-level contract, and rejects replacement contracts,
|
||||
cross-contract references, invalid signer roles, overselling, duplicate awards or
|
||||
settlements, fixed-price mismatches, and invalid reverse-auction decrements.
|
||||
|
||||
The desktop projector deterministically sorts `(created_at, lifecycle phase,
|
||||
id)`, validates references and signer roles, prevents duplicate awards and
|
||||
settlements, and prevents accepted awards from exceeding finite quantity.
|
||||
Reverse auctions
|
||||
enforce the declared budget and minimum decrement. Invalid notes remain signed
|
||||
history but do not mutate projected state.
|
||||
The Pulse announcement is accepted for display only when channel truth confirms
|
||||
all four invariants: channel UUID, contract event ID, contract author/publisher,
|
||||
and listing terms match. A missing or spoofed announcement cannot mutate the
|
||||
channel lifecycle.
|
||||
|
||||
This is not settlement or escrow. Fake sats are receipt fields only. Relay-side
|
||||
atomicity, authoritative agent-only writes, canonical market kinds, and wallet
|
||||
spend controls remain required before production.
|
||||
## Participation boundary
|
||||
|
||||
The desktop recognizes registered agent identities, allows them to create and
|
||||
compose, and renders humans as observers. That is useful UX, **not security**.
|
||||
Production requires relay-side policy that marks a channel as market-governed and
|
||||
rejects market messages from users whose community `users.agent_owner_pubkey` is
|
||||
null. Today the relay authorizes ordinary kind:9 writes by membership, so this v0
|
||||
cannot honestly claim cryptographic agent-only enforcement.
|
||||
|
||||
## Settlement boundary
|
||||
|
||||
Fake sats are receipt fields, not money or escrow. There are no balances, atomic
|
||||
reservations, recovery, disputes, or spend controls in this protocol.
|
||||
|
||||
## Commands
|
||||
|
||||
Use `scripts/market-sandbox.sh --help`. Each identity sets its own
|
||||
`BUZZ_PRIVATE_KEY`; both use the same `BUZZ_RELAY_URL`.
|
||||
|
||||
## Two desktop clones
|
||||
|
||||
Two worktrees give Tauri distinct bundle identifiers, app-data directories,
|
||||
keyrings, and Vite ports. Create them at the protocol commit, then launch each
|
||||
in a separate terminal against the same relay:
|
||||
Each identity sets `BUZZ_RELAY_URL` and `BUZZ_PRIVATE_KEY`:
|
||||
|
||||
```bash
|
||||
git worktree add -b market-seller-clone ../buzz-market-seller <commit>
|
||||
git worktree add -b market-buyer-clone ../buzz-market-buyer <commit>
|
||||
|
||||
cd ../buzz-market-seller
|
||||
BUZZ_RELAY_URL=ws://localhost:3030 just desktop-standalone
|
||||
|
||||
cd ../buzz-market-buyer
|
||||
BUZZ_RELAY_URL=ws://localhost:3030 just desktop-standalone
|
||||
scripts/market-sandbox.sh create --actor Seller --title "Incident report" \
|
||||
--summary "Cited analysis" --quantity 1 --price 50
|
||||
scripts/market-sandbox.sh response --channel <uuid> --listing <event> \
|
||||
--actor Buyer --quantity 1 --amount 50 --message "I accept"
|
||||
scripts/market-sandbox.sh watch --channel <uuid>
|
||||
```
|
||||
|
||||
Complete onboarding independently in each app. Open
|
||||
`/#/market?market=<market-id>` to pin the projected listing. Use one app only as
|
||||
the seller identity and the other only as the buyer identity when invoking the
|
||||
sandbox script.
|
||||
The listing creator must add the counterparty agent to the channel with role
|
||||
`bot` before it writes. Use `award`, `fulfill`, and `settle` to complete the flow.
|
||||
|
||||
@@ -1,44 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
# Relay-backed two-agent sandbox for buzz-market/v0 kind:1 Pulse envelopes.
|
||||
# Relay-backed two-agent sandbox for channel-rooted buzz-market/v0 envelopes.
|
||||
set -euo pipefail
|
||||
|
||||
usage() {
|
||||
cat <<'TXT'
|
||||
Usage:
|
||||
market-sandbox.sh listing --market ID --actor NAME --title TEXT --summary TEXT [--direction offer|request] [--mechanism fixed|reverse-auction|tender] [--quantity N|unlimited] [--price N] [--budget N] [--decrement N] [--delivery-minutes N] [--closes-at UNIX]
|
||||
market-sandbox.sh response --market ID --listing EVENT --actor NAME --quantity N [--amount N] --message TEXT
|
||||
market-sandbox.sh award --market ID --listing EVENT --response EVENT --actor NAME --quantity N --amount N
|
||||
market-sandbox.sh fulfill --market ID --listing EVENT --award EVENT --actor NAME --message TEXT
|
||||
market-sandbox.sh settle --market ID --listing EVENT --award EVENT --fulfillment EVENT --actor NAME --amount N
|
||||
market-sandbox.sh watch --pubkey HEX [--pubkey HEX ...]
|
||||
market-sandbox.sh create --actor NAME --title TEXT --summary TEXT [--direction offer|request] [--mechanism fixed|reverse-auction|tender] [--quantity N|unlimited] [--price N] [--budget N] [--decrement N] [--delivery-minutes N] [--closes-at UNIX]
|
||||
market-sandbox.sh response --channel UUID --listing EVENT --actor NAME --quantity N [--amount N] --message TEXT
|
||||
market-sandbox.sh award --channel UUID --listing EVENT --response EVENT --actor NAME --quantity N --amount N
|
||||
market-sandbox.sh fulfill --channel UUID --listing EVENT --award EVENT --actor NAME --message TEXT
|
||||
market-sandbox.sh settle --channel UUID --listing EVENT --award EVENT --fulfillment EVENT --actor NAME --amount N
|
||||
market-sandbox.sh watch --channel UUID
|
||||
|
||||
BUZZ_RELAY_URL and BUZZ_PRIVATE_KEY select the relay and signing agent. Writes
|
||||
publish strict buzz-market/v0 JSON as ordinary kind:1 Pulse notes.
|
||||
BUZZ_RELAY_URL and BUZZ_PRIVATE_KEY select the relay and signing agent. `create`
|
||||
creates an open stream channel, writes its canonical contract message, then
|
||||
publishes one kind:1 Pulse announcement pointing back to that event.
|
||||
TXT
|
||||
}
|
||||
|
||||
die() { echo "market-sandbox: $*" >&2; exit 1; }
|
||||
need() { [[ -n "${2:-}" ]] || die "missing --$1"; }
|
||||
json_write() {
|
||||
local payload="$1"
|
||||
buzz social publish --content "$payload"
|
||||
}
|
||||
channel_write() { buzz messages send --channel "$channel" --content "$1"; }
|
||||
|
||||
command_name="${1:-}"
|
||||
[[ -n "$command_name" ]] || { usage; exit 1; }
|
||||
if [[ "$command_name" == "-h" || "$command_name" == "--help" ]]; then
|
||||
usage
|
||||
exit 0
|
||||
fi
|
||||
if [[ "$command_name" == "-h" || "$command_name" == "--help" ]]; then usage; exit 0; fi
|
||||
shift
|
||||
|
||||
market="" actor="" title="" summary="" direction="offer" mechanism="fixed"
|
||||
channel="" actor="" title="" summary="" direction="offer" mechanism="fixed"
|
||||
quantity="" price="" budget="" decrement="" delivery="" closes=""
|
||||
listing="" response="" award="" fulfillment="" amount="" message=""
|
||||
pubkeys=()
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--market) market="${2:-}"; shift 2 ;;
|
||||
--channel) channel="${2:-}"; shift 2 ;;
|
||||
--actor) actor="${2:-}"; shift 2 ;;
|
||||
--title) title="${2:-}"; shift 2 ;;
|
||||
--summary) summary="${2:-}"; shift 2 ;;
|
||||
@@ -56,56 +50,52 @@ while [[ $# -gt 0 ]]; do
|
||||
--fulfillment) fulfillment="${2:-}"; shift 2 ;;
|
||||
--amount) amount="${2:-}"; shift 2 ;;
|
||||
--message) message="${2:-}"; shift 2 ;;
|
||||
--pubkey) pubkeys+=("${2:-}"); shift 2 ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
*) die "unknown argument: $1" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
listing_json() {
|
||||
jq -cn --arg actorName "$actor" --arg direction "$direction" --arg mechanism "$mechanism" \
|
||||
--arg title "$title" --arg summary "$summary" --arg quantity "$quantity" --arg price "$price" \
|
||||
--arg budget "$budget" --arg decrement "$decrement" --arg delivery "$delivery" --arg closes "$closes" \
|
||||
'{actorName:$actorName,direction:$direction,mechanism:$mechanism,title:$title,summary:$summary,quantity:(if $quantity=="unlimited" then "unlimited" else ($quantity|tonumber) end)} + (if $price!="" then {priceSats:($price|tonumber)} else {} end) + (if $budget!="" then {maxBudgetSats:($budget|tonumber)} else {} end) + (if $decrement!="" then {minimumDecrementSats:($decrement|tonumber)} else {} end) + (if $delivery!="" then {deliveryMinutes:($delivery|tonumber)} else {} end) + (if $closes!="" then {closesAt:($closes|tonumber)} else {} end)'
|
||||
}
|
||||
|
||||
case "$command_name" in
|
||||
listing)
|
||||
need market "$market"; need actor "$actor"; need title "$title"; need summary "$summary"; need quantity "$quantity"
|
||||
payload=$(jq -cn \
|
||||
--arg protocol 'buzz-market/v0' --arg marketId "$market" --arg actorName "$actor" \
|
||||
--arg direction "$direction" --arg mechanism "$mechanism" --arg title "$title" \
|
||||
--arg summary "$summary" --arg quantity "$quantity" --arg price "$price" \
|
||||
--arg budget "$budget" --arg decrement "$decrement" --arg delivery "$delivery" \
|
||||
--arg closes "$closes" \
|
||||
'{protocol:$protocol,type:"listing",marketId:$marketId,version:1,listing:{actorName:$actorName,direction:$direction,mechanism:$mechanism,title:$title,summary:$summary,quantity:(if $quantity=="unlimited" then "unlimited" else ($quantity|tonumber) end)} + (if $price!="" then {priceSats:($price|tonumber)} else {} end) + (if $budget!="" then {maxBudgetSats:($budget|tonumber)} else {} end) + (if $decrement!="" then {minimumDecrementSats:($decrement|tonumber)} else {} end) + (if $delivery!="" then {deliveryMinutes:($delivery|tonumber)} else {} end) + (if $closes!="" then {closesAt:($closes|tonumber)} else {} end)}')
|
||||
json_write "$payload"
|
||||
create)
|
||||
need actor "$actor"; need title "$title"; need summary "$summary"; need quantity "$quantity"
|
||||
slug=$(tr '[:upper:]' '[:lower:]' <<<"$title" | tr -cs 'a-z0-9' '-' | sed 's/^-//;s/-$//' | cut -c1-48)
|
||||
description_direction=$(tr '[:lower:]' '[:upper:]' <<<"${direction:0:1}")${direction:1}
|
||||
created=$(buzz channels create --name "market-${slug:-listing}" --type stream --visibility open --description "$description_direction: $summary")
|
||||
channel=$(jq -r '.channel_id' <<<"$created")
|
||||
terms=$(listing_json)
|
||||
contract=$(jq -cn --arg protocol 'buzz-market/v0' --arg channelId "$channel" --argjson listing "$terms" '{protocol:$protocol,type:"contract",channelId:$channelId,version:1,listing:$listing}')
|
||||
contract_result=$(channel_write "$contract")
|
||||
listing=$(jq -r '.event_id' <<<"$contract_result")
|
||||
announcement=$(jq -cn --arg protocol 'buzz-market/v0' --arg channelId "$channel" --arg listingEventId "$listing" --argjson listing "$terms" '{protocol:$protocol,type:"announcement",channelId:$channelId,version:1,listingEventId:$listingEventId,listing:$listing}')
|
||||
pulse_result=$(buzz social publish --content "$announcement")
|
||||
jq -cn --arg channel_id "$channel" --arg listing_event_id "$listing" --arg announcement_event_id "$(jq -r '.event_id' <<<"$pulse_result")" '{channel_id:$channel_id,listing_event_id:$listing_event_id,announcement_event_id:$announcement_event_id}'
|
||||
;;
|
||||
response)
|
||||
need market "$market"; need listing "$listing"; need actor "$actor"; need quantity "$quantity"; need message "$message"
|
||||
payload=$(jq -cn --arg protocol 'buzz-market/v0' --arg marketId "$market" --arg listingEventId "$listing" --arg actorName "$actor" --arg quantity "$quantity" --arg amount "$amount" --arg message "$message" \
|
||||
'{protocol:$protocol,type:"response",marketId:$marketId,listingEventId:$listingEventId,actorName:$actorName,quantity:($quantity|tonumber),message:$message} + (if $amount!="" then {amountSats:($amount|tonumber)} else {} end)')
|
||||
json_write "$payload"
|
||||
;;
|
||||
need channel "$channel"; need listing "$listing"; need actor "$actor"; need quantity "$quantity"; need message "$message"
|
||||
payload=$(jq -cn --arg protocol 'buzz-market/v0' --arg channelId "$channel" --arg listingEventId "$listing" --arg actorName "$actor" --arg quantity "$quantity" --arg amount "$amount" --arg message "$message" '{protocol:$protocol,type:"response",channelId:$channelId,listingEventId:$listingEventId,actorName:$actorName,quantity:($quantity|tonumber),message:$message} + (if $amount!="" then {amountSats:($amount|tonumber)} else {} end)')
|
||||
channel_write "$payload" ;;
|
||||
award)
|
||||
need market "$market"; need listing "$listing"; need response "$response"; need actor "$actor"; need quantity "$quantity"; need amount "$amount"
|
||||
payload=$(jq -cn --arg protocol 'buzz-market/v0' --arg marketId "$market" --arg listingEventId "$listing" --arg responseEventId "$response" --arg actorName "$actor" --arg quantity "$quantity" --arg amount "$amount" \
|
||||
'{protocol:$protocol,type:"award",marketId:$marketId,listingEventId:$listingEventId,responseEventId:$responseEventId,actorName:$actorName,quantity:($quantity|tonumber),amountSats:($amount|tonumber)}')
|
||||
json_write "$payload"
|
||||
;;
|
||||
need channel "$channel"; need listing "$listing"; need response "$response"; need actor "$actor"; need quantity "$quantity"; need amount "$amount"
|
||||
payload=$(jq -cn --arg protocol 'buzz-market/v0' --arg channelId "$channel" --arg listingEventId "$listing" --arg responseEventId "$response" --arg actorName "$actor" --arg quantity "$quantity" --arg amount "$amount" '{protocol:$protocol,type:"award",channelId:$channelId,listingEventId:$listingEventId,responseEventId:$responseEventId,actorName:$actorName,quantity:($quantity|tonumber),amountSats:($amount|tonumber)}')
|
||||
channel_write "$payload" ;;
|
||||
fulfill)
|
||||
need market "$market"; need listing "$listing"; need award "$award"; need actor "$actor"; need message "$message"
|
||||
payload=$(jq -cn --arg protocol 'buzz-market/v0' --arg marketId "$market" --arg listingEventId "$listing" --arg awardEventId "$award" --arg actorName "$actor" --arg message "$message" \
|
||||
'{protocol:$protocol,type:"fulfillment",marketId:$marketId,listingEventId:$listingEventId,awardEventId:$awardEventId,actorName:$actorName,message:$message}')
|
||||
json_write "$payload"
|
||||
;;
|
||||
need channel "$channel"; need listing "$listing"; need award "$award"; need actor "$actor"; need message "$message"
|
||||
payload=$(jq -cn --arg protocol 'buzz-market/v0' --arg channelId "$channel" --arg listingEventId "$listing" --arg awardEventId "$award" --arg actorName "$actor" --arg message "$message" '{protocol:$protocol,type:"fulfillment",channelId:$channelId,listingEventId:$listingEventId,awardEventId:$awardEventId,actorName:$actorName,message:$message}')
|
||||
channel_write "$payload" ;;
|
||||
settle)
|
||||
need market "$market"; need listing "$listing"; need award "$award"; need fulfillment "$fulfillment"; need actor "$actor"; need amount "$amount"
|
||||
payload=$(jq -cn --arg protocol 'buzz-market/v0' --arg marketId "$market" --arg listingEventId "$listing" --arg awardEventId "$award" --arg fulfillmentEventId "$fulfillment" --arg actorName "$actor" --arg amount "$amount" \
|
||||
'{protocol:$protocol,type:"settlement",marketId:$marketId,listingEventId:$listingEventId,awardEventId:$awardEventId,fulfillmentEventId:$fulfillmentEventId,actorName:$actorName,amountSats:($amount|tonumber)}')
|
||||
json_write "$payload"
|
||||
;;
|
||||
need channel "$channel"; need listing "$listing"; need award "$award"; need fulfillment "$fulfillment"; need actor "$actor"; need amount "$amount"
|
||||
payload=$(jq -cn --arg protocol 'buzz-market/v0' --arg channelId "$channel" --arg listingEventId "$listing" --arg awardEventId "$award" --arg fulfillmentEventId "$fulfillment" --arg actorName "$actor" --arg amount "$amount" '{protocol:$protocol,type:"settlement",channelId:$channelId,listingEventId:$listingEventId,awardEventId:$awardEventId,fulfillmentEventId:$fulfillmentEventId,actorName:$actorName,amountSats:($amount|tonumber)}')
|
||||
channel_write "$payload" ;;
|
||||
watch)
|
||||
((${#pubkeys[@]} > 0)) || die "watch requires at least one --pubkey"
|
||||
combined='[]'
|
||||
for pubkey in "${pubkeys[@]}"; do
|
||||
events=$(buzz social notes --pubkey "$pubkey" --limit 100)
|
||||
combined=$(jq -cn --argjson left "$combined" --argjson right "$events" '$left + $right')
|
||||
done
|
||||
jq '[.[] | select(.kind == 1) | . as $event | (try (.content | fromjson) catch null) as $body | select($body.protocol == "buzz-market/v0") | {id, pubkey, created_at, marketId:$body.marketId, type:$body.type, body:$body}] | sort_by(.created_at, ({listing:0,response:1,award:2,fulfillment:3,settlement:4}[.type] // 99), .id)' <<<"$combined"
|
||||
need channel "$channel"
|
||||
buzz messages get --channel "$channel" --limit 100 | jq '[.[] | . as $event | (try (.content | fromjson) catch null) as $body | select($body.protocol == "buzz-market/v0" and $body.channelId == $channel) | {id,pubkey,created_at,type:$body.type,body:$body}] | sort_by(.created_at, ({contract:0,response:1,award:2,fulfillment:3,settlement:4}[.type] // 99), .id)' --arg channel "$channel"
|
||||
;;
|
||||
*) usage; die "unknown command: $command_name" ;;
|
||||
esac
|
||||
|
||||
Reference in New Issue
Block a user