Console

Getting to Know Ape Console

written by
Evan
Date Last Updated
November 22, 2022
Download Project Files

Ape provides an interactive console with useful pre-defined locals to interact with your project.

Ape console - Unplugged

Ape console comes with a few fresh features out of the box but really comes alive when combined with ape plugins.

In this first section, we'll explore the unplugged version and later see how the power of ape console is magnified with plugins.

What Is Ape Console?

Ape console is an interactive Python shell with ape-specific features. The console can be activated from the command line to access a Python interactive environment, like IPython.

The --help or -h flag will display a message showing available options with usage and description information.


$ ape console --help

Ape Console Command Line

Let's start by exploring the ape console command line.

--network

The --network flag is used to pass the name of an ecosystem, a network, and a provider for the current session.

The format for this value is [ecosystem-name]:[network-name]:[provider-name].

The default ecosystem is ethereum.


# ape console --network [NETWORK_NAME]
$ ape console --network ethereum:local:test

To see a list of available networks, use the network list command below.


$ ape networks list
# ethereum  (default)                                                                                                             
# ├── mainnet                                                                                                                     
# │   └── geth  (default)                                                                                                         
# ├── ropsten                                                                                                                     
# │   └── geth  (default)                                                                                                         
# ├── kovan                                                                                                                       
# │   └── geth  (default)                                                                                                         
# ├── rinkeby                                                                                                                     
# │   └── geth  (default)                                                                                                         
# ├── goerli                                                                                                                      
# │   └── geth  (default)                                                                                                         
# └── local  (default)                                                                                                            
#    ├── geth                                                                                                                    
#    └── test  (default)         

--verbosity

The --verbosity or -v flag is used to pass the message status level for the current session from the following values:

  • ERROR - most restrictive, only error messages
  • WARNING
  • SUCCESS
  • INFO
  • DEBUG - least restrictive; all messages


$ ape console --verbosity ERROR

$ ape console -v DEBUG

Ape Console Namespace - Pre-defined Locals

Ape console comes with pre-defined local variables, classes, and methods. In a more advanced tutorial, we'll look at how you can add your own locals to the ape console.

accounts

The accounts variable provides access to manage accounts, both aliased personal accounts (see Ape Console - Plugged In) and pre-funded test accounts.


# By default, 10 pre-funded test_acounts available
acct_a = accounts.test_accounts[0]
acct_a.balance
# 1000000000000000000000000

acct_b = accounts.test_accounts[1]
acct_b.balance
# 1000000000000000000000000

acct_b.tranfer(acct_a, 1000)
# Receipt 0xf920f746fb9208cdd05d42b508bd4cb082e5343e00f8ef06027bc957ae8c4688

acct_a.balance
# 1000000000000000000001000

chain

The chain variable provides access to the currently connected blockchain; it requires an active provider. This access is useful for development purposes, such as controlling the state of the blockchain. It's also handy for querying data about the chain.


chain.blocks.head.timestamp
# 1654034603

latest_block = chain.blocks[-1]
# Block(
#	gas_data=BlockGasFee(
#  	gas_limit=30029122, 
#    gas_used=0, 
#    base_fee=1000000000), 
#  consensus_data=BlockConsensus(
#  	difficulty=131072, 
#   total_difficulty=131072), 
#  hash=HexBytes('0xd058e0b6824e0e4a99254ae1c4e1c9f6ba2220757fb2f8303d2f0754dbbae32b'), 
#  number=0, 
#  parent_hash=HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000'), 
#  size=517, 
#  timestamp=1654034603)

# Print new blocks as they're mined
for new_block in chain.blocks.poll_blocks():
    print(f"New block found: number={new_block.number}")
    
biggest_block_size = chain.blocks.query("size").max() 

config

The config variable provides access to manage configuration settings within the current project. Ape configuration settings are stored in the ape-config.yaml file but can be interactively accessed in the console.


config.dict()
# {'DATA_FOLDER': PosixPath('/Users/worx/.ape'),
# 'REQUEST_HEADER': {'User-Agent': 'Ape/0.2.7 (Python/3.9.2 final)'},
# 'PROJECT_FOLDER': PosixPath('/Users/worx/ape'),
# 'name': '',
# 'version': '',
# 'contracts_folder': PosixPath('/Users/worx/ape/contracts'),
# 'dependencies': [],
# 'deployments': {},
# 'default_ecosystem': 'ethereum',
# 'transaction_acceptance_timeout': 120}

compilers

The compilers variable provides access to a compiler manager.


compilers.registered_compilers
# {'.json': InterfaceCompiler ethpm}

convert

The convert method provides a conversion utility function.


amount = convert("1 gwei", int)
# 1000000000

convert("1 ETH", int)
# 1000000000000000000

convert("283Af0B28c62C092C9727F1Ee09c02CA627EB7F5", bytes)
# HexBytes('0x283af0b28c62c092c9727f1ee09c02ca627eb7f5')

