-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChainPilot_Agent.py
460 lines (375 loc) · 15 KB
/
ChainPilot_Agent.py
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
import json
from swarm import Agent
from cdp import *
from typing import List, Dict, Any
import os
from openai import OpenAI
from decimal import Decimal
from typing import Union
from web3 import Web3
from web3.exceptions import ContractLogicError
from cdp.errors import ApiError, UnsupportedAssetError
from dotenv import load_dotenv
from duckduckgo_search import DDGS
from swarm.repl import run_demo_loop
from datetime import datetime
load_dotenv()
API_KEY_NAME = os.environ.get("CDP_API_KEY_NAME")
PRIVATE_KEY = os.environ.get("CDP_PRIVATE_KEY", "").replace('\\n', '\n')
Cdp.configure(API_KEY_NAME, PRIVATE_KEY)
agent_wallet = Wallet.create()
faucet = agent_wallet.faucet()
print(f"Faucet transaction: {faucet}")
print(f"Agent wallet address: {agent_wallet.default_address.address_id}")
# Function to create a new ERC-20 token
def create_token(name, symbol, initial_supply):
"""
Create a new ERC-20 token.
Args:
name (str): The name of the token
symbol (str): The symbol of the token
initial_supply (int): The initial supply of tokens
Returns:
str: A message confirming the token creation with details
"""
deployed_contract = agent_wallet.deploy_token(name, symbol, initial_supply)
deployed_contract.wait()
transaction_link = deployed_contract._transaction.transaction_link
return f"Token {name} ({symbol}) created with initial supply of {initial_supply} and contract address {deployed_contract.contract_address}. This is the transaction link : {transaction_link}"
# Function to transfer assets
def transfer_asset(amount, asset_id, destination_address):
"""
Transfer an asset to a specific address.
Args:
amount (Union[int, float, Decimal]): Amount to transfer
asset_id (str): Asset identifier ("eth", "usdc") or contract address of an ERC-20 token
destination_address (str): Recipient's address
Returns:
str: A message confirming the transfer or describing an error
"""
try:
# Check if we're on Base Mainnet and the asset is USDC for gasless transfer
is_mainnet = agent_wallet.network_id == "base-mainnet"
is_usdc = asset_id.lower() == "usdc"
gasless = is_mainnet and is_usdc
# For ETH and USDC, we can transfer directly without checking balance
if asset_id.lower() in ["eth", "usdc"]:
transfer = agent_wallet.transfer(amount,
asset_id,
destination_address,
gasless=gasless)
transfer.wait()
gasless_msg = " (gasless)" if gasless else ""
return f"Transferred {amount} {asset_id}{gasless_msg} to {destination_address}"
# For other assets, check balance first
try:
balance = agent_wallet.balance(asset_id)
except UnsupportedAssetError:
return f"Error: The asset {asset_id} is not supported on this network. It may have been recently deployed. Please try again in about 30 minutes."
if balance < amount:
return f"Insufficient balance. You have {balance} {asset_id}, but tried to transfer {amount}."
transfer = agent_wallet.transfer(amount, asset_id, destination_address)
transfer.wait()
return f"Transferred {amount} {asset_id} to {destination_address}"
except Exception as e:
return f"Error transferring asset: {str(e)}. If this is a custom token, it may have been recently deployed. Please try again in about 30 minutes, as it needs to be indexed by CDP first."
# Function to get the balance of a specific asset
def get_balance(asset_id):
"""
Get the balance of a specific asset in the agent's wallet.
Args:
asset_id (str): Asset identifier ("eth", "usdc") or contract address of an ERC-20 token
Returns:
str: A message showing the current balance of the specified asset
"""
balance = agent_wallet.balance(asset_id)
return f"Current balance of {asset_id}: {balance}"
# Function to request ETH from the faucet (testnet only)
def request_eth_from_faucet():
"""
Request ETH from the Base Sepolia testnet faucet.
Returns:
str: Status message about the faucet request
"""
if agent_wallet.network_id == "base-mainnet":
return "Error: The faucet is only available on Base Sepolia testnet."
faucet_tx = agent_wallet.faucet()
return f"Requested ETH from faucet. Transaction: {faucet_tx}"
# Function to generate art using DALL-E (requires separate OpenAI API key)
def generate_art(prompt):
"""
Generate art using DALL-E based on a text prompt.
Args:
prompt (str): Text description of the desired artwork
Returns:
str: Status message about the art generation, including the image URL if successful
"""
try:
client = OpenAI()
response = client.images.generate(
model="dall-e-3",
prompt=prompt,
size="1024x1024",
quality="standard",
n=1,
)
image_url = response.data[0].url
return f"Generated artwork available at: {image_url}"
except Exception as e:
return f"Error generating artwork: {str(e)}"
# Function to deploy an ERC-721 NFT contract
def deploy_nft(name, symbol, base_uri):
"""
Deploy an ERC-721 NFT contract.
Args:
name (str): Name of the NFT collection
symbol (str): Symbol of the NFT collection
base_uri (str): Base URI for token metadata
Returns:
str: Status message about the NFT deployment, including the contract address
"""
try:
deployed_nft = agent_wallet.deploy_nft(name, symbol, base_uri)
deployed_nft.wait()
contract_address = deployed_nft.contract_address
return f"Successfully deployed NFT contract '{name}' ({symbol}) at address {contract_address} with base URI: {base_uri}. "
except Exception as e:
return f"Error deploying NFT contract: {str(e)}"
# Function to mint an NFT
def mint_nft(contract_address, mint_to):
"""
Mint an NFT to a specified address.
Args:
contract_address (str): Address of the NFT contract
mint_to (str): Address to mint NFT to
Returns:
str: Status message about the NFT minting
"""
try:
mint_args = {"to": mint_to, "quantity": "1"}
mint_invocation = agent_wallet.invoke_contract(
contract_address=contract_address, method="mint", args=mint_args)
mint_invocation.wait()
transaction_link = mint_invocation.transaction_link
return f"Successfully minted NFT to {mint_to}. Here is the transaction link : {transaction_link}"
except Exception as e:
return f"Error minting NFT: {str(e)}"
# Function to swap assets (only works on Base Mainnet)
def swap_assets(amount: Union[int, float, Decimal], from_asset_id: str,
to_asset_id: str):
"""
Swap one asset for another using the trade function.
This function only works on Base Mainnet.
Args:
amount (Union[int, float, Decimal]): Amount of the source asset to swap
from_asset_id (str): Source asset identifier
to_asset_id (str): Destination asset identifier
Returns:
str: Status message about the swap
"""
if agent_wallet.network_id != "base-mainnet":
return "Error: Asset swaps are only available on Base Mainnet. Current network is not Base Mainnet."
try:
trade = agent_wallet.trade(amount, from_asset_id, to_asset_id)
trade.wait()
return f"Successfully swapped {amount} {from_asset_id} for {to_asset_id}"
except Exception as e:
return f"Error swapping assets: {str(e)}"
# Contract addresses for Basenames
BASENAMES_REGISTRAR_CONTROLLER_ADDRESS_MAINNET = "0x4cCb0BB02FCABA27e82a56646E81d8c5bC4119a5"
BASENAMES_REGISTRAR_CONTROLLER_ADDRESS_TESTNET = "0x49aE3cC2e3AA768B1e5654f5D3C6002144A59581"
L2_RESOLVER_ADDRESS_MAINNET = "0xC6d566A56A1aFf6508b41f6c90ff131615583BCD"
L2_RESOLVER_ADDRESS_TESTNET = "0x6533C94869D28fAA8dF77cc63f9e2b2D6Cf77eBA"
# Function to create registration arguments for Basenames
def create_register_contract_method_args(base_name: str, address_id: str,
is_mainnet: bool) -> dict:
"""
Create registration arguments for Basenames.
Args:
base_name (str): The Basename (e.g., "example.base.eth" or "example.basetest.eth")
address_id (str): The Ethereum address
is_mainnet (bool): True if on mainnet, False if on testnet
Returns:
dict: Formatted arguments for the register contract method
"""
w3 = Web3()
resolver_contract = w3.eth.contract(abi=l2_resolver_abi)
name_hash = w3.ens.namehash(base_name)
address_data = resolver_contract.encode_abi("setAddr",
args=[name_hash, address_id])
name_data = resolver_contract.encode_abi("setName",
args=[name_hash, base_name])
register_args = {
"request": [
base_name.replace(".base.eth" if is_mainnet else ".basetest.eth",
""),
address_id,
"31557600", # 1 year in seconds
L2_RESOLVER_ADDRESS_MAINNET
if is_mainnet else L2_RESOLVER_ADDRESS_TESTNET,
[address_data, name_data],
True
]
}
return register_args
# Function to register a basename
def register_basename(basename: str, amount: float = 0.002):
"""
Register a basename for the agent's wallet.
Args:
basename (str): The basename to register (e.g. "myname.base.eth" or "myname.basetest.eth")
amount (float): Amount of ETH to pay for registration (default 0.002)
Returns:
str: Status message about the basename registration
"""
address_id = agent_wallet.default_address.address_id
is_mainnet = agent_wallet.network_id == "base-mainnet"
suffix = ".base.eth" if is_mainnet else ".basetest.eth"
if not basename.endswith(suffix):
basename += suffix
register_args = create_register_contract_method_args(
basename, address_id, is_mainnet)
try:
contract_address = (BASENAMES_REGISTRAR_CONTROLLER_ADDRESS_MAINNET
if is_mainnet else
BASENAMES_REGISTRAR_CONTROLLER_ADDRESS_TESTNET)
invocation = agent_wallet.invoke_contract(
contract_address=contract_address,
method="register",
args=register_args,
abi=registrar_abi,
amount=amount,
asset_id="eth",
)
invocation.wait()
return f"Successfully registered basename {basename} for address {address_id}"
except ContractLogicError as e:
return f"Error registering basename: {str(e)}"
except Exception as e:
return f"Unexpected error registering basename: {str(e)}"
def search_duckduckgo(query):
"""
Search DuckDuckGo for the latest news on a given topic.
Args:
query (str): The search query
Returns:
str: A message with the search results
"""
results = DDGS().text(query, max_results=5)
return results
def ask_researcher(query):
return research_agent
def revert_to_asker(query):
return chainpilot_agent
def current_datetime():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def bye():
exit()
research_agent = Agent(
name="Research Agent",
instructions=
f"YOU SHOULD ALWAYS REVERT TO ASKER WITH `revert_to_asker` call. DO NOT ASK ANY QUESTIONS. Today's date: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}. You are a cyrpto and blockchain research agent, your task is to do market research about the query and revert to asked with the suggestions. You have access to Duckduckgo search engine. You can query it what ever news, information you want.",
functions=[
search_duckduckgo,
revert_to_asker,
current_datetime,
bye,
],
)
# Create the Chainpilot Agent with all available functions
chainpilot_agent = Agent(
name="Chainpilot Agent",
instructions=
f"Today's date: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}. You are a helpful agent that can interact onchain on the Base Layer 2 using the Coinbase Developer Platform SDK. You can create tokens, transfer assets, generate art, deploy NFTs, mint NFTs, register basenames, and swap assets (on mainnet only). If you ever need to know your address, it is {agent_wallet.default_address.address_id}. If you ever need funds, you can request them from the faucet. You can also deploy your own ERC-20 tokens, NFTs, and interact with them. If someone asks you to do something you can't do, you can say so, and encourage them to implement it themselves using the CDP SDK, recommend they go to docs.cdp.coinbase.com for more informaton. You can also offer to help them implement it by writing the function and telling them to add it to the agents.py file and within your list of callable functions. You can ask a researcher about any kind of market information or news you might need.",
functions=[
create_token,
generate_art,
transfer_asset,
get_balance,
request_eth_from_faucet,
deploy_nft,
mint_nft,
swap_assets,
register_basename,
ask_researcher,
current_datetime,
bye
],
)
l2_resolver_abi = [{
"inputs": [{
"internalType": "bytes32",
"name": "node",
"type": "bytes32"
}, {
"internalType": "address",
"name": "a",
"type": "address"
}],
"name":
"setAddr",
"outputs": [],
"stateMutability":
"nonpayable",
"type":
"function"
}, {
"inputs": [{
"internalType": "bytes32",
"name": "node",
"type": "bytes32"
}, {
"internalType": "string",
"name": "newName",
"type": "string"
}],
"name":
"setName",
"outputs": [],
"stateMutability":
"nonpayable",
"type":
"function"
}]
registrar_abi = [{
"inputs": [{
"components": [{
"internalType": "string",
"name": "name",
"type": "string"
}, {
"internalType": "address",
"name": "owner",
"type": "address"
}, {
"internalType": "uint256",
"name": "duration",
"type": "uint256"
}, {
"internalType": "address",
"name": "resolver",
"type": "address"
}, {
"internalType": "bytes[]",
"name": "data",
"type": "bytes[]"
}, {
"internalType": "bool",
"name": "reverseRecord",
"type": "bool"
}],
"internalType":
"struct RegistrarController.RegisterRequest",
"name":
"request",
"type":
"tuple"
}],
"name":
"register",
"outputs": [],
"stateMutability":
"payable",
"type":
"function"
}]