or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

accounts.mdcli.mdcontracts.mdconversion-testing.mdindex.mdnetwork.mdproject.md

network.mddocs/

0

# Network Management

1

2

Blockchain network connections, RPC node management, chain state control, and multi-network configuration for development, testing, and production environments.

3

4

## Capabilities

5

6

### Network Connection Management

7

8

Global functions for managing blockchain network connections and configuration.

9

10

```python { .api }

11

def connect(network: str = None, launch_rpc: bool = True) -> None:

12

"""

13

Connect to a blockchain network.

14

15

Args:

16

network: Network name from brownie-config.yaml (None for default)

17

launch_rpc: Launch local RPC node if needed

18

19

Raises:

20

ConnectionError: If connection fails

21

MainnetUndefined: If connecting to mainnet without configuration

22

"""

23

24

def disconnect() -> None:

25

"""Disconnect from current network and stop local RPC if running."""

26

27

def is_connected() -> bool:

28

"""

29

Check if connected to a network.

30

31

Returns:

32

bool: True if connected to a network

33

"""

34

35

def show_active() -> str:

36

"""

37

Display currently active network information.

38

39

Returns:

40

str: Active network name

41

"""

42

43

def gas_limit(*args) -> Union[int, None]:

44

"""

45

Get or set global gas limit for transactions.

46

47

Args:

48

*args: New gas limit value (empty to get current)

49

50

Returns:

51

int: Current gas limit setting

52

"""

53

54

def gas_price(*args) -> Union[int, None]:

55

"""

56

Get or set global gas price for legacy transactions.

57

58

Args:

59

*args: New gas price in wei (empty to get current)

60

61

Returns:

62

int: Current gas price setting

63

"""

64

65

def max_fee(*args) -> Union[int, None]:

66

"""

67

Get or set global max fee per gas for EIP-1559 transactions.

68

69

Args:

70

*args: New max fee in wei (empty to get current)

71

72

Returns:

73

int: Current max fee setting

74

"""

75

76

def priority_fee(*args) -> Union[int, None]:

77

"""

78

Get or set global priority fee per gas for EIP-1559 transactions.

79

80

Args:

81

*args: New priority fee in wei (empty to get current)

82

83

Returns:

84

int: Current priority fee setting

85

"""

86

```

87

88

### Chain State Management

89

90

The Chain class provides blockchain state management including snapshots, time manipulation, and mining control for testing environments.

91

92

```python { .api }

93

class Chain:

94

"""

95

Blockchain state manager for development and testing.

96

97

Available as global singleton 'chain' after importing brownie.

98

99

Attributes:

100

height (int): Current block height

101

time (int): Latest block timestamp

102

id (int): Chain ID of connected network

103

"""

104

105

def __len__(self) -> int:

106

"""Get current block height."""

107

108

def __getitem__(self, index: int) -> dict:

109

"""

110

Get block information by number.

111

112

Args:

113

index: Block number

114

115

Returns:

116

dict: Block data including hash, timestamp, transactions

117

"""

118

119

def snapshot(self) -> str:

120

"""

121

Take a snapshot of current blockchain state.

122

123

Returns:

124

str: Snapshot ID for later reversion

125

"""

126

127

def revert(self, snapshot_id: str = None) -> None:

128

"""

129

Revert blockchain state to a snapshot.

130

131

Args:

132

snapshot_id: Snapshot ID (latest if None)

133

"""

134

135

def reset(self) -> None:

136

"""Reset blockchain to initial state (block 0)."""

137

138

def undo(self, num_transactions: int = 1) -> None:

139

"""

140

Undo recent transactions.

141

142

Args:

143

num_transactions: Number of transactions to undo

144

"""

145

146

def redo(self, num_transactions: int = 1) -> None:

147

"""

148

Redo previously undone transactions.

149

150

Args:

151

num_transactions: Number of transactions to redo

152

"""

153

154

def mine(self, blocks: int = 1, timestamp: int = None) -> None:

155

"""

156

Mine empty blocks.

157

158

Args:

159

blocks: Number of blocks to mine

160

timestamp: Timestamp for mined blocks (auto if None)

161

"""

162

163

def sleep(self, seconds: int) -> None:

164

"""

165

Advance blockchain time without mining blocks.

166

167

Args:

168

seconds: Seconds to advance

169

"""

170

171

def set_time(self, timestamp: int) -> None:

172

"""

173

Set blockchain time to specific timestamp.

174

175

Args:

176

timestamp: Unix timestamp

177

"""

178

179

def get_transaction(self, txid: str) -> TransactionReceipt:

180

"""

181

Get transaction by hash.

182

183

Args:

184

txid: Transaction hash

185

186

Returns:

187

TransactionReceipt: Transaction details

188

"""

189

190

def new_block(self, timestamp: int = None) -> None:

191

"""

192

Mine a new block with optional timestamp.

193

194

Args:

195

timestamp: Block timestamp (auto if None)

196

"""

197

```

