or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

account-management.mdens-operations.mdethereum-operations.mdindex.mdmiddleware.mdproviders.mdsmart-contracts.mdutilities.mdweb3-client.md

account-management.mddocs/

0

# Account Management

1

2

Cryptographic account operations including key generation, transaction signing, message signing, account recovery, and secure key management with support for various key formats.

3

4

## Capabilities

5

6

### Account Creation and Management

7

8

Core account operations for creating and managing Ethereum accounts.

9

10

```python { .api }

11

class Account:

12

@staticmethod

13

def create(extra_entropy: str = '') -> LocalAccount:

14

"""

15

Create new random account.

16

17

Parameters:

18

- extra_entropy: Additional entropy for key generation

19

20

Returns:

21

LocalAccount instance with private key and address

22

"""

23

24

@staticmethod

25

def from_key(private_key: Union[PrivateKey, int, bytes, str]) -> LocalAccount:

26

"""

27

Create account from existing private key.

28

29

Parameters:

30

- private_key: Private key in various formats

31

32

Returns:

33

LocalAccount instance

34

"""

35

36

@staticmethod

37

def from_mnemonic(

38

mnemonic: str,

39

passphrase: str = "",

40

account_path: str = "m/44'/60'/0'/0/0"

41

) -> LocalAccount:

42

"""

43

Create account from BIP39 mnemonic phrase.

44

45

Parameters:

46

- mnemonic: BIP39 mnemonic phrase

47

- passphrase: Optional passphrase

48

- account_path: HD wallet derivation path

49

50

Returns:

51

LocalAccount instance

52

"""

53

54

@staticmethod

55

def recover_message(

56

message: Union[str, bytes],

57

signature: Union[str, bytes, Signature]

58

) -> ChecksumAddress:

59

"""

60

Recover address from signed message.

61

62

Parameters:

63

- message: Original message

64

- signature: Message signature

65

66

Returns:

67

Recovered address

68

"""

69

70

@staticmethod

71

def recover_transaction(serialized_transaction: bytes) -> ChecksumAddress:

72

"""

73

Recover address from signed transaction.

74

75

Parameters:

76

- serialized_transaction: Signed transaction bytes

77

78

Returns:

79

Recovered address

80

"""

81

```

82

83

### Transaction Signing

84

85

Transaction creation and signing operations.

86

87

```python { .api }

88

class Account:

89

@staticmethod

90

def sign_transaction(

91

transaction_dict: Dict[str, Any],

92

private_key: Union[PrivateKey, int, bytes, str]

93

) -> SignedTransaction:

94

"""

95

Sign transaction with private key.

96

97

Parameters:

98

- transaction_dict: Transaction parameters

99

- private_key: Private key for signing

100

101

Returns:

102

SignedTransaction with hash and raw transaction

103

"""

104

105

@staticmethod

106

def create_access_list_transaction(

107

w3: Web3,

108

transaction: Dict[str, Any]

109

) -> AccessListTransaction:

110

"""

111

Create EIP-2930 access list transaction.

112

113

Parameters:

114

- w3: Web3 instance

115

- transaction: Transaction parameters

116

117

Returns:

118

Access list transaction

119

"""

120

121

@staticmethod

122

def create_dynamic_fee_transaction(

123

transaction: Dict[str, Any]

124

) -> DynamicFeeTransaction:

125

"""

126

Create EIP-1559 dynamic fee transaction.

127

128

Parameters:

129

- transaction: Transaction parameters with maxFeePerGas

130

131

Returns:

132

Dynamic fee transaction

133

"""

134

```

135

136

### Message Signing

137

138

Message signing and verification operations.

139

140

```python { .api }

141

class Account:

142

@staticmethod

143

def sign_message(

144

message: Union[str, bytes, EncodableData],

145

private_key: Union[PrivateKey, int, bytes, str]

146

) -> SignedMessage:

147

"""

148

Sign arbitrary message with private key.

149

150

Parameters:

151

- message: Message to sign

152

- private_key: Private key for signing

153

154

Returns:

155

SignedMessage with signature data

156

"""

157

158

@staticmethod

159

def signHash(

160

message_hash: bytes,

161

private_key: Union[PrivateKey, int, bytes, str]

162

) -> SignedMessage:

163

"""

164

Sign message hash directly.

165

166

Parameters:

167

- message_hash: Pre-hashed message

168

- private_key: Private key for signing

169

170

Returns:

171

SignedMessage with signature data

172

"""

173

```

174

175

### Keystore Operations

176

177

Keystore file encryption and decryption.

178

179

