Elffuss BraidHub

kikocis/Based-Agent public

8add4bde3316 · 12.0 KiBRawPermalink
1import json
2from swarm import Agent
3from cdp import *
4from typing import List, Dict, Any
5import os
6from openai import OpenAI
7
8# Configure the CDP SDK
9Cdp.configure_from_json("./examples/based_agent/cdp_api_key.json")
10
11agent_wallet = Wallet.create()
12faucet = agent_wallet.faucet()
13print(f"Faucet transaction: {faucet}")
14print(f"Agent wallet address: {agent_wallet.default_address.address_id}")
15
16
17
18def create_token(name, symbol, initial_supply):
19 """Create a new ERC-20 token."""
20 deployed_contract = agent_wallet.deploy_token(name, symbol, initial_supply)
21 deployed_contract.wait()
22 return f"Token {name} ({symbol}) created with initial supply of {initial_supply}"
23
24def transfer_asset(amount, asset_id, destination_address):
25 """Transfer an asset to a specific address.
26
27 Args:
28 amount: Amount to transfer
29 asset_id: Asset identifier (e.g. "eth", "usdc")
30 destination_address: Recipient's address
31 """
32 transfer = agent_wallet.transfer(amount, asset_id, destination_address)
33 transfer.wait()
34 return f"Transferred {amount} {asset_id} to {destination_address}"
35
36def get_balance(asset_id):
37 """Get the balance of a specific asset in the agent's wallet.
38
39 Args:
40 asset_id: Asset identifier (e.g. "eth", "usdc") or contract address
41
42 Returns:
43 Current balance of the specified asset
44 """
45 balance = agent_wallet.balance(asset_id)
46 return f"Current balance of {asset_id}: {balance}"
47
48
49def request_eth_from_faucet():
50 """Request ETH from the Base Sepolia testnet faucet.
51
52 Returns:
53 Status message about the faucet request
54 """
55 faucet_tx = agent_wallet.faucet()
56 return f"Requested ETH from faucet. Transaction: {faucet_tx}"
57
58
59def generate_art(prompt):
60 """Generate art using DALL-E based on a text prompt.
61
62 Args:
63 prompt: Text description of the desired artwork
64
65 Returns:
66 Status message about the art generation
67 """
68 try:
69 # Note: This requires OpenAI API key to be configured separately
70 client = OpenAI()
71
72 response = client.images.generate(
73 model="dall-e-3",
74 prompt=prompt,
75 size="1024x1024",
76 quality="standard",
77 n=1,
78 )
79
80 image_url = response.data[0].url
81 return f"Generated artwork available at: {image_url}"
82
83 except Exception as e:
84 return f"Error generating artwork: {str(e)}"
85
86
87def deploy_nft(name, symbol, base_uri):
88 """Deploy an ERC-721 NFT contract.
89
90 Args:
91 name: Name of the NFT collection
92 symbol: Symbol of the NFT collection
93 base_uri: Base URI for token metadata
94
95 Returns:
96 Status message about the NFT deployment
97 """
98 try:
99 # Deploy the NFT contract
100 deployed_nft = agent_wallet.deploy_nft(name, symbol, base_uri)
101 deployed_nft.wait()
102 contract_address = deployed_nft.contract_address
103
104 return f"Successfully deployed NFT contract '{name}' ({symbol}) at address {contract_address} with base URI: {base_uri}"
105
106 except Exception as e:
107 return f"Error deploying NFT contract: {str(e)}"
108
109def mint_nft(contract_address, mint_to):
110 """Mint an NFT to a specified address.
111
112 Args:
113 contract_address: Address of the NFT contract
114 mint_to: Address to mint NFT to
115
116 Returns:
117 Status message about the NFT minting
118 """
119 try:
120 # Call mint function on the NFT contract
121 mint_args = {
122 "to": mint_to,
123 "quantity": "1" # Changed to string to match working example
124 }
125
126 mint_invocation = agent_wallet.invoke_contract(
127 contract_address=contract_address,
128 method="mint",
129 args=mint_args
130 )
131 mint_invocation.wait()
132
133 return f"Successfully minted NFT to {mint_to}"
134
135 except Exception as e:
136 return f"Error minting NFT: {str(e)}"
137
138# Add the new functions to the based_agent
139based_agent = Agent(
140 name="Based Agent",
141 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, and mint NFTs. 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.",
142 functions=[
143 create_token,
144 transfer_asset,
145 get_balance,
146 request_eth_from_faucet,
147 generate_art,
148 deploy_nft,
149 mint_nft,
150 ],
151)
152
153
154
155
156
157
158
159
160
161
162
163
164# TODO - implement this properly, need a way to encode the function data for the setAddr and setName functions
165
166
167# Base Sepolia contract addresses
168REGISTRAR_ADDRESS = "0x4cCb0BB02FCABA27e82a56646E81d8c5bC4119a5"
169RESOLVER_ADDRESS = "0xC6d566A56A1aFf6508b41f6c90ff131615583BCD"
170
171REGISTRAR_ABI = [
172 {
173 "inputs": [
174 {
175 "components": [
176 {"internalType": "string", "name": "name", "type": "string"},
177 {"internalType": "address", "name": "owner", "type": "address"},
178 {"internalType": "uint256", "name": "duration", "type": "uint256"},
179 {"internalType": "address", "name": "resolver", "type": "address"},
180 {"internalType": "bytes[]", "name": "data", "type": "bytes[]"},
181 {"internalType": "bool", "name": "reverseRecord", "type": "bool"}
182 ],
183 "internalType": "struct RegistrarController.RegisterRequest",
184 "name": "request",
185 "type": "tuple"
186 }
187 ],
188 "name": "register",
189 "outputs": [],
190 "stateMutability": "payable",
191 "type": "function"
192 }
193]
194
195RESOLVER_ABI = [
196 {
197 "inputs": [
198 {"internalType": "bytes32", "name": "node", "type": "bytes32"},
199 {"internalType": "address", "name": "a", "type": "address"}
200 ],
201 "name": "setAddr",
202 "outputs": [],
203 "stateMutability": "nonpayable",
204 "type": "function"
205 },
206 {
207 "inputs": [
208 {"internalType": "bytes32", "name": "node", "type": "bytes32"},
209 {"internalType": "string", "name": "newName", "type": "string"}
210 ],
211 "name": "setName",
212 "outputs": [],
213 "stateMutability": "nonpayable",
214 "type": "function"
215 }
216]
217
218def create_register_contract_method_args(basename: str, address_id: str) -> Dict[str, Any]:
219 # Note: In a real implementation, you'd need to implement namehash and encodeFunctionData
220 # functions similar to the JavaScript version
221 address_data = "0x..." # Placeholder for encoded setAddr function data
222 name_data = "0x..." # Placeholder for encoded setName function data
223
224 return {
225 "request": [
226 basename.replace(".base.eth", ""),
227 address_id,
228 "31557600",
229 RESOLVER_ADDRESS,
230 [address_data, name_data],
231 True
232 ]
233 }
234
235def register_basename(basename: str, amount: float = 0.002):
236 """Register a basename for the agent's wallet.
237
238 Args:
239 basename: The basename to register (e.g. "myname.base.eth")
240 amount: Amount of ETH to pay for registration (default 0.002)
241
242 Returns:
243 Status message about the basename registration
244 """
245 address_id = agent_wallet.default_address.address_id
246
247 register_args = create_register_contract_method_args(basename, address_id)
248
249 try:
250 # Invoke register function on registrar contract
251 invocation = agent_wallet.invoke_contract(
252 contract_address=REGISTRAR_ADDRESS,
253 method="register",
254 args=register_args,
255 abi=REGISTRAR_ABI,
256 value=amount
257 )
258 invocation.wait()
259 return f"Successfully registered basename {basename} for address {address_id}"
260 except Exception as e:
261 return f"Error registering basename: {str(e)}"
262
263
264# TODO - can't deploy liquidity pool until we have arbitrary contract deployment
265def create_liquidity_pool(token0_address: str, token1_address: str, fee_tier: int, amount0: float, amount1: float):
266 """Create a new Uniswap V3 liquidity pool and add initial liquidity.
267
268 Args:
269 token0_address: Address of the first token
270 token1_address: Address of the second token
271 fee_tier: Fee tier (500 = 0.05%, 3000 = 0.3%, 10000 = 1%)
272 amount0: Amount of token0 to provide as liquidity
273 amount1: Amount of token1 to provide as liquidity
274 """
275 try:
276 # Address of the Uniswap V3 NonfungiblePositionManager
277 # https://sepolia.basescan.org/address/0x27F971cb582BF9E50F397e4d29a5C7A34f11faA2#code
278 # https://github.com/Uniswap/v3-periphery/blob/v1.0.0/contracts/NonfungiblePositionManager.sol
279 position_manager_address = "0x27F971cb582BF9E50F397e4d29a5C7A34f11faA2"
280
281 # Parameters for creating the position
282 params = {
283 "token0": token0_address,
284 "token1": token1_address,
285 "fee": str(fee_tier),
286 "tickLower": "-887272", # Represents price range lower bound
287 "tickUpper": "887272", # Represents price range upper bound
288 "amount0Desired": str(amount0),
289 "amount1Desired": str(amount1),
290 "amount0Min": "0", # Minimum amount of token0 to provide
291 "amount1Min": "0", # Minimum amount of token1 to provide
292 "recipient": agent_wallet.default_address.address_id,
293 "deadline": "999999999999999" # Far future deadline
294 }
295
296 # Create the position through contract invocation
297 mint_position = agent_wallet.invoke_contract(
298 contract_address=position_manager_address,
299 method="mint",
300 args=params
301 )
302 mint_position.wait()
303
304 return f"Successfully created liquidity pool for {token0_address}/{token1_address} with {amount0} and {amount1} tokens"
305
306 except Exception as e:
307 return f"Error creating liquidity pool: {str(e)}"
308
309def increase_liquidity(token_id: int, amount0: float, amount1: float):
310 """Increase liquidity for an existing position.
311
312 Args:
313 token_id: ID of the NFT position token
314 amount0: Additional amount of token0 to provide
315 amount1: Additional amount of token1 to provide
316 """
317 try:
318 position_manager_address = "0xC36442b4a4522E871399CD717aBDD847Ab11FE88"
319
320 params = {
321 "tokenId": str(token_id),
322 "amount0Desired": str(amount0),
323 "amount1Desired": str(amount1),
324 "amount0Min": "0",
325 "amount1Min": "0",
326 "deadline": "999999999999999"
327 }
328
329 increase_position = agent_wallet.invoke_contract(
330 contract_address=position_manager_address,
331 method="increaseLiquidity",
332 args=params
333 )
334 increase_position.wait()
335
336 return f"Successfully increased liquidity for position {token_id}"
337
338 except Exception as e:
339 return f"Error increasing liquidity: {str(e)}"
340
341def collect_fees(token_id: int):
342 """Collect accumulated fees for a position.
343
344 Args:
345 token_id: ID of the NFT position token
346 """
347 try:
348 position_manager_address = "0xC36442b4a4522E871399CD717aBDD847Ab11FE88"
349
350 params = {
351 "tokenId": str(token_id),
352 "recipient": agent_wallet.default_address.address_id,
353 "amount0Max": "340282366920938463463374607431768211455", # uint128 max
354 "amount1Max": "340282366920938463463374607431768211455" # uint128 max
355 }
356
357 collect_tx = agent_wallet.invoke_contract(
358 contract_address=position_manager_address,
359 method="collect",
360 args=params
361 )
362 collect_tx.wait()
363
364 return f"Successfully collected fees for position {token_id}"
365
366 except Exception as e:
367 return f"Error collecting fees: {str(e)}"