198

199

### RPC Node Management

200

201

The Rpc class manages local RPC node processes for development and testing.

202

203

```python { .api }

204

class Rpc:

205

"""

206

RPC node process manager for local development networks.

207

208

Available as global singleton 'rpc' after importing brownie.

209

210

Attributes:

211

is_active (bool): Whether RPC node is running

212

endpoint (str): RPC endpoint URL

213

port (int): RPC port number

214

"""

215

216

def launch(self, cmd: str = None, **kwargs) -> None:

217

"""

218

Launch local RPC node process.

219

220

Args:

221

cmd: Custom command to launch RPC (auto-detect if None)

222

**kwargs: Additional RPC configuration options

223

"""

224

225

def attach(self, laddr: str) -> None:

226

"""

227

Attach to existing RPC node.

228

229

Args:

230

laddr: RPC endpoint address

231

"""

232

233

def kill(self, confirm: bool = True) -> None:

234

"""

235

Stop the RPC node process.

236

237

Args:

238

confirm: Require confirmation before stopping

239

"""

240

241

def snapshot(self) -> str:

242

"""

243

Take RPC-level snapshot of blockchain state.

244

245

Returns:

246

str: Snapshot ID

247

"""

248

249

def revert(self, snapshot_id: str) -> None:

250

"""

251

Revert to RPC-level snapshot.

252

253

Args:

254

snapshot_id: Snapshot ID to revert to

255

"""

256

257

def mine(self, blocks: int = 1) -> None:

258

"""

259

Mine blocks via RPC.

260

261

Args:

262

blocks: Number of blocks to mine

263

"""

264

265

def sleep(self, seconds: int) -> None:

266

"""

267

Advance time via RPC.

268

269

Args:

270

seconds: Seconds to advance

271

"""

272

273

def reset(self) -> None:

274

"""Reset RPC node to initial state."""

275

```

276

277

### Web3 Integration

278

279

Enhanced Web3 instance with brownie-specific functionality and middleware.

280

281

```python { .api }

282

class Web3:

283

"""

284

Enhanced Web3 instance with brownie-specific functionality.

285

286

Available as global singleton 'web3' after importing brownie.

287

288

Attributes:

289

eth: Ethereum interface

290

net: Network interface

291

personal: Personal account interface

292

txpool: Transaction pool interface

293

admin: Admin interface (if available)

294

miner: Miner interface (if available)

295

"""

296

297

def __init__(self):

298

"""Initialize enhanced Web3 instance."""

299

300

def isConnected(self) -> bool:

301

"""Check if Web3 is connected to provider."""

302

303

def middleware_onion(self):

304

"""Access Web3 middleware stack."""

305

306

def clientVersion(self) -> str:

307

"""Get client version string."""

308

309

# Standard Web3 methods available through eth interface

310

def toWei(self, value: Union[int, float, str], unit: str) -> int:

311

"""Convert value to wei."""

312

313

def fromWei(self, value: int, unit: str) -> Union[int, float]:

314

"""Convert wei to other units."""

315

316

def toHex(self, value: Union[int, str, bytes]) -> str:

317

"""Convert value to hexadecimal string."""

318

319

def isAddress(self, address: str) -> bool:

320

"""Check if string is valid Ethereum address."""

321

322

def toChecksumAddress(self, address: str) -> str:

323

"""Convert address to checksum format."""

324

```