```python { .api }

180

class Account:

181

@staticmethod

182

def encrypt(

183

private_key: Union[PrivateKey, int, bytes, str],

184

password: str,

185

kdf: str = "scrypt",

186

iterations: Optional[int] = None

187

) -> Dict[str, Any]:

188

"""

189

Encrypt private key to keystore format.

190

191

Parameters:

192

- private_key: Private key to encrypt

193

- password: Encryption password

194

- kdf: Key derivation function ('scrypt' or 'pbkdf2')

195

- iterations: KDF iterations (None for default)

196

197

Returns:

198

Keystore JSON dictionary

199

"""

200

201

@staticmethod

202

def decrypt(keyfile_json: Dict[str, Any], password: str) -> PrivateKey:

203

"""

204

Decrypt keystore file.

205

206

Parameters:

207

- keyfile_json: Keystore JSON data

208

- password: Decryption password

209

210

Returns:

211

Decrypted private key

212

"""

213

```

214

215

### Local Account

216

217

Local account instance with private key access.

218

219

```python { .api }

220

class LocalAccount:

221

@property

222

def address(self) -> ChecksumAddress:

223

"""Get account address."""

224

225

@property

226

def key(self) -> PrivateKey:

227

"""Get private key."""

228

229

def sign_message(self, message: Union[str, bytes, EncodableData]) -> SignedMessage:

230

"""

231

Sign message with this account's private key.

232

233

Parameters:

234

- message: Message to sign

235

236

Returns:

237

SignedMessage with signature

238

"""

239

240

def sign_transaction(self, transaction_dict: Dict[str, Any]) -> SignedTransaction:

241

"""

242

Sign transaction with this account's private key.

243

244

Parameters:

245

- transaction_dict: Transaction parameters

246

247

Returns:

248

SignedTransaction

249

"""

250

251

def encrypt(self, password: str, kdf: str = "scrypt") -> Dict[str, Any]:

252

"""

253

Encrypt this account to keystore format.

254

255

Parameters:

256

- password: Encryption password

257

- kdf: Key derivation function

258

259

Returns:

260

Keystore JSON dictionary

261

"""

262

```

263

264

## Types

265

266

Account-related type definitions.

267

268

```python { .api }

269

PrivateKey = NewType('PrivateKey', bytes)

270

271

class SignedMessage(NamedTuple):

272

messageHash: Hash32

273

r: int

274

s: int

275

v: int

276

signature: HexBytes

277

278

class SignedTransaction(NamedTuple):

279

rawTransaction: HexBytes

280

hash: Hash32

281

r: int

282

s: int

283

v: int

284

285

class Signature(NamedTuple):

286

v: int

287

r: int

288

s: int

289

290

class AccessListEntry(TypedDict):

291

address: ChecksumAddress

292

storageKeys: List[Hash32]

293

294

class AccessListTransaction(TypedDict):

295

chainId: int

296

nonce: int

297

gasPrice: Wei

298

gas: int

299

to: ChecksumAddress

300

value: Wei

301

data: HexBytes

302

accessList: List[AccessListEntry]

303

304

class DynamicFeeTransaction(TypedDict):

305

chainId: int

306

nonce: int

307

maxFeePerGas: Wei

308

maxPriorityFeePerGas: Wei

309

gas: int

310

to: ChecksumAddress

311

value: Wei

312

data: HexBytes

313

accessList: List[AccessListEntry]

314

```

315

316

## Usage Examples

317

318

### Creating New Accounts

319

320

```python

321

from web3 import Account

322

323

# Create random account

324

account = Account.create()

325

print(f"Address: {account.address}")

326

print(f"Private key: {account.key.hex()}")

327

328

# Create account with extra entropy

329

account = Account.create(extra_entropy="my-extra-randomness")

330

print(f"Secure address: {account.address}")

331

332

# Create account from existing private key

333

private_key = "0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318"

334

account = Account.from_key(private_key)

335

print(f"Restored address: {account.address}")

336

```

337

338

### HD Wallet Support

339

340

```python

341

from web3 import Account

342

343

# Create account from mnemonic

344

mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"

345

account = Account.from_mnemonic(mnemonic)

346

print(f"HD wallet address: {account.address}")

347

348

# Different derivation paths

349

account1 = Account.from_mnemonic(mnemonic, account_path="m/44'/60'/0'/0/0")

350

account2 = Account.from_mnemonic(mnemonic, account_path="m/44'/60'/0'/0/1")

351

print(f"Account 1: {account1.address}")

352

print(f"Account 2: {account2.address}")

353

354

# With passphrase

355

secure_account = Account.from_mnemonic(

356

mnemonic,

357

passphrase="my-secure-passphrase"

358

)

359

print(f"Secured address: {secure_account.address}")

360

```

361

362

### Transaction Signing

363

364

