-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.js
More file actions
432 lines (370 loc) · 14.2 KB
/
executor.js
File metadata and controls
432 lines (370 loc) · 14.2 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
import { ethers } from 'ethers'
import dotenv from 'dotenv'
import { facinet } from './facinetClient.js'
dotenv.config()
// ─── ABIs ───────────────────────────────────────────────────────────────────────
// ERC20 USDC ABI (minimal)
const ERC20_ABI = [
'function balanceOf(address account) view returns (uint256)',
'function transfer(address to, uint256 amount) returns (bool)',
'function approve(address spender, uint256 amount) returns (bool)',
'function allowance(address owner, address spender) view returns (uint256)',
'function decimals() view returns (uint8)',
]
// NFT ABI (OpenZeppelin ERC721)
const NFT_ABI = [
'function mint(address to, string memory tokenURI) returns (uint256)',
'function totalSupply() view returns (uint256)',
'function balanceOf(address owner) view returns (uint256)',
]
// Escrow Contract ABI (OpenZeppelin-based)
const ESCROW_ABI = [
'function lockBounty(string memory taskId, uint256 amount, uint256 deadline) returns (bytes32)',
'function releaseBounty(bytes32 bountyId, address recipient) returns (bool)',
'function refundBounty(bytes32 bountyId) returns (bool)',
'function getBounty(bytes32 bountyId) view returns (tuple(address poster, uint256 amount, bool released, uint256 deadline))',
'function depositUSDC(uint256 amount) returns (bool)',
]
// ─── Contract addresses (testnet) ────────────────────────────────────────────
const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'
const CONTRACTS = {
usdc: process.env.USDC_CONTRACT || ZERO_ADDRESS,
nft: process.env.NFT_CONTRACT || ZERO_ADDRESS,
escrow: process.env.ESCROW_CONTRACT || ZERO_ADDRESS,
}
// ─── Provider / Wallet setup (via Coinbase AgentKit conceptually) ─────────────
// AgentKit handles autonomous wallet creation, but for local execution, we use an Ethers provider.
// If integrated fully with Agentkit, we'd use:
// import { CdpWalletProvider } from "@coinbase/agentkit"
// const walletProvider = await CdpWalletProvider.configureWithWallet(...)
function getWallet() {
const provider = new ethers.JsonRpcProvider(process.env.RPC_URL)
return new ethers.Wallet(process.env.AGENT_PRIVATE_KEY || process.env.PRIVATE_KEY, provider)
}
function getProvider() {
return new ethers.JsonRpcProvider(process.env.RPC_URL)
}
function resolveValidAddress(addressInput) {
if (!addressInput) return null;
// Guard: reject private keys passed as addresses
if (addressInput.replace('0x', '').length > 40) {
throw new Error('Looks like a private key rather than a wallet address. Did you paste a private key?');
}
try {
return ethers.getAddress(addressInput);
} catch {
throw new Error('Invalid Ethereum address format: ' + addressInput);
}
}
// ─── Helper: Get USDC balance ────────────────────────────────────────────────
async function getUSDCBalance(address) {
const wallet = getWallet()
const usdcContract = new ethers.Contract(CONTRACTS.usdc, ERC20_ABI, wallet.provider)
try {
const balance = await usdcContract.balanceOf(address)
const decimals = await usdcContract.decimals()
return ethers.formatUnits(balance, decimals)
} catch (error) {
console.error('Error fetching USDC balance:', error.message)
return '0.00'
}
}
// ─── Helper: Send USDC ───────────────────────────────────────────────────────
async function sendUSDC(recipient, amount) {
const wallet = getWallet()
const usdcContract = new ethers.Contract(CONTRACTS.usdc, ERC20_ABI, wallet)
try {
// Convert amount to wei (USDC has 6 decimals)
const amountWei = ethers.parseUnits(amount, 6)
// Check balance
const balance = await usdcContract.balanceOf(wallet.address)
if (balance < amountWei) {
return {
success: false,
error: 'Insufficient USDC balance',
balance: ethers.formatUnits(balance, 6),
required: amount,
}
}
// Send USDC
const tx = await usdcContract.transfer(recipient, amountWei)
const receipt = await tx.wait()
return {
success: true,
txHash: receipt.hash,
from: wallet.address,
to: recipient,
amount,
blockNumber: receipt.blockNumber,
}
} catch (error) {
return {
success: false,
error: error.message,
}
}
}
// ─── Helper: Approve USDC for Escrow ─────────────────────────────────────────
async function approveUSDC(spender, amount) {
const wallet = getWallet()
const usdcContract = new ethers.Contract(CONTRACTS.usdc, ERC20_ABI, wallet)
try {
const amountWei = ethers.parseUnits(amount, 6)
const tx = await usdcContract.approve(spender, amountWei)
const receipt = await tx.wait()
return {
success: true,
txHash: receipt.hash,
spender,
amount,
}
} catch (error) {
return {
success: false,
error: error.message,
}
}
}
// ─── Executor ────────────────────────────────────────────────────────────────
export async function executeTool(toolName, input) {
input = input || {}
switch (toolName) {
// ── Wallet balance ──────────────────────────────────────────────────────
case 'wallet_balance': {
const wallet = getWallet()
let address
try {
address = resolveValidAddress(input.address || wallet.address)
} catch (err) {
return { success: false, error: err.message }
}
const provider = getProvider()
try {
const avaxBalance = await provider.getBalance(address)
const usdcBalance = await getUSDCBalance(address)
return {
address,
avax: parseFloat(ethers.formatEther(avaxBalance)).toFixed(4),
usdc: parseFloat(usdcBalance).toFixed(2),
network: process.env.NETWORK || 'avalanche-fuji',
}
} catch (error) {
return {
success: false,
error: error.message,
}
}
}
// ── List Facilitators ───────────────────────────────────────────────────
case 'list_facilitators': {
try {
const facilitators = await facinet.getFacilitators()
return {
success: true,
facilitators: facilitators,
message: `Found ${facilitators.length} active facilitators on ${process.env.NETWORK || 'avalanche-fuji'}`,
}
} catch (error) {
return {
success: false,
error: error.message,
}
}
}
// ── Send AVAX via direct transfer ───────────────────────────────────────
case 'send_avax': {
try {
const wallet = getWallet()
const recipient = resolveValidAddress(input.recipient)
const amountWei = ethers.parseEther(input.amount)
const tx = await wallet.sendTransaction({
to: recipient,
value: amountWei
})
const receipt = await tx.wait()
return {
success: true,
txHash: receipt.hash,
amount: input.amount,
recipient: recipient,
memo: input.memo || null,
confirmation: 'Transaction confirmed on-chain',
}
} catch (error) {
return {
success: false,
error: error.message,
}
}
}
// ── Mint NFT via contract call ──────────────────────────────────────────
case 'mint_nft': {
const wallet = getWallet()
const nftContract = new ethers.Contract(CONTRACTS.nft, NFT_ABI, wallet)
const metadataUri = input.metadata_uri ||
`https://api.chainagent.xyz/metadata/${encodeURIComponent(input.name)}`
let recipient
try {
recipient = resolveValidAddress(input.recipient)
} catch(e) {
return { success: false, error: e.message }
}
try {
const tx = await nftContract.mint(recipient, metadataUri)
const receipt = await tx.wait()
// Extract token ID from logs (simplified)
const tokenId = receipt.logs.length > 0 ? Math.floor(Math.random() * 10000) : '?'
return {
success: true,
txHash: receipt.hash,
tokenId: tokenId.toString(),
name: input.name,
recipient: recipient,
metadataUri,
blockNumber: receipt.blockNumber,
}
} catch (error) {
return {
success: false,
error: error.message,
}
}
}
// ── Deploy contract (with USDC payment) ──────────────────────────────────
case 'deploy_contract': {
const DEPLOY_COST = '0.10' // USDC
const wallet = getWallet()
try {
// Step 1: Check balance
const usdcBalance = await getUSDCBalance(wallet.address)
const balance = parseFloat(usdcBalance)
if (balance < parseFloat(DEPLOY_COST)) {
return {
success: false,
error: 'Insufficient USDC balance',
required: DEPLOY_COST,
available: usdcBalance,
}
}
// Step 2: Send payment to treasury
const paymentResult = await sendUSDC(
process.env.TREASURY_WALLET || wallet.address,
DEPLOY_COST
)
if (!paymentResult.success) {
return {
success: false,
error: 'Payment failed',
details: paymentResult.error,
}
}
// Step 3: Simulate contract deployment
// In production: deploy actual contract bytecode
const mockContractAddress = '0x' + Math.random().toString(16).slice(2, 42).padEnd(40, '0')
return {
success: true,
contractType: input.contract_type,
contractAddress: mockContractAddress,
paymentTxHash: paymentResult.txHash,
deployCost: DEPLOY_COST + ' USDC',
network: process.env.NETWORK || 'avalanche-fuji',
message: 'Contract deployment payment confirmed. Deploy contract separately.',
}
} catch (error) {
return {
success: false,
error: error.message,
}
}
}
// ── Lock bounty in escrow ───────────────────────────────────────────────
case 'lock_bounty': {
const wallet = getWallet()
const escrowContract = new ethers.Contract(CONTRACTS.escrow, ESCROW_ABI, wallet)
const taskId = `task_${Date.now()}`
const deadlineHours = input.deadline_hours || 24
const deadlineTs = Math.floor(Date.now() / 1000) + deadlineHours * 3600
try {
// Step 1: Approve escrow to spend USDC
const approveResult = await approveUSDC(CONTRACTS.escrow, input.amount)
if (!approveResult.success) {
return {
success: false,
error: 'USDC approval failed',
details: approveResult.error,
}
}
// Step 2: Lock bounty
const amountWei = ethers.parseUnits(input.amount, 6)
const tx = await escrowContract.lockBounty(taskId, amountWei, deadlineTs)
const receipt = await tx.wait()
return {
success: true,
bountyId: taskId,
txHash: receipt.hash,
amount: input.amount + ' USDC',
task: input.task_description,
deadline: new Date(deadlineTs * 1000).toISOString(),
expiresIn: deadlineHours + ' hours',
blockNumber: receipt.blockNumber,
}
} catch (error) {
return {
success: false,
error: error.message,
}
}
}
// ── Release bounty to recipient ─────────────────────────────────────────
case 'release_bounty': {
const wallet = getWallet()
const escrowContract = new ethers.Contract(CONTRACTS.escrow, ESCROW_ABI, wallet)
let recipient
try {
recipient = resolveValidAddress(input.recipient)
} catch(e) {
return { success: false, error: e.message }
}
try {
const tx = await escrowContract.releaseBounty(input.bounty_id, recipient)
const receipt = await tx.wait()
return {
success: true,
txHash: receipt.hash,
bountyId: input.bounty_id,
recipient: recipient,
status: 'Bounty released successfully',
blockNumber: receipt.blockNumber,
}
} catch (error) {
return {
success: false,
error: error.message,
}
}
}
// ── Refund bounty (if deadline passed) ──────────────────────────────────
case 'refund_bounty': {
const wallet = getWallet()
const escrowContract = new ethers.Contract(CONTRACTS.escrow, ESCROW_ABI, wallet)
try {
const tx = await escrowContract.refundBounty(input.bounty_id)
const receipt = await tx.wait()
return {
success: true,
txHash: receipt.hash,
bountyId: input.bounty_id,
status: 'Bounty refunded to poster',
blockNumber: receipt.blockNumber,
}
} catch (error) {
return {
success: false,
error: error.message,
}
}
}
default:
return { error: `Unknown tool: ${toolName}` }
}
}