Elffuss BraidHub

kikocis/Based-Agent public

96fe88dcefb1 · 6.7 KiBRawPermalink
1import json
2from swarm import Agent
3from cdp import *
4from typing import List, Dict, Any
5import os
6from openai import OpenAI
7from decimal import Decimal
8from typing import Union
9
10# Configure the CDP SDK
11Cdp.configure_from_json("./examples/based_agent/cdp_api_key.json")
12
13# If you want to create a wallet on Base Mainnet, use Wallet.create(network_id="base-mainnet") and comment out the faucet line
14agent_wallet = Wallet.create()
15faucet = agent_wallet.faucet()
16print(f"Faucet transaction: {faucet}")
17print(f"Agent wallet address: {agent_wallet.default_address.address_id}")
18
19
20
21def create_token(name, symbol, initial_supply):
22 """Create a new ERC-20 token."""
23 deployed_contract = agent_wallet.deploy_token(name, symbol, initial_supply)
24 deployed_contract.wait()
25 return f"Token {name} ({symbol}) created with initial supply of {initial_supply} and contract address {deployed_contract.contract_address}"
26
27def transfer_asset(amount, asset_id, destination_address):
28 """Transfer an asset to a specific address.
29
30 Args:
31 amount: Amount to transfer
32 asset_id: Asset identifier ("eth", "usdc" are the only supported values) or contract address of another ERC-20 token. Unless the asset is ETH or USDC, you must use the contract address of the token.
33 destination_address: Recipient's address
34 """
35 transfer = agent_wallet.transfer(amount, asset_id, destination_address)
36 transfer.wait()
37 return f"Transferred {amount} {asset_id} to {destination_address}"
38
39def get_balance(asset_id):
40 """Get the balance of a specific asset in the agent's wallet.
41
42 Args:
43 asset_id: Asset identifier ("eth", "usdc" are the only supported values) or contract address of another ERC-20 token. If you're unsure, use the contract address of the token.
44
45 Returns:
46 Current balance of the specified asset
47 """
48 balance = agent_wallet.balance(asset_id)
49 return f"Current balance of {asset_id}: {balance}"
50
51
52def request_eth_from_faucet():
53 """Request ETH from the Base Sepolia testnet faucet.
54
55 Returns:
56 Status message about the faucet request
57 """
58 faucet_tx = agent_wallet.faucet()
59 return f"Requested ETH from faucet. Transaction: {faucet_tx}"
60
61
62def generate_art(prompt):
63 """Generate art using DALL-E based on a text prompt.
64
65 Args:
66 prompt: Text description of the desired artwork
67
68 Returns:
69 Status message about the art generation
70 """
71 try:
72 # Note: This requires OpenAI API key to be configured separately
73 client = OpenAI()
74
75 response = client.images.generate(
76 model="dall-e-3",
77 prompt=prompt,
78 size="1024x1024",
79 quality="standard",
80 n=1,
81 )
82
83 image_url = response.data[0].url
84 return f"Generated artwork available at: {image_url}"
85
86 except Exception as e:
87 return f"Error generating artwork: {str(e)}"
88
89
90def deploy_nft(name, symbol, base_uri):
91 """Deploy an ERC-721 NFT contract.
92
93 Args:
94 name: Name of the NFT collection
95 symbol: Symbol of the NFT collection
96 base_uri: Base URI for token metadata
97
98 Returns:
99 Status message about the NFT deployment
100 """
101 try:
102 # Deploy the NFT contract
103 deployed_nft = agent_wallet.deploy_nft(name, symbol, base_uri)
104 deployed_nft.wait()
105 contract_address = deployed_nft.contract_address
106
107 return f"Successfully deployed NFT contract '{name}' ({symbol}) at address {contract_address} with base URI: {base_uri}"
108
109 except Exception as e:
110 return f"Error deploying NFT contract: {str(e)}"
111
112def mint_nft(contract_address, mint_to):
113 """Mint an NFT to a specified address.
114
115 Args:
116 contract_address: Address of the NFT contract
117 mint_to: Address to mint NFT to
118
119 Returns:
120 Status message about the NFT minting
121 """
122 try:
123 # Call mint function on the NFT contract
124 mint_args = {
125 "to": mint_to,
126 "quantity": "1" # Changed to string to match working example
127 }
128
129 mint_invocation = agent_wallet.invoke_contract(
130 contract_address=contract_address,
131 method="mint",
132 args=mint_args
133 )
134 mint_invocation.wait()
135
136 return f"Successfully minted NFT to {mint_to}"
137
138 except Exception as e:
139 return f"Error minting NFT: {str(e)}"
140
141def swap_assets(amount: Union[int, float, Decimal], from_asset_id: str, to_asset_id: str):
142 """
143 Swap one asset for another using the trade function.
144 This function only works on Base Mainnet.
145
146 Args:
147 amount: Amount of the source asset to swap
148 from_asset_id: Source asset identifier ("eth", "usdc" are the only supported values) or contract address of another ERC-20 token. Unless the asset is ETH or USDC, you must use the contract address of the token.
149 to_asset_id: Destination asset identifier ("eth", "usdc" are the only supported values) or contract address of another ERC-20 token. Unless the asset is ETH or USDC, you must use the contract address of the token.
150
151 Returns:
152 Status message about the swap
153 """
154 if agent_wallet.network_id != "base-mainnet":
155 return "Error: Asset swaps are only available on Base Mainnet. Current network is not Base Mainnet."
156
157 try:
158 trade = agent_wallet.trade(amount, from_asset_id, to_asset_id)
159 trade.wait()
160 return f"Successfully swapped {amount} {from_asset_id} for {to_asset_id}"
161 except Exception as e:
162 return f"Error swapping assets: {str(e)}"
163
164# Add the new functions to the based_agent
165based_agent = Agent(
166 name="Based Agent",
167 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, 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.",
168 functions=[
169 create_token,
170 transfer_asset,
171 get_balance,
172 request_eth_from_faucet,
173 #generate_art,
174 deploy_nft,
175 mint_nft,
176 swap_assets, # Add the new function here
177 ],
178)