325

326

### Transaction History

327

328

The TxHistory class manages and filters transaction history for analysis and debugging.

329

330

```python { .api }

331

class TxHistory:

332

"""

333

Transaction history manager with filtering and analysis capabilities.

334

335

Available as global singleton 'history' after importing brownie.

336

"""

337

338

def __len__(self) -> int:

339

"""Get number of transactions in history."""

340

341

def __getitem__(self, index: int) -> TransactionReceipt:

342

"""

343

Get transaction by index.

344

345

Args:

346

index: Transaction index

347

348

Returns:

349

TransactionReceipt: Transaction at index

350

"""

351

352

def __iter__(self):

353

"""Iterate over transaction history."""

354

355

def clear(self) -> None:

356

"""Clear transaction history."""

357

358

def filter(self, **kwargs) -> list:

359

"""

360

Filter transactions by criteria.

361

362

Args:

363

**kwargs: Filter criteria (sender, receiver, function, etc.)

364

365

Returns:

366

list: Filtered transaction receipts

367

"""

368

369

def from_sender(self, account: str) -> list:

370

"""

371

Get transactions from specific sender.

372

373

Args:

374

account: Sender address

375

376

Returns:

377

list: Transactions from sender

378

"""

379

380

def to_receiver(self, account: str) -> list:

381

"""

382

Get transactions to specific receiver.

383

384

Args:

385

account: Receiver address

386

387

Returns:

388

list: Transactions to receiver

389

"""

390

391

def of_address(self, account: str) -> list:

392

"""

393

Get transactions involving specific address.

394

395

Args:

396

account: Address to search for

397

398

Returns:

399

list: Transactions involving address

400

"""

401

```

402

403

### Multicall Utility

404

405

The Multicall class enables batching multiple contract calls into a single transaction for gas optimization.

406

407

```python { .api }

408

class Multicall:

409

"""

410

Multicall utility for batching contract calls.

411

412

Available as global singleton 'multicall' after importing brownie.

413

"""

414

415

def __init__(self, address: str = None):

416

"""

417

Initialize multicall with contract address.

418

419

Args:

420

address: Multicall contract address (auto-detect if None)

421

"""

422

423

def __enter__(self):

424

"""Enter multicall context manager."""

425

426

def __exit__(self, exc_type, exc_val, exc_tb):

427

"""Exit multicall context and execute batched calls."""

428

429

def flush(self) -> None:

430

"""Execute all queued calls and clear the queue."""

431

```

432

433

## Usage Examples

434

435

### Network Connection

436

437

```python

438

import brownie

439

from brownie import network

440

441

# Connect to development network

442

network.connect('development')

443

print(f"Connected to: {network.show_active()}")

444

445

# Connect to testnet

446

network.connect('sepolia')

447

448

# Connect to mainnet

449

network.connect('mainnet')

450

451

# Check connection status

452

if network.is_connected():

453

print("Connected to network")

454

else:

455

print("Not connected")

456

457

# Disconnect

458

network.disconnect()

459

```

460

461

### Gas Configuration

462

463

```python

464

from brownie import network

465

466

# Set global gas settings

467

network.gas_limit(3000000)

468

network.gas_price("20 gwei")

469

470

# EIP-1559 settings

471

network.max_fee("30 gwei")

472

network.priority_fee("2 gwei")

473

474

# Check current settings

475

print(f"Gas limit: {network.gas_limit()}")

476

print(f"Gas price: {network.gas_price()}")

477

```

478

479

### Chain State Management

480

481

