-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagents.py
521 lines (437 loc) · 18.1 KB
/
agents.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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
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
# Configure the CDP SDK
# This loads the API key from a JSON file. Make sure this file exists and contains valid credentials.
Cdp.configure_from_json("./cdp_api_key.json")
# Create a new wallet on the Base Sepolia testnet
# You could make this a function for the agent to create a wallet on any network
# If you want to use Base Mainnet, change Wallet.create() to Wallet.create(network_id="base-mainnet")
# see https://docs.cdp.coinbase.com/mpc-wallet/docs/wallets for more information
agent_wallet = Wallet.create()
# NOTE: the wallet is not currently persisted, meaning that it will be deleted after the agent is stopped. To persist the wallet, see https://docs.cdp.coinbase.com/mpc-wallet/docs/wallets#developer-managed-wallets
# Here's an example of how to persist the wallet:
# WARNING: This is for development only - implement secure storage in production!
# # Export wallet data (contains seed and wallet ID)
# wallet_data = agent_wallet.export_data()
# wallet_dict = wallet_data.to_dict()
# # Example of saving to encrypted local file
# file_path = "wallet_seed.json"
# agent_wallet.save_seed(file_path, encrypt=True)
# print(f"Seed for wallet {agent_wallet.id} saved to {file_path}")
# # Example of loading a saved wallet:
# # 1. Fetch the wallet by ID
# fetched_wallet = Wallet.fetch(wallet_id)
# # 2. Load the saved seed
# fetched_wallet.load_seed("wallet_seed.json")
# Example of importing previously exported wallet data:
# imported_wallet = Wallet.import_data(wallet_dict)
# Request funds from the faucet (only works on testnet)
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()
return f"Token {name} ({symbol}) created with initial supply of {initial_supply} and contract address {deployed_contract.contract_address}"
# 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
"""
try:
balance = agent_wallet.balance(asset_id)
return f"Current balance of {asset_id}: {balance}"
except Exception as e:
return f"Error fetching balance for {asset_id}: {str(e)}"
# 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()
return f"Successfully minted NFT to {mint_to}"
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
"""
try:
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
except Exception as e:
raise ValueError(f"Error creating registration arguments for {base_name}: {str(e)}")
# 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
"""
try:
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)
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 ValueError as e:
return str(e)
except Exception as e:
return f"Unexpected error registering basename: {str(e)}"
# Create the Based Agent with all available functions
based_agent = Agent(
name="Based Agent",
instructions="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.",
functions=[
create_token,
transfer_asset,
get_balance,
request_eth_from_faucet,
#generate_art, # Uncomment this line if you have configured the OpenAI API
deploy_nft,
mint_nft,
swap_assets,
register_basename
],
)
# add the following import to the top of the file, add the code below it, and add the new functions to the based_agent.functions list
# from twitter_utils import TwitterBot
# # Initialize TwitterBot with your credentials
# twitter_bot = TwitterBot(
# api_key="your_api_key",
# api_secret="your_api_secret",
# access_token="your_access_token",
# access_token_secret="your_access_token_secret"
# )
# # Add these new functions to your existing functions list
# def post_to_twitter(content: str):
# """
# Post a message to Twitter.
#
# Args:
# content (str): The content to tweet
#
# Returns:
# str: Status message about the tweet
# """
# return twitter_bot.post_tweet(content)
# def check_twitter_mentions():
# """
# Check recent Twitter mentions.
#
# Returns:
# str: Formatted string of recent mentions
# """
# mentions = twitter_bot.read_mentions()
# if not mentions:
# return "No recent mentions found"
# result = "Recent mentions:\n"
# for mention in mentions:
# if 'error' in mention:
# return f"Error checking mentions: {mention['error']}"
# result += f"- @{mention['user']}: {mention['text']}\n"
# return result
# def reply_to_twitter_mention(tweet_id: str, content: str):
# """
# Reply to a specific tweet.
#
# Args:
# tweet_id (str): ID of the tweet to reply to
# content (str): Content of the reply
#
# Returns:
# str: Status message about the reply
# """
# return twitter_bot.reply_to_tweet(tweet_id, content)
# def search_twitter(query: str):
# """
# Search for tweets matching a query.
#
# Args:
# query (str): Search query
#
# Returns:
# str: Formatted string of matching tweets
# """
# tweets = twitter_bot.search_tweets(query)
# if not tweets:
# return f"No tweets found matching query: {query}"
# result = f"Tweets matching '{query}':\n"
# for tweet in tweets:
# if 'error' in tweet:
# return f"Error searching tweets: {tweet['error']}"
# result += f"- @{tweet['user']}: {tweet['text']}\n"
# return result
# ABIs for smart contracts (used in basename registration)
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"
}
]
# To add a new function:
# 1. Define your function above (follow the existing pattern)
# 2. Add appropriate error handling
# 3. Add the function to the based_agent's functions list
# 4. If your function requires new imports or global variables, add them at the top of the file
# 5. Test your new function thoroughly before deploying
# Example of adding a new function:
# def my_new_function(param1, param2):
# """
# Description of what this function does.
#
# Args:
# param1 (type): Description of param1
# param2 (type): Description of param2
#
# Returns:
# type: Description of what is returned
# """
# try:
# # Your function logic here
# result = do_something(param1, param2)
# return f"Operation successful: {result}"
# except Exception as e:
# return f"Error in my_new_function: {str(e)}"
# Then add to based_agent.functions:
# based_agent = Agent(
# ...
# functions=[
# ...
# my_new_function,
# ],
# )