-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathweb.ts
More file actions
333 lines (305 loc) · 8.71 KB
/
Copy pathweb.ts
File metadata and controls
333 lines (305 loc) · 8.71 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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import {
createPublicClient,
createWalletClient,
defineChain,
http,
webSocket,
encodeFunctionData,
decodeFunctionResult,
decodeEventLog,
BaseError,
} from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { config } from './config.js';
const PLATFORM_ADDRESS = '0x037Bb9C718F3f7fe5eCBDB0b600D607b52706776';
const RPC_URL = 'https://dream-rpc.somnia.network/';
const WS_URL = 'wss://dream-rpc.somnia.network/ws';
const PER_AGENT_EXECUTION_COST = 100000000000000000n;
const SUBCOMMITTEE_SIZE = 3n;
const somniaTestnet = defineChain({
id: 50312,
name: 'Somnia Testnet',
nativeCurrency: { decimals: 18, name: 'STT', symbol: 'STT' },
rpcUrls: {
default: {
http: [RPC_URL],
webSocket: [WS_URL],
},
},
});
const ResponseStatus = {
None: 0,
Pending: 1,
Success: 2,
Failed: 3,
TimedOut: 4,
} as const;
const platformAbi = [
{
type: 'function',
name: 'createRequest',
inputs: [
{ type: 'uint256', name: 'agentId' },
{ type: 'address', name: 'callbackAddress' },
{ type: 'bytes4', name: 'callbackSelector' },
{ type: 'bytes', name: 'payload' },
],
outputs: [{ type: 'uint256', name: 'requestId' }],
stateMutability: 'payable',
},
{
type: 'function',
name: 'getRequestDeposit',
inputs: [],
outputs: [{ type: 'uint256', name: '' }],
stateMutability: 'view',
},
{
type: 'function',
name: 'getRequest',
inputs: [{ type: 'uint256', name: 'requestId' }],
outputs: [
{
type: 'tuple',
components: [
{ type: 'uint256', name: 'id' },
{ type: 'address', name: 'requester' },
{ type: 'address', name: 'callbackAddress' },
{ type: 'bytes4', name: 'callbackSelector' },
{ type: 'address[]', name: 'subcommittee' },
{
type: 'tuple[]',
name: 'responses',
components: [
{ type: 'address', name: 'validator' },
{ type: 'bytes', name: 'result' },
{ type: 'uint8', name: 'status' },
{ type: 'uint256', name: 'receipt' },
{ type: 'uint256', name: 'timestamp' },
{ type: 'uint256', name: 'executionCost' },
],
},
{ type: 'uint256', name: 'responseCount' },
{ type: 'uint256', name: 'failureCount' },
{ type: 'uint256', name: 'threshold' },
{ type: 'uint256', name: 'createdAt' },
{ type: 'uint256', name: 'deadline' },
{ type: 'uint8', name: 'status' },
{ type: 'uint8', name: 'consensusType' },
{ type: 'uint256', name: 'remainingBudget' },
{ type: 'uint256', name: 'perAgentBudget' },
],
},
],
stateMutability: 'view',
},
{
type: 'event',
name: 'RequestCreated',
inputs: [
{ type: 'uint256', name: 'requestId', indexed: true },
{ type: 'uint256', name: 'agentId', indexed: true },
{ type: 'uint256', name: 'perAgentBudget', indexed: false },
{ type: 'bytes', name: 'payload', indexed: false },
{ type: 'address[]', name: 'subcommittee', indexed: false },
],
},
{
type: 'event',
name: 'RequestFinalized',
inputs: [
{ type: 'uint256', name: 'requestId', indexed: true },
{ type: 'uint8', name: 'status', indexed: false },
],
},
] as const;
const agentMethodAbi = [
{
type: 'function',
name: 'ExtractString',
inputs: [
{ type: 'string', name: 'key' },
{ type: 'string', name: 'description' },
{ type: 'string[]', name: 'options' },
{ type: 'string', name: 'prompt' },
{ type: 'string', name: 'url' },
{ type: 'bool', name: 'resolveUrl' },
{ type: 'uint8', name: 'numPages' },
{ type: 'uint8', name: 'confidenceThreshold' },
],
outputs: [{ type: 'string', name: 'output' }],
},
] as const;
async function invokeAgent(
key: string,
description: string,
options: string[],
prompt: string,
url: string,
resolveUrl: boolean,
numPages: number,
confidenceThreshold: number,
) {
const account = privateKeyToAccount(config.PRIVATE_KEY! as `0x${string}`);
const walletClient = createWalletClient({
account,
chain: somniaTestnet,
transport: http(RPC_URL),
});
const readClient = createPublicClient({
chain: somniaTestnet,
transport: http(RPC_URL),
});
const eventClient = createPublicClient({
chain: somniaTestnet,
transport: webSocket(WS_URL),
});
// 1. Encode payload
const payload = encodeFunctionData({
abi: agentMethodAbi,
functionName: 'ExtractString',
args: [
key,
description,
options,
prompt,
url,
resolveUrl,
numPages,
confidenceThreshold,
],
});
// 2. Calculate deposit
const reserve = await readClient.readContract({
address: PLATFORM_ADDRESS,
abi: platformAbi,
functionName: 'getRequestDeposit',
});
const deposit = reserve + PER_AGENT_EXECUTION_COST * SUBCOMMITTEE_SIZE;
// 3. Submit request
const hash = await walletClient.writeContract({
address: PLATFORM_ADDRESS,
abi: platformAbi,
functionName: 'createRequest',
args: [
12875401142070969085n,
'0x0000000000000000000000000000000000000000',
'0x00000000',
payload,
],
value: deposit,
});
console.log('Transaction submitted:', hash);
// 4. Extract requestId from receipt
const receipt = await readClient.waitForTransactionReceipt({
hash,
confirmations: 2,
});
const createdEvent = receipt.logs
.map((log) => {
try {
return decodeEventLog({
abi: platformAbi,
data: log.data,
topics: log.topics,
});
} catch {
return null;
}
})
.find((e) => e?.eventName === 'RequestCreated');
const requestId = createdEvent?.args?.requestId;
if (requestId == null)
throw new Error('RequestCreated event not found in transaction logs');
console.log('Request ID:', requestId);
// 5. Wait for RequestFinalized — capture the block number it landed in
const { finalizedStatus, finalizedBlockNumber } = await new Promise<{
finalizedStatus: number;
finalizedBlockNumber: bigint;
}>((resolve, reject) => {
let settled = false;
const timeout = setTimeout(() => {
if (settled) return;
settled = true;
unwatch();
reject(
new Error(
`Timed out waiting for RequestFinalized for request ${requestId}`,
),
);
}, 120_000);
const unwatch = eventClient.watchContractEvent({
address: PLATFORM_ADDRESS,
abi: platformAbi,
eventName: 'RequestFinalized',
onLogs: (logs) => {
for (const log of logs) {
if (log.args.requestId === requestId) {
if (settled) return;
settled = true;
clearTimeout(timeout);
unwatch();
resolve({
finalizedStatus: Number(log.args.status),
finalizedBlockNumber: log.blockNumber,
});
return;
}
}
},
onError: (error) => {
if (settled) return;
settled = true;
clearTimeout(timeout);
unwatch();
reject(error);
},
});
});
if (finalizedStatus !== ResponseStatus.Success) {
throw new Error(
finalizedStatus === ResponseStatus.Failed
? `Agent execution failed for request ${requestId}`
: `Request ${requestId} finalized with status ${finalizedStatus}`,
);
}
// 6. Read request at the block BEFORE finalization — still exists in that state
console.log(`Reading request state at block ${finalizedBlockNumber - 1n}...`);
let request;
try {
request = await readClient.readContract({
account,
address: PLATFORM_ADDRESS,
abi: platformAbi,
functionName: 'getRequest',
args: [requestId],
blockNumber: finalizedBlockNumber - 1n, // request not yet deleted here
});
} catch (error) {
const details =
error instanceof BaseError
? error.shortMessage
: error instanceof Error
? error.message
: String(error);
throw new Error(
`Failed to read request ${requestId} at pre-finalization block: ${details}`,
);
}
console.log('Responses:', request.responses);
// 7. Find the first successful response (not just index 0)
const successfulResponse = request.responses.find(
(r) => r.status === ResponseStatus.Success,
);
if (!successfulResponse) {
throw new Error(`No successful response found for request ${requestId}`);
}
const result = decodeFunctionResult({
abi: agentMethodAbi,
functionName: 'ExtractString',
data: successfulResponse.result,
});
console.log('Result:', result);
return result;
}
export default invokeAgent;