0
# Account Management
1
2
Comprehensive account management system for handling private keys, external signers, and transaction broadcasting with gas optimization and error handling capabilities.
3
4
## Capabilities
5
6
### Account Container
7
8
The global accounts container manages multiple account types and provides unified access to local accounts, hardware wallets, and external signers.
9
10
```python { .api }
11
class Accounts:
12
"""
13
Container for managing multiple accounts.
14
15
Available as global singleton 'accounts' after importing brownie.
16
"""
17
def __len__(self) -> int:
18
"""Return number of available accounts."""
19
20
def __getitem__(self, index: int) -> LocalAccount:
21
"""Get account by index."""
22
23
def __iter__(self):
24
"""Iterate over available accounts."""
25
26
def add(self, private_key: str) -> LocalAccount:
27
"""
28
Add account from private key.
29
30
Args:
31
private_key: Hexadecimal private key string
32
33
Returns:
34
LocalAccount instance for the added account
35
"""
36
37
def load(self, filename: str, password: str = None) -> LocalAccount:
38
"""
39
Load encrypted account from file.
40
41
Args:
42
filename: Path to encrypted account file
43
password: Password to decrypt the account
44
45
Returns:
46
LocalAccount instance for the loaded account
47
"""
48
49
def new(self, password: str = None) -> LocalAccount:
50
"""
51
Generate new random account.
52
53
Args:
54
password: Optional password to encrypt the account
55
56
Returns:
57
LocalAccount instance for the new account
58
"""
59
60
def clear(self) -> None:
61
"""Remove all accounts from the container."""
62
63
def default(self) -> LocalAccount:
64
"""Get the default account (accounts[0])."""
65
```
66
67
### Local Account
68
69
Local accounts handle private key management and transaction signing with comprehensive transaction options and gas management.
70
71
```python { .api }
72
class LocalAccount:
73
"""
74
Account with local private key for signing transactions.
75
76
Attributes:
77
address (str): Account's Ethereum address
78
private_key (str): Account's private key (read-only)
79
nonce (int): Current account nonce
80
"""
81
82
def __init__(self, address: str, private_key: str):
83
"""Initialize local account with address and private key."""
84
85
def balance(self) -> Wei:
86
"""
87
Get account balance in wei.
88
89
Returns:
90
Wei: Current account balance
91
"""
92
93
def transfer(
94
self,
95
to: str,
96
amount: Union[int, str, Wei],
97
gas_limit: int = None,
98
gas_price: int = None,
99
max_fee: int = None,
100
priority_fee: int = None,
101
nonce: int = None,
102
required_confs: int = 1,
103
allow_revert: bool = False,
104
silent: bool = False
105
) -> TransactionReceipt:
106
"""
107
Transfer ether to another account.
108
109
Args:
110
to: Recipient address
111
amount: Amount to transfer (in wei or string with units)
112
gas_limit: Gas limit for transaction
113
gas_price: Gas price (legacy transactions)
114
max_fee: Maximum fee per gas (EIP-1559)
115
priority_fee: Priority fee per gas (EIP-1559)
116
nonce: Transaction nonce (auto if None)
117
required_confs: Required confirmations
118
allow_revert: Allow reverted transactions
119
silent: Suppress console output
120
121
Returns:
122
TransactionReceipt: Transaction receipt
123
"""
124
125
def deploy(
126
self,
127
contract,
128
*args,
129
amount: Union[int, str, Wei] = 0,
130
gas_limit: int = None,
131
gas_price: int = None,
132
max_fee: int = None,
133
priority_fee: int = None,
134
nonce: int = None,
135
required_confs: int = 1,
136
allow_revert: bool = False,
137
silent: bool = False,
138
publish_source: bool = False
139
) -> Contract:
140
"""
141
Deploy a contract.
142
143
Args:
144
contract: Contract class or container to deploy
145
*args: Constructor arguments
146
amount: Ether to send with deployment
147
gas_limit: Gas limit for deployment
148
gas_price: Gas price (legacy transactions)
149
max_fee: Maximum fee per gas (EIP-1559)
150
priority_fee: Priority fee per gas (EIP-1559)
151
nonce: Transaction nonce (auto if None)
152
required_confs: Required confirmations
153
allow_revert: Allow reverted deployments
154
silent: Suppress console output
155
publish_source: Publish source to block explorer
156
157
Returns:
158
Contract: Deployed contract instance
159
"""
160
161
def estimate_gas(
162
self,
163
to: str,
164
amount: Union[int, str, Wei] = 0,
165
data: str = "0x"
166
) -> int:
167
"""
168
Estimate gas for a transaction.
169
170
Args:
171
to: Transaction recipient
172
amount: Ether amount to send
173
data: Transaction data
174
175
Returns:
176
int: Estimated gas amount
177
"""
178
179
def get_deployment_address(self, nonce: int = None) -> str:
180
"""
181
Calculate contract deployment address.
182
183
Args:
184
nonce: Nonce to use for calculation (current if None)
185
186
Returns:
187
str: Predicted deployment address
188
"""
189
```
190
191
### External Signers
192
193
Support for external signing services and hardware wallets through standardized interfaces.
194
195
```python { .api }
196
class ClefAccount:
197
"""
198
Account using Clef external signer.
199
200
Attributes:
201
address (str): Account's Ethereum address
202
"""
203
204
def __init__(self, address: str):
205
"""Initialize Clef account with address."""
206
207
def transfer(self, to: str, amount: Union[int, str, Wei], **kwargs) -> TransactionReceipt:
208
"""Transfer ether using Clef signer."""
209
210
def deploy(self, contract, *args, **kwargs) -> Contract:
211
"""Deploy contract using Clef signer."""
212
213
class PublicKeyAccount:
214
"""
215
Read-only account (no signing capability).
216
217
Attributes:
218
address (str): Account's Ethereum address
219
"""
220
221
def __init__(self, address: str):
222
"""Initialize public key account with address."""
223
224
def balance(self) -> Wei:
225
"""Get account balance."""
226
```
227
228
### Transaction Management
229
230
```python { .api }
231
class TransactionReceipt:
232
"""
233
Transaction receipt with events, logs, and execution details.
234
235
Attributes:
236
txid (str): Transaction hash
237
sender (str): Transaction sender address
238
receiver (str): Transaction receiver address
239
value (Wei): Ether amount transferred
240
gas_limit (int): Gas limit set for transaction
241
gas_used (int): Actual gas consumed
242
gas_price (int): Gas price paid per unit
243
nonce (int): Transaction nonce
244
block_number (int): Block number where transaction was mined
245
timestamp (int): Block timestamp
246
status (int): Transaction status (1=success, 0=failure)
247
events (dict): Decoded event logs
248
logs (list): Raw event logs
249
return_value: Return value from contract call
250
revert_msg (str): Revert message if transaction failed
251
"""
252
253
def __init__(self, txid: str):
254
"""Initialize transaction receipt."""
255
256
def call_trace(self) -> list:
257
"""Get detailed call trace for debugging."""
258
259
def traceback(self) -> None:
260
"""Print formatted traceback for failed transactions."""
261
262
def info(self) -> None:
263
"""Print formatted transaction information."""
264
265
def wait(self, required_confs: int = 1, timeout: int = None) -> 'TransactionReceipt':
266
"""
267
Wait for transaction confirmation.
268
269
Args:
270
required_confs: Number of confirmations to wait for
271
timeout: Timeout in seconds
272
273
Returns:
274
TransactionReceipt: Self after confirmation
275
"""
276
```
277
278
## Usage Examples
279
280
### Basic Account Operations
281
282
```python
283
from brownie import accounts, network
284
285
# Connect to network
286
network.connect('development')
287
288
# Access local development accounts
289
account = accounts[0]
290
print(f"Account address: {account.address}")
291
print(f"Account balance: {account.balance()}")
292
293
# Add account from private key
294
new_account = accounts.add('0x416b8a7d9290502f5661da81f0cf43893e3d19cb9aea3c426cfb36e8186e9c09')
295
296
# Generate new random account
297
random_account = accounts.new()
298
```
299
300
### Ether Transfers
301
302
```python
303
from brownie import accounts, Wei
304
305
account1 = accounts[0]
306
account2 = accounts[1]
307
308
# Transfer 1 ether
309
tx = account1.transfer(account2, "1 ether")
310
print(f"Transaction hash: {tx.txid}")
311
print(f"Gas used: {tx.gas_used}")
312
313
# Transfer with specific gas settings
314
tx = account1.transfer(
315
account2,
316
Wei("0.5 ether"),
317
gas_limit=21000,
318
gas_price="20 gwei"
319
)
320
321
# EIP-1559 transaction
322
tx = account1.transfer(
323
account2,
324
Wei("0.1 ether"),
325
max_fee="30 gwei",
326
priority_fee="2 gwei"
327
)
328
```
329
330
### Contract Deployment
331
332
```python
333
from brownie import accounts, project
334
335
# Load project and get account
336
p = project.load()
337
account = accounts[0]
338
339
# Deploy contract with constructor arguments
340
contract = account.deploy(p.MyContract, "constructor_arg", 42)
341
342
# Deploy with ether and custom gas
343
contract = account.deploy(
344
p.MyContract,
345
amount="1 ether",
346
gas_limit=3000000,
347
publish_source=True
348
)
349
```
350
351
### Error Handling
352
353
```python
354
from brownie import accounts, reverts
355
356
account = accounts[0]
357
358
# Handle transaction failures
359
try:
360
tx = account.transfer("invalid_address", "1 ether")
361
except ValueError as e:
362
print(f"Transaction failed: {e}")
363
364
# Allow reverted transactions
365
tx = account.transfer(
366
some_contract_address,
367
"1 ether",
368
allow_revert=True
369
)
370
371
if tx.status == 0:
372
print(f"Transaction reverted: {tx.revert_msg}")
373
tx.traceback() # Print detailed error trace
374
```
375
376
## Type Definitions
377
378
```python { .api }
379
# Type aliases for account-related operations
380
AccountType = Union[LocalAccount, ClefAccount, PublicKeyAccount]
381
TxParams = Dict[str, Union[int, str, bool]]
382
GasStrategy = Union[str, dict, Callable]
383
```