```python

482

from brownie import chain, accounts

483

484

# Take snapshot before test

485

snapshot = chain.snapshot()

486

print(f"Snapshot taken: {snapshot}")

487

488

# Perform operations

489

account = accounts[0]

490

initial_balance = account.balance()

491

492

# Mine some blocks

493

chain.mine(10)

494

print(f"Block height: {chain.height}")

495

496

# Advance time

497

chain.sleep(3600) # 1 hour

498

print(f"Block time: {chain.time()}")

499

500

# Revert to snapshot

501

chain.revert(snapshot)

502

print(f"Reverted to snapshot, height: {chain.height}")

503

504

# Reset to genesis

505

chain.reset()

506

```

507

508

### RPC Node Management

509

510

```python

511

from brownie import rpc

512

513

# Launch local RPC node

514

rpc.launch('ganache-cli', accounts=10, mnemonic='test test test')

515

516

# Take RPC snapshot

517

snapshot_id = rpc.snapshot()

518

519

# Perform operations

520

# ...

521

522

# Revert RPC state

523

rpc.revert(snapshot_id)

524

525

# Stop RPC node

526

rpc.kill()

527

```

528

529

### Transaction History Analysis

530

531

```python

532

from brownie import history, accounts

533

534

# View transaction history

535

print(f"Total transactions: {len(history)}")

536

537

# Get specific transaction

538

if len(history) > 0:

539

latest_tx = history[-1]

540

print(f"Latest transaction: {latest_tx.txid}")

541

542

# Filter transactions

543

sender_txs = history.from_sender(accounts[0].address)

544

print(f"Transactions from account[0]: {len(sender_txs)}")

545

546

# Filter by multiple criteria

547

filtered_txs = history.filter(

548

sender=accounts[0].address,

549

function='transfer'

550

)

551

552

# Clear history

553

history.clear()

554

```

555

556

### Multicall Batching

557

558

```python

559

from brownie import multicall, project

560

561

# Load contracts

562

token = project.Token.at("0x...")

563

vault = project.Vault.at("0x...")

564

565

# Batch multiple calls

566

with multicall:

567

token_balance = token.balanceOf(accounts[0])

568

vault_balance = vault.balanceOf(accounts[0])

569

total_supply = token.totalSupply()

570

571

# All calls executed in single transaction

572

print(f"Token balance: {token_balance}")

573

print(f"Vault balance: {vault_balance}")

574

print(f"Total supply: {total_supply}")

575

```

576

577

### Web3 Integration

578

579

```python

580

from brownie import web3

581

582

# Check connection

583

print(f"Connected: {web3.isConnected()}")

584

print(f"Client: {web3.clientVersion}")

585

586

# Unit conversions

587

wei_amount = web3.toWei(1, 'ether')

588

eth_amount = web3.fromWei(wei_amount, 'ether')

589

590

# Address utilities

591

address = "0x742d35Cc6634C0532925a3b8D8D944d0Cdbc1234"

592

checksum_addr = web3.toChecksumAddress(address.lower())

593

is_valid = web3.isAddress(address)

594

595

# Access standard Web3 interfaces

596

latest_block = web3.eth.get_block('latest')

597

network_id = web3.net.version

598

```

599

600

### Development Workflow

601

602

```python

603

from brownie import network, chain, accounts, rpc

604

605

# Setup development environment

606

network.connect('development')

607

network.gas_limit(6000000)

608

network.gas_price("10 gwei")

609

610

# Take initial snapshot

611

initial_state = chain.snapshot()

612

613

try:

614

# Deploy contracts and run tests

615

account = accounts[0]

616

# ... test operations ...

617

618

# Take checkpoint before risky operation

619

checkpoint = chain.snapshot()

620

621

# Perform risky operation

622

# ... risky code ...

623

624

except Exception as e:

625

print(f"Error occurred: {e}")

626

# Revert to checkpoint

627

chain.revert(checkpoint)

628

629

finally:

630

# Clean up - revert to initial state

631

chain.revert(initial_state)

632

network.disconnect()

633

```

634

635

## Type Definitions

636

637

```python { .api }

638

# Type aliases for network operations

639

NetworkType = str

640

BlockIdentifier = Union[int, str] # Block number or 'latest'/'pending'

641

SnapshotId = str

642

GasSettings = Dict[str, Union[int, str]]

643

FilterCriteria = Dict[str, Any]

644

```