forked from Prompt-Hash-Stellar/prompt-hash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromptHashClient.ts
More file actions
313 lines (291 loc) · 8.32 KB
/
Copy pathpromptHashClient.ts
File metadata and controls
313 lines (291 loc) · 8.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
/**
* WARNING: MOCK CONTRACT IMPLEMENTATION
* This file currently stubs all on-chain reads/writes with mock data.
* This should NOT reach production.
* TODO: Restore real Soroban contract integration before release.
*/
import { Server } from "@stellar/stellar-sdk/rpc";
let hasWarnedMock = false;
const warnMockUse = () => {
if (hasWarnedMock) return;
console.warn(
"⚠️ USING MOCK PromptHashClient: Contract calls are currently stubbed and will not hit the Stellar network.",
);
hasWarnedMock = true;
};
export interface PromptHashConfig {
rpcUrl: string;
networkPassphrase: string;
allowHttp?: boolean;
promptHashContractId: string;
nativeAssetContractId: string;
simulationAccount?: string;
}
// Added the missing interface required by the UI
export interface PromptRecord {
id: bigint;
creator: string;
priceStroops: bigint;
title: string;
category: string;
previewText: string;
description?: string;
tags?: string[];
imageUrl: string;
salesCount: number;
active: boolean;
contentHash: string;
encryptedPrompt?: string;
encryptionIv?: string;
wrappedKey?: string;
}
export interface RevenueSplitInput {
recipient: string;
bps: number;
}
export interface CreatePromptInput {
imageUrl: string;
title: string;
category: string;
previewText: string;
encryptedPrompt: string;
encryptionIv: string;
wrappedKey: string;
contentHash: string;
priceStroops: bigint;
splits?: RevenueSplitInput[];
}
export class PromptHashClient {
/**
* Checks if the user already has access to the prompt.
*/
static async checkAccess(
_config: PromptHashConfig | string,
_address: string,
_itemId?: string | bigint,
): Promise<boolean> {
warnMockUse();
return new Promise((resolve) => {
setTimeout(() => resolve(false), 1000);
});
}
static async getPrompt(
_config: PromptHashConfig,
promptId: bigint,
): Promise<PromptRecord> {
warnMockUse();
const prompts = await PromptHashClient.getAllPrompts(_config);
const match = prompts.find((p) => p.id === promptId);
if (!match) {
throw new Error(`Prompt #${promptId.toString()} not found.`);
}
return match;
}
/**
* Invokes the Soroban contract to purchase a prompt.
*/
static async purchasePrompt(
_itemId: string,
_userAddress: string,
options?: { forceFailure?: string; delay?: number },
): Promise<{ txHash: string; success: boolean }> {
warnMockUse();
return new Promise((resolve, reject) => {
const delay = options?.delay ?? 2000;
setTimeout(() => {
if (options?.forceFailure) {
return reject(new Error(options.forceFailure));
}
const mockHash =
"tx_" + Math.random().toString(16).slice(2, 14).padStart(12, "0");
resolve({ txHash: mockHash, success: true });
}, delay);
});
}
static async getAllPrompts(
_config: PromptHashConfig,
): Promise<PromptRecord[]> {
warnMockUse();
// Returning mock data so the Browse page isn't empty
return [
{
id: 1n,
creator: "GD...1234",
priceStroops: 50000000n, // 5 XLM
title: "GPT-4 Technical Architect",
category: "Development",
previewText:
"A high-performance prompt for generating system design documents...",
description:
"A full prompt designed to help architects craft scalable system blueprints and integration plans.",
tags: ["AI", "Architecture"],
imageUrl: "",
salesCount: 12,
active: true,
contentHash: "mock_hash_000000000001",
},
{
id: 2n,
creator: "GB...5678",
priceStroops: 120000000n, // 12 XLM
title: "Creative Storyteller Pro",
category: "Creative",
previewText:
"Unlock deep narrative structures and character development...",
description:
"A storytelling prompt built to help craft plot outlines, characters, and emotional arcs for long-form fiction.",
tags: ["Storytelling", "Creative"],
imageUrl: "",
salesCount: 45,
active: true,
contentHash: "mock_hash_000000000002",
},
];
}
static async getPromptsByBuyer(
_config: PromptHashConfig,
_address: string,
): Promise<PromptRecord[]> {
warnMockUse();
return [];
}
static async getPromptsByCreator(
_config: PromptHashConfig,
_address: string,
): Promise<PromptRecord[]> {
warnMockUse();
return [];
}
static async createPrompt(
_config: PromptHashConfig,
_walletSignerLike: any,
_address: string,
_data: CreatePromptInput,
) {
warnMockUse();
return { success: true, txHash: "tx_mock", promptId: "123" };
}
static async setPromptSaleStatus(
_config: PromptHashConfig,
_walletSignerLike: any,
_address: string,
_promptId: string,
_isForSale: boolean,
) {
warnMockUse();
return { success: true };
}
static async updatePromptPrice(
_config: PromptHashConfig,
_walletSignerLike: any,
_address: string,
_promptId: string,
_newPrice: string,
) {
warnMockUse();
return { success: true };
}
static async getRecentPurchases(
config: PromptHashConfig,
limit: number = 10
) {
try {
const server = new Server(config.rpcUrl, {
allowHttp: config.allowHttp,
});
// Get current ledger to limit our search
const latestLedgerResponse = await server.getLatestLedger();
const latestLedger = latestLedgerResponse.sequence;
// Search the last 10,000 ledgers (~14 hours)
const startLedger = Math.max(1, latestLedger - 10000);
const events = await server.getEvents({
startLedger,
filters: [
{
type: "contract",
contractIds: [config.promptHashContractId],
// Topics could be strictly typed to the PromptPurchased event topic if known
}
],
limit,
});
// Here we would normally parse `events.events` and decode the XDR.
// Since this is partly mocked, and XDR decoding is complex, we return a simulated list
// formatted as what we'd expect.
return events.events.map((e, i) => ({
id: e.id || `rpc-event-${i}`,
type: "sale",
title: `Prompt #${e.topic?.[1] || i}`, // Without full XDR decoding, we use placeholder
category: "Marketplace",
actor: "Someone", // Anonymized
timestamp: e.ledgerClosedAt,
priceXlm: undefined,
}));
} catch (e) {
console.error("Failed to fetch events from Soroban RPC:", e);
// Fallback for mocked environment
return [];
}
}
}
// --- Standalone exports to satisfy existing UI component imports ---
export const hasAccess = async (
config: PromptHashConfig,
address: string,
itemId: string | bigint,
) =>
PromptHashClient.checkAccess(
config,
address,
typeof itemId === "bigint" ? itemId.toString() : itemId,
);
export const getPrompt = async (config: PromptHashConfig, promptId: bigint) =>
PromptHashClient.getPrompt(config, promptId);
export const getAllPrompts = async (config: PromptHashConfig) =>
PromptHashClient.getAllPrompts(config);
export const getPromptsByBuyer = async (
config: PromptHashConfig,
address: string,
) => PromptHashClient.getPromptsByBuyer(config, address);
export const getPromptsByCreator = async (
config: PromptHashConfig,
address: string,
) => PromptHashClient.getPromptsByCreator(config, address);
export const createPrompt = async (
config: PromptHashConfig,
walletSignerLike: any,
address: string,
data: CreatePromptInput,
) => PromptHashClient.createPrompt(config, walletSignerLike, address, data);
export const setPromptSaleStatus = async (
config: PromptHashConfig,
walletSignerLike: any,
address: string,
promptId: string,
isForSale: boolean,
) =>
PromptHashClient.setPromptSaleStatus(
config,
walletSignerLike,
address,
promptId,
isForSale,
);
export const updatePromptPrice = async (
config: PromptHashConfig,
walletSignerLike: any,
address: string,
promptId: string,
newPrice: string,
) =>
PromptHashClient.updatePromptPrice(
config,
walletSignerLike,
address,
promptId,
newPrice,
);
export const getRecentPurchases = async (
config: PromptHashConfig,
limit?: number
) => PromptHashClient.getRecentPurchases(config, limit);