```python

365

from web3 import Web3, Account

366

367

w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))

368

account = Account.create()

369

370

# Build transaction

371

transaction = {

372

'nonce': w3.eth.get_nonce(account.address),

373

'to': '0x742d35Cc6635C0532925a3b8D5c0d9E3C4B3c8',

374

'value': w3.to_wei(1, 'ether'),

375

'gas': 21000,

376

'gasPrice': w3.to_wei(20, 'gwei'),

377

'chainId': 1

378

}

379

380

# Sign transaction

381

signed_txn = account.sign_transaction(transaction)

382

print(f"Signed transaction hash: {signed_txn.hash.hex()}")

383

print(f"Raw transaction: {signed_txn.rawTransaction.hex()}")

384

385

# Send signed transaction

386

tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)

387

print(f"Transaction hash: {tx_hash.hex()}")

388

```

389

390

### Message Signing and Recovery

391

392

```python

393

from web3 import Account

394

from eth_account.messages import encode_defunct

395

396

account = Account.create()

397

398

# Sign message

399

message = "Hello, Ethereum!"

400

message_encoded = encode_defunct(text=message)

401

signed_message = account.sign_message(message_encoded)

402

403

print(f"Message hash: {signed_message.messageHash.hex()}")

404

print(f"Signature: {signed_message.signature.hex()}")

405

406

# Recover address from signed message

407

recovered_address = Account.recover_message(message_encoded, signed_message.signature)

408

print(f"Original address: {account.address}")

409

print(f"Recovered address: {recovered_address}")

410

print(f"Addresses match: {account.address == recovered_address}")

411

```

412

413

### Keystore Operations

414

415

```python

416

from web3 import Account

417

import json

418

419

account = Account.create()

420

password = "secure-password-123"

421

422

# Encrypt account to keystore

423

keystore = account.encrypt(password)

424

print("Keystore created:")

425

print(json.dumps(keystore, indent=2))

426

427

# Save keystore to file

428

with open('keystore.json', 'w') as f:

429

json.dump(keystore, f)

430

431

# Decrypt keystore

432

with open('keystore.json', 'r') as f:

433

keystore_data = json.load(f)

434

435

decrypted_key = Account.decrypt(keystore_data, password)

436

restored_account = Account.from_key(decrypted_key)

437

438

print(f"Original address: {account.address}")

439

print(f"Restored address: {restored_account.address}")

440

print(f"Keys match: {account.key == restored_account.key}")

441

```

442

443

### EIP-1559 Dynamic Fee Transactions

444

445

```python

446

from web3 import Web3, Account

447

448

w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))

449

account = Account.create()

450

451

# EIP-1559 transaction with dynamic fees

452

transaction = {

453

'nonce': w3.eth.get_nonce(account.address),

454

'to': '0x742d35Cc6635C0532925a3b8D5c0d9E3C4B3c8',

455

'value': w3.to_wei(1, 'ether'),

456

'gas': 21000,

457

'maxFeePerGas': w3.to_wei(30, 'gwei'),

458

'maxPriorityFeePerGas': w3.to_wei(2, 'gwei'),

459

'chainId': 1,

460

'type': 2 # EIP-1559

461

}

462

463

signed_txn = account.sign_transaction(transaction)

464

tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)

465

print(f"EIP-1559 transaction hash: {tx_hash.hex()}")

466

```

467

468

### Access List Transactions (EIP-2930)

469

470

```python

471

from web3 import Web3, Account

472

473

w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))

474

account = Account.create()

475

476

# EIP-2930 access list transaction

477

access_list = [

478

{

479

'address': '0x742d35Cc6635C0532925a3b8D5c0d9E3C4B3c8',

480

'storageKeys': [

481

'0x0000000000000000000000000000000000000000000000000000000000000000'

482

]

483

}

484

]

485

486

transaction = {

487

'nonce': w3.eth.get_nonce(account.address),

488

'to': '0x742d35Cc6635C0532925a3b8D5c0d9E3C4B3c8',

489

'value': w3.to_wei(1, 'ether'),

490

'gas': 21000,

491

'gasPrice': w3.to_wei(20, 'gwei'),

492

'accessList': access_list,

493

'chainId': 1,

494

'type': 1 # EIP-2930

495

}

496

497

signed_txn = account.sign_transaction(transaction)

498

tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)

499

print(f"Access list transaction hash: {tx_hash.hex()}")

500

```

501

502

### Batch Operations

503

504

```python

505

from web3 import Account

506

507

# Create multiple accounts

508

accounts = [Account.create() for _ in range(5)]

509

510

# Display all addresses

511

for i, account in enumerate(accounts):

512

print(f"Account {i}: {account.address}")

513

514

# Sign the same message with all accounts

515

message = "Batch signing test"

516

signatures = []

517

518

for account in accounts:

519

signed = account.sign_message(encode_defunct(text=message))

520

signatures.append({

521

'address': account.address,

522

'signature': signed.signature.hex()

523

})

524

525

print(f"Generated {len(signatures)} signatures")

526

```