networks

The networks variable provides access to a network manager for the current project.


# Change the network provider, assumes alchemy plugin installed see Plugged In example
with networks.ethereum.mainnet.use_provider("alchemy"):
    print(networks.active_provider)
    
# name='alchemy' 
# network=mainnet chain_id=1
# provider_settings={} 
# data_folder=PosixPath('/Users/worx/.ape/ethereum/mainnet') 
# request_header={'User-Agent': 'Ape/0.2.7 (Python/3.9.2 final)'} 
# cached_chain_id=None 
# network_uris={'mainnet': 'https://eth-mainnet.alchemyapi.io/v2/[API KEY]'}

project

The project variable providers access to the currently active project.


from ape import project  # "project" is the ProjectManager for the active project
from ape import Project  # Is a ProjectManager

# MyContractType (example) is contract type in the active project
contract_type = project.MyContactType

Project

The Project class provides the ability to load a project from a given path.


# currently active project
project

# load another project
other_project = project.get_project("path/to/another/project")

Ape console - Plugged in

--network w/ Alchemy plugin & Infura plugin

Ape's console, combined with the Alchemy and/or Infura provider plugins, provides access to the underlying service provider. Plugin installation is simple and straightforward once your API KEY is generated within the Alchemy and/or Infura website and set in your Python environment.


# Please see ape alchemy and ape infura for more details on provider plugins

$ ape plugins install alchemy infura -y
# INFO: Installing alchemy...
# SUCCESS: Plugin 'alchemy==0.2.0' has been installed.
# INFO: Installing infura...
# SUCCESS: Plugin 'infura==0.2.0' has been installed.

$ ape console --network :mainnet:alchemy

Now we can switch within the console between the two providers.


networks.active_provider
# alchemy chain_id=1

mainnet = networks.ethereum.mainnet  # An instance of NetworkAPI
with mainnet.use_provider("infura"):
	print(networks.active_provider)
  
# name='infura' 
# network=mainnet chain_id=1 
# provider_settings={} 
# data_folder=PosixPath('/Users/worx/.ape/ethereum/mainnet') 
# request_header={'User-Agent': 'Ape/0.2.7 (Python/3.9.2 final)'} 
# cached_chain_id=None 
# network_uris={'mainnet': 'https://mainnet.infura.io/v3/[API KEY]'}

accounts w/ accounts CLI

Ape's console, combined with the account plugin, provides access to an account manager for loading, creating, and interfacing with accounts.


# Please see ape accounts for more details on CLI accounts

# ape accounts generate [ALIAS_OF_ACCOUNT]
$ ape accounts generate demo_account

# Add extra entropy for key generation...: 
# Create Passphrase: 
# Repeat for confirmation: 
# SUCCESS: A new account '0xB1b1A92A6f7435ba375e4cc470aED1e951e92fe5' has been added with the id 'demo_account'

If we use the CLI to generate an account, it will then be available in the console via the alias.


accounts.load("demo_account")
# KeyfileAccount address=0xB1b1A92A6f7435ba375e4cc470aED1e951e92fe5 alias=demo_account

To return to our previous state, we can delete the account.


$ ape accounts delete demo_account
# Enter passphrase to delete 'demo_account' []: 
# SUCCESS: Account 'demo_account' has been deleted

compilers w/ Vyper plugin

Ape's console, combined with the Vyper plugin, provides access to the compilers for the current project.


# Please ape vyper for more details on compilers

# ape plugins install [NAME_OF_PLUGIN]
$ ape plugins install vyper -y

# INFO: Installing vyper...
# SUCCESS: Plugin 'vyper==0.2.0' has been installed.

After we've installed the compiler plugin, we can access it in the console.


compilers.registered_compilers
{'.json': InterfaceCompiler ethpm, '.vy': VyperCompiler vyper}

To return to our previous state, we can uninstall the Vyper plugin.


$ ape plugins uninstall vyper -y
# SUCCESS: Plugin 'vyper' has been uninstalled.

config

The config variable allows loading Projects dynamically.


from pathlib import Path

project_path = Path("path/to/project")
contracts_path = project_path / "contracts"

with config.using_project(project_path) as my_project:
    print(my_project)

Contract w/ Alchemy plugin & Etherscan plugin

The Contract class provides a class for creating a contract instance. Combining this class with the Etherscan plugin allows a user to create instances of verified contracts from the blockchain.


$ ape plugins install etherscan alchemy -y
# INFO: Installing etherscan...
# SUCCESS: Plugin 'etherscan==0.2.0' has been installed.
# INFO: Installing alchemy...
# SUCCESS: Plugin 'alchemy==0.2.0' has been installed.

$ ape console --network :mainnet:alchemy

In the console, use the Contract class to create the instance.


contract = Contract("0x283Af0B28c62C092C9727F1Ee09c02CA627EB7F5")

contract.balance
# 16666984943662723690493 

contract.nonce
# 1

contract.codesize
# 9394