y package
Subpackages
- y.classes package
- Submodules
- y.classes.common module
ContractBase
ERC20
ERC20._decimals
ERC20._scale
ERC20.__eq__()
ERC20.__init__()
ERC20.__str__()
ERC20.__build_name__
ERC20.__decimals__
ERC20.__name__
ERC20.__scale__
ERC20.__symbol__
ERC20.address
ERC20.asynchronous
ERC20.balance_of
ERC20.balance_of_readable
ERC20.build_name
ERC20.contract
ERC20.decimals
ERC20.deploy_block
ERC20.has_method
ERC20.name
ERC20.price
ERC20.scale
ERC20.symbol
ERC20.total_supply
ERC20.total_supply_readable
WeiBalance
WeiBalance.__add__()
WeiBalance.__bool__()
WeiBalance.__eq__()
WeiBalance.__ge__()
WeiBalance.__init__()
WeiBalance.__lt__()
WeiBalance.__mul__()
WeiBalance.__radd__()
WeiBalance.__str__()
WeiBalance.__sub__()
WeiBalance.__truediv__()
WeiBalance.__price__
WeiBalance.__readable__
WeiBalance.__value_usd__
WeiBalance.asynchronous
WeiBalance.block
WeiBalance.price
WeiBalance.readable
WeiBalance.value_usd
hex_to_string()
- y.classes.singleton module
ChecksumASyncSingletonMeta
ChecksumASyncSingletonMeta.__base__
ChecksumASyncSingletonMeta.__call__()
ChecksumASyncSingletonMeta.__dir__()
ChecksumASyncSingletonMeta.__getattribute__()
ChecksumASyncSingletonMeta.__init__()
ChecksumASyncSingletonMeta.__instancecheck__()
ChecksumASyncSingletonMeta.__or__()
ChecksumASyncSingletonMeta.__prepare__()
ChecksumASyncSingletonMeta.__ror__()
ChecksumASyncSingletonMeta.__sizeof__()
ChecksumASyncSingletonMeta.__subclasscheck__()
ChecksumASyncSingletonMeta.__subclasses__()
ChecksumASyncSingletonMeta.mro()
ChecksumASyncSingletonMeta.register()
ChecksumASyncSingletonMeta.__bases__
ChecksumASyncSingletonMeta.__basicsize__
ChecksumASyncSingletonMeta.__dictoffset__
ChecksumASyncSingletonMeta.__flags__
ChecksumASyncSingletonMeta.__itemsize__
ChecksumASyncSingletonMeta.__mro__
ChecksumASyncSingletonMeta.__name__
ChecksumASyncSingletonMeta.__qualname__
ChecksumASyncSingletonMeta.__text_signature__
ChecksumASyncSingletonMeta.__weakrefoffset__
- Module contents
ERC20
ERC20._decimals
ERC20._scale
ERC20.__eq__()
ERC20.__init__()
ERC20.__str__()
ERC20.__build_name__
ERC20.__decimals__
ERC20.__name__
ERC20.__scale__
ERC20.__symbol__
ERC20.address
ERC20.asynchronous
ERC20.balance_of
ERC20.balance_of_readable
ERC20.build_name
ERC20.contract
ERC20.decimals
ERC20.deploy_block
ERC20.has_method
ERC20.name
ERC20.price
ERC20.scale
ERC20.symbol
ERC20.total_supply
ERC20.total_supply_readable
- y.interfaces package
- y.prices package
- Subpackages
- Submodules
- y.prices.band module
- y.prices.chainlink module
Chainlink
Feed
FeedsFromEvents
FeedsFromEvents.obj_type
FeedsFromEvents.__aiter__()
FeedsFromEvents.__await__()
FeedsFromEvents.__init__()
FeedsFromEvents.__iter__()
FeedsFromEvents._objects_thru()
FeedsFromEvents.events()
FeedsFromEvents.filter()
FeedsFromEvents.logs()
FeedsFromEvents.objects()
FeedsFromEvents.sort()
FeedsFromEvents.wrap()
FeedsFromEvents.__wrapped__
FeedsFromEvents.addresses
FeedsFromEvents.asynchronous
FeedsFromEvents.bulk_insert
FeedsFromEvents.cache
FeedsFromEvents.executor
FeedsFromEvents.from_block
FeedsFromEvents.insert_to_db
FeedsFromEvents.is_asleep
FeedsFromEvents.is_reusable
FeedsFromEvents.materialized
FeedsFromEvents.semaphore
FeedsFromEvents.to_block
FeedsFromEvents.topics
- y.prices.convex module
- y.prices.gearbox module
DieselPool
DieselPool.__eq__()
DieselPool.__init__()
DieselPool.__str__()
DieselPool.__build_name__
DieselPool.__contract__
DieselPool.__diesel_token__
DieselPool.__underlying__
DieselPool.address
DieselPool.asynchronous
DieselPool.build_name
DieselPool.contract
DieselPool.deploy_block
DieselPool.diesel_token
DieselPool.exchange_rate
DieselPool.get_price
DieselPool.has_method
DieselPool.underlying
Gearbox
- y.prices.magic module
- y.prices.one_to_one module
- y.prices.pendle module
- y.prices.popsicle module
- y.prices.rkp3r module
- y.prices.solidex module
- y.prices.synthetix module
- y.prices.yearn module
YearnInspiredVault
YearnInspiredVault._decimals
YearnInspiredVault._scale
YearnInspiredVault.__eq__()
YearnInspiredVault.__init__()
YearnInspiredVault.__str__()
YearnInspiredVault.__build_name__
YearnInspiredVault.__decimals__
YearnInspiredVault.__name__
YearnInspiredVault.__scale__
YearnInspiredVault.__symbol__
YearnInspiredVault.__underlying__
YearnInspiredVault.address
YearnInspiredVault.asynchronous
YearnInspiredVault.balance_of
YearnInspiredVault.balance_of_readable
YearnInspiredVault.build_name
YearnInspiredVault.contract
YearnInspiredVault.decimals
YearnInspiredVault.deploy_block
YearnInspiredVault.has_method
YearnInspiredVault.name
YearnInspiredVault.price
YearnInspiredVault.scale
YearnInspiredVault.share_price
YearnInspiredVault.symbol
YearnInspiredVault.total_supply
YearnInspiredVault.total_supply_readable
YearnInspiredVault.underlying
get_price
is_yearn_vault
share_price_methods
underlying_methods
- Module contents
- y.utils package
- Submodules
- y.utils.cache module
- y.utils.checks module
- y.utils.client module
- y.utils.dank_mids module
- y.utils.events module
Events
Events.obj_type
Events.__aiter__()
Events.__await__()
Events.__init__()
Events.__iter__()
Events._objects_thru()
Events.events()
Events.filter()
Events.logs()
Events.sort()
Events.wrap()
Events.__wrapped__
Events.addresses
Events.bulk_insert
Events.cache
Events.executor
Events.from_block
Events.insert_to_db
Events.is_asleep
Events.is_reusable
Events.materialized
Events.semaphore
Events.to_block
Events.topics
LogFilter
LogFilter.__aiter__()
LogFilter.__await__()
LogFilter.__init__()
LogFilter.__iter__()
LogFilter._objects_thru()
LogFilter.filter()
LogFilter.logs()
LogFilter.sort()
LogFilter.wrap()
LogFilter.__wrapped__
LogFilter.addresses
LogFilter.bulk_insert
LogFilter.cache
LogFilter.executor
LogFilter.from_block
LogFilter.insert_to_db
LogFilter.is_asleep
LogFilter.is_reusable
LogFilter.materialized
LogFilter.semaphore
LogFilter.to_block
LogFilter.topics
ProcessedEvents
ProcessedEvents.obj_type
ProcessedEvents.__aiter__()
ProcessedEvents.__await__()
ProcessedEvents.__init__()
ProcessedEvents.__iter__()
ProcessedEvents._objects_thru()
ProcessedEvents.events()
ProcessedEvents.filter()
ProcessedEvents.logs()
ProcessedEvents.objects()
ProcessedEvents.sort()
ProcessedEvents.wrap()
ProcessedEvents.__wrapped__
ProcessedEvents.addresses
ProcessedEvents.bulk_insert
ProcessedEvents.cache
ProcessedEvents.executor
ProcessedEvents.from_block
ProcessedEvents.insert_to_db
ProcessedEvents.is_asleep
ProcessedEvents.is_reusable
ProcessedEvents.materialized
ProcessedEvents.semaphore
ProcessedEvents.to_block
ProcessedEvents.topics
_get_logs
checkpoints_to_weight()
decode_logs()
get_logs_asap
get_logs_asap_generator()
logs_to_balance_checkpoints()
- y.utils.fakes module
- y.utils.gather module
- y.utils.logging module
PriceLogger
PriceLogger.__init__()
PriceLogger.addFilter()
PriceLogger.addHandler()
PriceLogger.callHandlers()
PriceLogger.close()
PriceLogger.critical()
PriceLogger.debug()
PriceLogger.error()
PriceLogger.exception()
PriceLogger.fatal()
PriceLogger.filter()
PriceLogger.findCaller()
PriceLogger.getChild()
PriceLogger.getEffectiveLevel()
PriceLogger.handle()
PriceLogger.hasHandlers()
PriceLogger.info()
PriceLogger.isEnabledFor()
PriceLogger.log()
PriceLogger.makeRecord()
PriceLogger.removeFilter()
PriceLogger.removeHandler()
PriceLogger.setLevel()
PriceLogger.warn()
PriceLogger.warning()
PriceLogger.address
PriceLogger.block
PriceLogger.debug_task
PriceLogger.enabled
PriceLogger.key
PriceLogger.manager
PriceLogger.root
enable_debug_logging()
get_price_logger()
- y.utils.middleware module
- y.utils.multicall module
- y.utils.raw_calls module
- Module contents
Submodules
y.ENVIRONMENT_VARIABLES module
- y.ENVIRONMENT_VARIABLES.CACHE_TTL = <EnvironmentVariable[name=`YPRICEMAGIC_CACHE_TTL`, type=int, default_value=3600, current_value=3600, using_default=True]>
TTL for various in-memory caches throughout the library
- y.ENVIRONMENT_VARIABLES.CONTRACT_CACHE_TTL = <EnvironmentVariable[name=`YPRICEMAGIC_CONTRACT_CACHE_TTL`, type=int, default_value=3600, current_value=3600, using_default=True]>
TTL for contract cache, defaults to
CACHE_TTL
if not set
- y.ENVIRONMENT_VARIABLES.DB_DATABASE = <EnvironmentVariable[name=`YPRICEMAGIC_DB_DATABASE`, type=str, default_value=ypricemagic, current_value=ypricemagic, using_default=True]>
Database name
- y.ENVIRONMENT_VARIABLES.DB_HOST = <EnvironmentVariable[name=`YPRICEMAGIC_DB_HOST`, type=str, default_value=, current_value=, using_default=True]>
Database host address
- y.ENVIRONMENT_VARIABLES.DB_PASSWORD = <EnvironmentVariable[name=`YPRICEMAGIC_DB_PASSWORD`, type=str, default_value=, current_value=, using_default=True]>
Database password
- y.ENVIRONMENT_VARIABLES.DB_PORT = <EnvironmentVariable[name=`YPRICEMAGIC_DB_PORT`, type=str, default_value=, current_value=, using_default=True]>
Database port number
- y.ENVIRONMENT_VARIABLES.DB_PROVIDER = <EnvironmentVariable[name=`YPRICEMAGIC_DB_PROVIDER`, type=str, default_value=sqlite, current_value=sqlite, using_default=True]>
Database provider (e.g., ‘sqlite’, ‘postgresql’)
- y.ENVIRONMENT_VARIABLES.DB_USER = <EnvironmentVariable[name=`YPRICEMAGIC_DB_USER`, type=str, default_value=, current_value=, using_default=True]>
Database user name
- y.ENVIRONMENT_VARIABLES.GETLOGS_BATCH_SIZE = <EnvironmentVariable[name=`YPRICEMAGIC_GETLOGS_BATCH_SIZE`, type=int, default_value=0, current_value=0, using_default=True]>
Batch size for getlogs operations, 0 will use default as determined by your provider.
- y.ENVIRONMENT_VARIABLES.GETLOGS_DOP = <EnvironmentVariable[name=`YPRICEMAGIC_GETLOGS_DOP`, type=int, default_value=32, current_value=32, using_default=True]>
Degree of parallelism for eth_getLogs operations
- y.ENVIRONMENT_VARIABLES.SKIP_CACHE = <EnvironmentVariable[name=`YPRICEMAGIC_SKIP_CACHE`, type=bool, default_value=False, current_value=False, using_default=True]>
Flag to skip cache usage
- y.ENVIRONMENT_VARIABLES.SKIP_YPRICEAPI = <EnvironmentVariable[name=`SKIP_YPRICEAPI`, type=bool, default_value=False, current_value=False, using_default=True]>
Flag to skip using ypriceapi
y.constants module
- y.constants.EEE_ADDRESS = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE'
The address used to represent the native token (e.g., ETH on Ethereum, AVAX on Avalanche, etc.) in various DeFi protocols.
- y.constants.WRAPPED_GAS_COIN = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2'
The address of the wrapped version of the native token on the active network. For example, on Ethereum Mainnet, WRAPPED_GAS_COIN == the WETH address. On Fantom, it is equal to the WFTM address. And so on.
- y.constants.dai = <Dai Contract '0x6B175474E89094C44Da98b954EedeAC495271d0F'>
Dai Stablecoin (DAI) contract on Base.
- y.constants.sushi: Contract | None = <SushiToken Contract '0x6B3595068778DD592e39A122f4f5a5cF09C90fE2'>
SushiToken (SUSHI) contract on Ethereum Mainnet.
- y.constants.usdc = <FiatTokenV2_1 Contract '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'>
USD Coin (USDC) contract on Optimism.
- y.constants.usdt = <TetherToken Contract '0xdAC17F958D2ee523a2206206994597C13D831ec7'>
Tether USD (USDT) contract on Optimism.
- y.constants.wbtc = <WBTC Contract '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599'>
Wrapped Bitcoin (WBTC) contract on Optimism.
- y.constants.weth = <WETH9 Contract '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2'>
Wrapped Ether (WETH) contract on Base.
y.contracts module
- class y.contracts.Contract[source]
Bases:
Contract
Though it may look complicated, a ypricemagic Contract object is simply a brownie Contract object with a few modifications:
- Contracts will not be compiled. This allows you to more quickly fetch contracts from the block explorer and prevents you from having to download and install compilers.
NOTE: You must set autofetch_sources=false in your project’s brownie-config.yaml for this to work correctly.
- To each contract method, a coroutine property has been defined which allows you to make asynchronous calls which are intelligently batched in the background by
dank_mids
to reduce overhead. - Example:
>>> contract = Contract("0xAddress") >>> contract.methodName(*args, block_identifier=12345678) 1000000000000000000 >>> coro = contract.methodName.coroutine(*args, block_identifier=12345678) >>> coro <coroutine coroutine object at 0x12345678> >>> contract.methodName(*args, block_identifier=12345678) == await coro True
- To each contract method, a coroutine property has been defined which allows you to make asynchronous calls which are intelligently batched in the background by
- New methods:
- A few attributes were removed in order to minimize the size of a Contract object in memory:
ast
bytecode
coverageMap
deployedBytecode
deployedSourceMap
natspec
opcodes
pcMap
- __getattribute__(name)[source]
Get a contract method attribute.
This method implements lazy initialization of contract methods. If a method object does not yet exist, it is created and cached.
- Parameters:
name (str) – The name of the attribute to get.
- Returns:
The contract method object.
- Return type:
- __init__(address, owner=None, require_success=True, cache_ttl=<EnvironmentVariable[name=`YPRICEMAGIC_CONTRACT_CACHE_TTL`, type=int, default_value=3600, current_value=3600, using_default=True]>)[source]
Initialize the Contract instance.
This method sets up lazy initialization for contract methods.
- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int)
owner (AccountsType | None)
require_success (bool)
cache_ttl (int | None)
- Return type:
None
- async build_name(return_None_on_failure=False)[source]
Get the build name of the contract.
- Parameters:
return_None_on_failure (optional) – If True, return None if the build name cannot be determined instead of raising an Exception. Default False.
- Returns:
The build name of the contract, or None if the build name cannot be determined and return_None_on_failure is True.
- Return type:
str | None
- async classmethod coroutine(address, require_success=True, cache_ttl=<EnvironmentVariable[name=`YPRICEMAGIC_CONTRACT_CACHE_TTL`, type=int, default_value=3600, current_value=3600, using_default=True]>)[source]
- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int)
require_success (bool)
cache_ttl (int | None)
- Return type:
Self
- decode_input(calldata)
Decode input calldata for this contract.
- classmethod from_abi(name, address, abi, owner=None, persist=True, cache_ttl=<EnvironmentVariable[name=`YPRICEMAGIC_CONTRACT_CACHE_TTL`, type=int, default_value=3600, current_value=3600, using_default=True]>)[source]
Create a Contract instance from an ABI.
- Args:
name: The name of the contract. address: The address of the contract. abi: The ABI of the contract. owner (optional): The owner of the contract. Default None. persist (optional): If True, persist the contract in brownie’s local contract database. Default True. cache_ttl (optional): The time-to-live for the contract cache in seconds. Default set in
ENVIRONMENT_VARIABLES
.- Returns:
A Contract instance for the given ABI.
Since from_abi is an
ASyncFunctionSyncDefault
, you can optionally pass sync=False or asynchronous=True to force it to return a coroutine. Without either kwarg, it will run synchronously.
- classmethod from_ethpm(name, manifest_uri, address=None, owner=None, persist=True)[source]
Create a new Contract instance from an ethPM manifest.
This method allows for the creation of a Contract instance using an ethPM manifest, which is a standardized format for Ethereum smart contract packages.
- Parameters:
name (str) – The name of the contract.
manifest_uri (str) – The URI of the ethPM manifest.
address (str | None) – The address of the deployed contract (optional).
owner (AccountsType | None) – The account that owns this contract instance.
persist (bool) – Whether to persist the contract data to brownie’s local db for future use.
- Returns:
A new Contract instance.
- Return type:
- classmethod from_explorer(address, as_proxy_for=None, owner=None, silent=False, persist=True)[source]
Create a new Contract instance by fetching the ABI from a block explorer.
This method is useful for interacting with contracts that are not part of the current project, as it automatically fetches the contract’s ABI from a block explorer.
- Parameters:
address (str) – The address of the deployed contract.
as_proxy_for (str | None) – The address of the implementation contract if this is a proxy contract.
owner (AccountsType | None) – The account that owns this contract instance.
silent (bool) – Whether to suppress console output during the process.
persist (bool) – Whether to persist the contract data to brownie’s db for future use.
- Returns:
A new Contract instance.
- Return type:
- async get_code(block=None)[source]
Get the bytecode of the contract at a specific block.
- Parameters:
block (optional) – The block number at which to get the bytecode. Defaults to latest block.
- Returns:
The bytecode of the contract at the specified block.
- Return type:
- get_method_object(calldata)
Given a calldata hex string, returns a ContractMethod object.
- Parameters:
calldata (str)
- Return type:
_ContractMethod | None
- classmethod get_solc_version(compiler_str, address)[source]
Return the solc compiler version either from the passed compiler string or try to find the latest available patch semver compiler version.
- has_method(method, return_response=False)[source]
Check if the contract has a specific method.
- Parameters:
method (str) – The name of the method to check for.
return_response (optional) – If True, return the response of the method call instead of a boolean. Default False.
- Returns:
A boolean indicating whether the contract has the method, or the response of the method call if return_response is True.
- Return type:
- async has_methods(methods, _func=<built-in function all>)[source]
Check if the contract has all the specified methods.
- info()
Display NatSpec documentation for this contract.
- Return type:
None
- classmethod remove_deployment(address=None, alias=None)[source]
Removes this contract from the internal deployments db with the passed address or alias.
- set_alias(alias, persist=True)[source]
Apply a unique alias this object. The alias can be used to restore the object in future sessions.
- events: ContractEvents
A container for various event types associated with this contract.
Provides a convenient way to query contract events with minimal code.
- signatures: Dict[Method, Signature]
A dictionary mapping method names to their corresponding signatures.
- verified = True
True if the contract is verified on this network’s block explorer. False otherwise.
- class y.contracts.ContractEvents[source]
Bases:
ContractEvents
- __iter__()
Iterate over supported
- get_sequence(from_block, to_block=None, event_type=None)[source]
Returns the logs of events of type ‘event_type’ that occurred between the blocks ‘from_block’ and ‘to_block’. If ‘event_type’ is not specified, it retrieves the occurrences of all events in the contract.
- Parameters:
from_block (int) – The block from which to search for events that have occurred.
to_block (int, optional) – The block on which to stop searching for events.
specified (if not)
block (it is set to the most recently mined)
None. (between the specified blocks. Defaults to)
event_type (ContractEvent, str, optional) – Type or name of the event to be searched
None.
- Returns:
- [list]: List of events of type ‘event_type’ that occurred between
’from_block’ and ‘to_block’.
- else:
event_logbook [dict]: Dictionary of events of the contract that occurred between ‘from_block’ and ‘to_block’.
- Return type:
if ‘event_type’ is specified
- listen(event_name, timeout=0)[source]
Creates a listening Coroutine object ending whenever an event matching ‘event_name’ occurs. If timeout is superior to zero and no event matching ‘event_name’ has occured, the Coroutine ends when the timeout is reached.
- The Coroutine return value is an AttributeDict filled with the following fields :
‘event_data’ (AttributeDict): The event log receipt that was caught.
‘timed_out’ (bool): False if the event did not timeout, else True
If the ‘timeout’ parameter is not passed or is inferior or equal to 0, the Coroutine listens indefinitely.
- y.contracts.Contract_erc20(address)[source]
Create a Contract instance for an ERC20 token.
This function uses the standard ERC20 ABI instead of fetching the contract ABI from the block explorer.
- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int) – The address of the ERC20 token.
- Returns:
A Contract instance for the ERC20 token.
- Return type:
- y.contracts.Contract_with_erc20_fallback(address)[source]
Create a Contract instance for an address, falling back to an ERC20 token if the contract is not verified.
- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int) – The address of the contract or ERC20 token.
- Returns:
A Contract instance for the contract address.
- Return type:
- ASyncFunctiony.contracts.build_name(address: str | hexbytes.main.HexBytes | AnyAddress | brownie.convert.datatypes.EthAddress | brownie.network.contract.Contract | int, return_None_on_failure: bool = False) str [source]
Get the build name of a contract.
- Args:
address: The address of the contract. return_None_on_failure (optional): If True, return None if the build name cannot be determined instead of raising an Exception. Default False.
- Returns:
The build name of the contract, or None if the build name cannot be determined and return_None_on_failure is True.
Since build_name is an
ASyncFunctionSyncDefault
, you can optionally pass sync=False or asynchronous=True to force it to return a coroutine. Without either kwarg, it will run synchronously.- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int)
return_None_on_failure (bool)
- Return type:
- ASyncFunctiony.contracts.contract_creation_block_async(address: str | hexbytes.main.HexBytes | AnyAddress | brownie.convert.datatypes.EthAddress | brownie.network.contract.Contract | int, when_no_history_return_0: bool = False) int [source]
Determine the block when a contract was created using binary search. NOTE Requires access to historical state. Doesn’t account for CREATE2 or SELFDESTRUCT.
- Args:
address: The address of the contract. when_no_history_return_0: If True, return 0 when no history is found instead of raising a
NodeNotSynced
exception. Default False.- Returns:
The block number at which the contract was created.
- Raises:
exceptions.NodeNotSynced: If the node is not fully synced. ValueError: If the contract creation block cannot be determined.
Since contract_creation_block_async is an
ASyncFunctionAsyncDefault
, you can optionally pass sync=True or asynchronous=False to force it to run synchronously and return a value. Without either kwarg, it will return a coroutine for you to await.- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int)
when_no_history_return_0 (bool)
- Return type:
- ASyncFunctiony.contracts.has_method(address: str | hexbytes.main.HexBytes | AnyAddress | brownie.convert.datatypes.EthAddress, method: str, return_response: bool = False) bool | Any [source]
Checks to see if a contract has a method view method with no inputs. return_response=True will return response in bytes if response else False
- Args:
address: The address of the contract. method: The name of the method to check for. return_response: If True, return the response of the method call instead of a boolean. Default False.
- Returns:
A boolean indicating whether the contract has the method, or the response of the method call if return_response is True.
Since has_method is an
ASyncFunctionSyncDefault
, you can optionally pass sync=False or asynchronous=True to force it to return a coroutine. Without either kwarg, it will run synchronously.- Parameters:
address (str | HexBytes | AnyAddress | EthAddress)
method (str)
return_response (bool)
- Return type:
- async y.contracts.has_methods(address, methods, _func=<built-in function all>)[source]
Checks to see if a contract has each view method (with no inputs) in methods. Pass at_least_one=True to only verify a contract has at least one of the methods.
Since has_methods is an
ASyncFunctionSyncDefault
, you can optionally pass sync=False or asynchronous=True to force it to return a coroutine. Without either kwarg, it will run synchronously.- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int)
_func (Callable)
- Return type:
- async y.contracts.probe(address, methods, block=None, return_method=False)[source]
- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int)
block (int | BlockNumber | None)
return_method (bool)
- Return type:
- async y.contracts.proxy_implementation(address, block)[source]
Get the implementation address for a proxy contract.
- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int) – The address of the proxy contract.
block (int | BlockNumber | None) – The block number at which to get the implementation address. Defaults to latest block.
- Returns:
The address of the implementation contract.
- Return type:
str | HexBytes | AnyAddress | EthAddress
y.convert module
- y.convert.to_address(address)[source]
- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int)
- Return type:
y.datatypes module
- class y.datatypes.UsdPrice[source]
Bases:
UsdValue
Represents a USD price.
- __add__(value, /)
Return self+value.
- __bool__()
True if self else False
- __eq__(value, /)
Return self==value.
- __floordiv__(value, /)
Return self//value.
- __ge__(value, /)
Return self>=value.
- __getattribute__(name, /)
Return getattr(self, name).
- __gt__(value, /)
Return self>value.
- __le__(value, /)
Return self<=value.
- __lt__(value, /)
Return self<value.
- __mul__(value, /)
Return self*value.
- __pow__(value, mod=None, /)
Return pow(self, value, mod).
- __radd__(value, /)
Return value+self.
- __str__()
Return a string representation of the USD value.
- Returns:
A string formatted as a USD value with 8 decimal places.
- Return type:
- __sub__(value, /)
Return self-value.
- __truediv__(value, /)
Return self/value.
- fromhex()
Create a floating-point number from a hexadecimal string.
>>> float.fromhex('0x1.ffffp10') 2047.984375 >>> float.fromhex('-0x1p-1074') -5e-324
- hex()
Return a hexadecimal representation of a floating-point number.
>>> (-0.1).hex() '-0x1.999999999999ap-4' >>> 3.14159.hex() '0x1.921f9f01b866ep+1'
- class y.datatypes.UsdValue[source]
Bases:
float
Represents a USD value with custom string representation.
- __add__(value, /)
Return self+value.
- __bool__()
True if self else False
- __eq__(value, /)
Return self==value.
- __floordiv__(value, /)
Return self//value.
- __ge__(value, /)
Return self>=value.
- __getattribute__(name, /)
Return getattr(self, name).
- __gt__(value, /)
Return self>value.
- __le__(value, /)
Return self<=value.
- __lt__(value, /)
Return self<value.
- __mul__(value, /)
Return self*value.
- __pow__(value, mod=None, /)
Return pow(self, value, mod).
- __radd__(value, /)
Return value+self.
- __str__()[source]
Return a string representation of the USD value.
- Returns:
A string formatted as a USD value with 8 decimal places.
- Return type:
- __sub__(value, /)
Return self-value.
- __truediv__(value, /)
Return self/value.
- fromhex()
Create a floating-point number from a hexadecimal string.
>>> float.fromhex('0x1.ffffp10') 2047.984375 >>> float.fromhex('-0x1p-1074') -5e-324
- hex()
Return a hexadecimal representation of a floating-point number.
>>> (-0.1).hex() '-0x1.999999999999ap-4' >>> 3.14159.hex() '0x1.921f9f01b866ep+1'
- y.datatypes.Address
A union of types used to represent Ethereum addresses.
alias of
str
|HexBytes
|AnyAddress
|EthAddress
- y.datatypes.AnyAddressType
A type alias representing any valid representation of an Ethereum address. This can be an Address, a
Contract
, or an integer.alias of
str
|HexBytes
|AnyAddress
|EthAddress
|Contract
|int
- y.datatypes.Block
A union of types used to represent block numbers as integers.
alias of
int
|BlockNumber
- y.datatypes.Pool
A union of types representing liquidity pools.
alias of
UniswapV2Pool
|CurvePool
y.exceptions module
- exception y.exceptions.CallReverted[source]
Bases:
Exception
Raised when a contract call is reverted.
- exception y.exceptions.CalldataPreparationError[source]
Bases:
Exception
Raised when there’s an error in preparing calldata for a contract interaction.
- exception y.exceptions.ContractNotVerified[source]
Bases:
_ExplorerError
Raised when attempting to fetch the ABI for an unverified contract from a block explorer.
- exception y.exceptions.InvalidAPIKeyError[source]
Bases:
_ExplorerError
Raised when the API key for the block explorer has been rejected. This typically occurs when making requests to a block explorer API with a missing, incorrect, or banned key.
- exception y.exceptions.MessedUpBrownieContract[source]
Bases:
Exception
Raised when there’s an issue initialized a Brownie contract instance, typically in the compilation step.
- exception y.exceptions.NoProxyImplementation[source]
Bases:
Exception
Raised when the implementation address of a proxy contract cannot be determined.
This may occur when trying to interact with proxy contracts that don’t follow standard patterns.
- exception y.exceptions.NonStandardERC20[source]
Bases:
Exception
Raised when an ERC20 token contract is expected but the provided address is not a standard ERC20 token.
- exception y.exceptions.NotABalancerV2Pool[source]
Bases:
Exception
Raised when a contract is incorrectly identified as a Balancer V2 pool.
- exception y.exceptions.NotAUniswapV2Pool[source]
Bases:
Exception
Raised when a contract is incorrectly identified as a Uniswap V2 pool.
- __init__(non_pool)[source]
- Parameters:
non_pool (UniswapV2Pool)
- exception y.exceptions.PriceError[source]
Bases:
Exception
Raised when a queried price is not found.
- exception y.exceptions.TokenError[source]
Bases:
ValueError
Raised when a token contract is not the correct contract type for the desired operation.
- __init__(token, desired_type, *optional_extra_args)[source]
- Parameters:
token (str | HexBytes | AnyAddress | EthAddress | Contract | int)
desired_type (str)
optional_extra_args (Any)
- exception y.exceptions.TokenNotFound[source]
Bases:
ValueError
Raised when a specified token cannot be found in a given container.
This is usually used when searching for a token in a liquidity pool.
- exception y.exceptions.UnsupportedNetwork[source]
Bases:
ValueError
Raised when an operation is attempted on an unsupported blockchain network.
- exception y.exceptions.yPriceMagicError[source]
Bases:
ValueError
Custom exception for ypricemagic-related errors.
This exception is raised when any error occurs inside of ypricemagic. For example, if a price fails to fetch or if there are unexpected Exceptions while calculating prices.
- block
The block that was queried when the error occurred.
- token
The token that caused the error.
y.networks module
- class y.networks.Network[source]
Bases:
IntEnum
A lightweight enum that enables lookup of chainids for popular blockchain networks.
Each network is associated with its unique integer Chain ID.
- __add__(value, /)
Return self+value.
- __and__(value, /)
Return self&value.
- __bool__()
True if self else False
- __eq__(value, /)
Return self==value.
- __floordiv__(value, /)
Return self//value.
- __ge__(value, /)
Return self>=value.
- __getattribute__(name, /)
Return getattr(self, name).
- __gt__(value, /)
Return self>value.
- __index__()
Return self converted to an integer, if self is suitable for use as an index into a list.
- __invert__()
~self
- __le__(value, /)
Return self<=value.
- __lshift__(value, /)
Return self<<value.
- __lt__(value, /)
Return self<value.
- __mul__(value, /)
Return self*value.
- __or__(value, /)
Return self|value.
- __pow__(value, mod=None, /)
Return pow(self, value, mod).
- __radd__(value, /)
Return value+self.
- __rand__(value, /)
Return value&self.
- __rlshift__(value, /)
Return value<<self.
- __ror__(value, /)
Return value|self.
- __rrshift__(value, /)
Return value>>self.
- __rshift__(value, /)
Return self>>value.
- __rxor__(value, /)
Return value^self.
- __sizeof__()
Returns size in memory, in bytes.
- __sub__(value, /)
Return self-value.
- __truediv__(value, /)
Return self/value.
- __xor__(value, /)
Return self^value.
- from_bytes(byteorder, *, signed=False)
Return the integer represented by the given array of bytes.
- bytes
Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.
- signed
Indicates whether two’s complement is used to represent the integer.
- to_bytes(length, byteorder, *, signed=False)
Return an array of bytes representing an integer.
- length
Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.
- signed
Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.
- Arbitrum = 42161
The Chain ID for Arbitrum One
- Aurora = 1313161554
The Chain ID for Aurora
- Avalanche = 43114
The Chain ID for Avalanche C-Chain
- Base = 8453
The Chain ID for Base
- BinanceSmartChain = 56
The Chain ID for Binance Smart Chain
- Cronos = 25
The Chain ID for Cronos Mainnet
- Fantom = 250
The Chain ID for Fantom Opera Network
- Gnosis = 100
The Chain ID for xDai Chain (now Gnosis Chain)
- Harmony = 1666600000
The Chain ID for Harmony Mainnet Shard 0
- Heco = 128
The Chain ID for Heco
- Mainnet = 1
The Chain ID for Ethereum Mainnet
- Moonriver = 1285
The Chain ID for Moonriver Network
- OKEx = 66
The Chain ID for OKEx Chain
- Optimism = 10
The Chain ID for Optimism
- Polygon = 137
The Chain ID for Polygon (formerly Matic) Network
- denominator
the denominator of a rational number in lowest terms
- numerator
the numerator of a rational number in lowest terms
- xDai = 100
The Chain ID for xDai Chain (now Gnosis Chain)
y.time module
- exception y.time.NoBlockFound[source]
Bases:
Exception
Raised when no block is found for a specified timestamp because the timestamp is in the future.
- ASyncFunctiony.time.closest_block_after_timestamp_async(timestamp: y.time.UnixTimestamp | datetime.datetime, wait_for_block_if_needed: bool = False) int [source]
Since closest_block_after_timestamp_async is an
ASyncFunctionAsyncDefault
, you can optionally pass sync=True or asynchronous=False to force it to run synchronously and return a value. Without either kwarg, it will return a coroutine for you to await.
- ASyncFunctiony.time.get_block_at_timestamp(timestamp: datetime.datetime) int [source]
Since get_block_at_timestamp is an
ASyncFunctionAsyncDefault
, you can optionally pass sync=True or asynchronous=False to force it to run synchronously and return a value. Without either kwarg, it will return a coroutine for you to await.
- ASyncFunctiony.time.get_block_timestamp_async(height: int) int [source]
Since get_block_timestamp_async is an
ASyncFunctionAsyncDefault
, you can optionally pass sync=True or asynchronous=False to force it to run synchronously and return a value. Without either kwarg, it will return a coroutine for you to await.
Module contents
- class y.Contract[source]
Bases:
Contract
Though it may look complicated, a ypricemagic Contract object is simply a brownie Contract object with a few modifications:
- Contracts will not be compiled. This allows you to more quickly fetch contracts from the block explorer and prevents you from having to download and install compilers.
NOTE: You must set autofetch_sources=false in your project’s brownie-config.yaml for this to work correctly.
- To each contract method, a coroutine property has been defined which allows you to make asynchronous calls which are intelligently batched in the background by
dank_mids
to reduce overhead. - Example:
>>> contract = Contract("0xAddress") >>> contract.methodName(*args, block_identifier=12345678) 1000000000000000000 >>> coro = contract.methodName.coroutine(*args, block_identifier=12345678) >>> coro <coroutine coroutine object at 0x12345678> >>> contract.methodName(*args, block_identifier=12345678) == await coro True
- To each contract method, a coroutine property has been defined which allows you to make asynchronous calls which are intelligently batched in the background by
- New methods:
- A few attributes were removed in order to minimize the size of a Contract object in memory:
ast
bytecode
coverageMap
deployedBytecode
deployedSourceMap
natspec
opcodes
pcMap
- __getattribute__(name)[source]
Get a contract method attribute.
This method implements lazy initialization of contract methods. If a method object does not yet exist, it is created and cached.
- Parameters:
name (str) – The name of the attribute to get.
- Returns:
The contract method object.
- Return type:
- __init__(address, owner=None, require_success=True, cache_ttl=<EnvironmentVariable[name=`YPRICEMAGIC_CONTRACT_CACHE_TTL`, type=int, default_value=3600, current_value=3600, using_default=True]>)[source]
Initialize the Contract instance.
This method sets up lazy initialization for contract methods.
- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int)
owner (AccountsType | None)
require_success (bool)
cache_ttl (int | None)
- Return type:
None
- async build_name(return_None_on_failure=False)[source]
Get the build name of the contract.
- Parameters:
return_None_on_failure (optional) – If True, return None if the build name cannot be determined instead of raising an Exception. Default False.
- Returns:
The build name of the contract, or None if the build name cannot be determined and return_None_on_failure is True.
- Return type:
str | None
- async classmethod coroutine(address, require_success=True, cache_ttl=<EnvironmentVariable[name=`YPRICEMAGIC_CONTRACT_CACHE_TTL`, type=int, default_value=3600, current_value=3600, using_default=True]>)[source]
- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int)
require_success (bool)
cache_ttl (int | None)
- Return type:
Self
- decode_input(calldata)
Decode input calldata for this contract.
- classmethod from_abi(name, address, abi, owner=None, persist=True, cache_ttl=<EnvironmentVariable[name=`YPRICEMAGIC_CONTRACT_CACHE_TTL`, type=int, default_value=3600, current_value=3600, using_default=True]>)[source]
Create a Contract instance from an ABI.
- Args:
name: The name of the contract. address: The address of the contract. abi: The ABI of the contract. owner (optional): The owner of the contract. Default None. persist (optional): If True, persist the contract in brownie’s local contract database. Default True. cache_ttl (optional): The time-to-live for the contract cache in seconds. Default set in
ENVIRONMENT_VARIABLES
.- Returns:
A Contract instance for the given ABI.
Since from_abi is an
ASyncFunctionSyncDefault
, you can optionally pass sync=False or asynchronous=True to force it to return a coroutine. Without either kwarg, it will run synchronously.
- classmethod from_ethpm(name, manifest_uri, address=None, owner=None, persist=True)[source]
Create a new Contract instance from an ethPM manifest.
This method allows for the creation of a Contract instance using an ethPM manifest, which is a standardized format for Ethereum smart contract packages.
- Parameters:
name (str) – The name of the contract.
manifest_uri (str) – The URI of the ethPM manifest.
address (str | None) – The address of the deployed contract (optional).
owner (AccountsType | None) – The account that owns this contract instance.
persist (bool) – Whether to persist the contract data to brownie’s local db for future use.
- Returns:
A new Contract instance.
- Return type:
- classmethod from_explorer(address, as_proxy_for=None, owner=None, silent=False, persist=True)[source]
Create a new Contract instance by fetching the ABI from a block explorer.
This method is useful for interacting with contracts that are not part of the current project, as it automatically fetches the contract’s ABI from a block explorer.
- Parameters:
address (str) – The address of the deployed contract.
as_proxy_for (str | None) – The address of the implementation contract if this is a proxy contract.
owner (AccountsType | None) – The account that owns this contract instance.
silent (bool) – Whether to suppress console output during the process.
persist (bool) – Whether to persist the contract data to brownie’s db for future use.
- Returns:
A new Contract instance.
- Return type:
- async get_code(block=None)[source]
Get the bytecode of the contract at a specific block.
- Parameters:
block (optional) – The block number at which to get the bytecode. Defaults to latest block.
- Returns:
The bytecode of the contract at the specified block.
- Return type:
- get_method_object(calldata)
Given a calldata hex string, returns a ContractMethod object.
- Parameters:
calldata (str)
- Return type:
_ContractMethod | None
- classmethod get_solc_version(compiler_str, address)[source]
Return the solc compiler version either from the passed compiler string or try to find the latest available patch semver compiler version.
- has_method(method, return_response=False)[source]
Check if the contract has a specific method.
- Parameters:
method (str) – The name of the method to check for.
return_response (optional) – If True, return the response of the method call instead of a boolean. Default False.
- Returns:
A boolean indicating whether the contract has the method, or the response of the method call if return_response is True.
- Return type:
- async has_methods(methods, _func=<built-in function all>)[source]
Check if the contract has all the specified methods.
- info()
Display NatSpec documentation for this contract.
- Return type:
None
- classmethod remove_deployment(address=None, alias=None)[source]
Removes this contract from the internal deployments db with the passed address or alias.
- set_alias(alias, persist=True)[source]
Apply a unique alias this object. The alias can be used to restore the object in future sessions.
- events: ContractEvents
A container for various event types associated with this contract.
Provides a convenient way to query contract events with minimal code.
- signatures: Dict[Method, Signature]
A dictionary mapping method names to their corresponding signatures.
- verified = True
True if the contract is verified on this network’s block explorer. False otherwise.
- class y.ERC20[source]
Bases:
ContractBase
Represents an ERC20 token.
- ASyncFunction_decimals(block: int | eth_typing.evm.BlockNumber | NoneType = None) int [source]
used to fetch decimals at specific block
Since _decimals is an
ASyncFunctionAsyncDefault
, you can optionally pass sync=True or asynchronous=False to force it to run synchronously and return a value. Without either kwarg, it will return a coroutine for you to await.- Parameters:
block (int | BlockNumber | None)
- Return type:
- ASyncFunction_scale(block: int | eth_typing.evm.BlockNumber | NoneType = None) int [source]
Since _scale is an
ASyncFunctionAsyncDefault
, you can optionally pass sync=True or asynchronous=False to force it to run synchronously and return a value. Without either kwarg, it will return a coroutine for you to await.- Parameters:
block (int | BlockNumber | None)
- Return type:
- __eq__(_ContractBase__o)
Return self==value.
- __init__(address, asynchronous=False, _deploy_block=None)
- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int)
asynchronous (bool)
_deploy_block (int | None)
- Return type:
None
- __str__()
Return the contract address as a string.
- Returns:
The contract address as a string.
- Return type:
- __build_name__: HiddenMethodDescriptor[Self, str]
Asynchronously retrieves the property value.
- Args:
instance: The instance from which the property is accessed. owner: The owner class of the property.
- Returns:
The property value.
The original docstring for
get()
is shown below:Asynchronously retrieves the property value.
- Args:
instance: The instance from which the property is accessed. owner: The owner class of the property.
- Returns:
The property value.
- __decimals__: HiddenMethodDescriptor[Self, int]
Asynchronously retrieves the property value.
- Args:
instance: The instance from which the property is accessed. owner: The owner class of the property.
- Returns:
The property value.
The original docstring for
get()
is shown below:Asynchronously retrieves the property value.
- Args:
instance: The instance from which the property is accessed. owner: The owner class of the property.
- Returns:
The property value.
- __name__: HiddenMethodDescriptor[Self, str] = 'ERC20'
- __scale__: HiddenMethodDescriptor[Self, int]
Asynchronously retrieves the property value.
- Args:
instance: The instance from which the property is accessed. owner: The owner class of the property.
- Returns:
The property value.
The original docstring for
get()
is shown below:Asynchronously retrieves the property value.
- Args:
instance: The instance from which the property is accessed. owner: The owner class of the property.
- Returns:
The property value.
- __symbol__: HiddenMethodDescriptor[Self, str]
Asynchronously retrieves the property value.
- Args:
instance: The instance from which the property is accessed. owner: The owner class of the property.
- Returns:
The property value.
The original docstring for
get()
is shown below:Asynchronously retrieves the property value.
- Args:
instance: The instance from which the property is accessed. owner: The owner class of the property.
- Returns:
The property value.
- address: str | HexBytes | AnyAddress | EthAddress
The contract address of the token.
- balance_of[source]
Query the balance of the token for a given address at a specific block.
- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int) – The address to query.
block (optional) – The block number to query. Defaults to latest block.
- Returns:
The balance of the token held by address at block block.
- Return type:
- balance_of_readable[source]
- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int)
block (int | BlockNumber | None)
- Return type:
- build_name
Get the contract’s build name.
- Returns:
The contract’s build name.
- decimals[source]
The number of decimal places for the token.
- Returns:
The number of decimal places for the token.
- deploy_block: ASyncBoundMethod[Self, Any, int]
- price[source]
Get the price of the token in USD.
- Parameters:
block (optional) – The block number to query. Defaults to latest block.
return_None_on_failure (bool) – If True, return None instead of raising a
yPriceMagicError
on failure.skip_cache (bool) – If True, skip using the cache while fetching price data.
ignore_pools (Tuple[UniswapV2Pool | CurvePool, ...]) – An optional tuple of pools to ignore when calculating the price.
- Returns:
The price of the token in USD, or None if return_None_on_failure is True and the price cannot be retrieved.
- Raises:
yPriceMagicError – If return_None_on_failure is False and the price cannot be retrieved.
- Return type:
UsdPrice | None
- class y.Network[source]
Bases:
IntEnum
A lightweight enum that enables lookup of chainids for popular blockchain networks.
Each network is associated with its unique integer Chain ID.
- __add__(value, /)
Return self+value.
- __and__(value, /)
Return self&value.
- __bool__()
True if self else False
- __eq__(value, /)
Return self==value.
- __floordiv__(value, /)
Return self//value.
- __ge__(value, /)
Return self>=value.
- __getattribute__(name, /)
Return getattr(self, name).
- __gt__(value, /)
Return self>value.
- __index__()
Return self converted to an integer, if self is suitable for use as an index into a list.
- __invert__()
~self
- __le__(value, /)
Return self<=value.
- __lshift__(value, /)
Return self<<value.
- __lt__(value, /)
Return self<value.
- __mul__(value, /)
Return self*value.
- __or__(value, /)
Return self|value.
- __pow__(value, mod=None, /)
Return pow(self, value, mod).
- __radd__(value, /)
Return value+self.
- __rand__(value, /)
Return value&self.
- __rlshift__(value, /)
Return value<<self.
- __ror__(value, /)
Return value|self.
- __rrshift__(value, /)
Return value>>self.
- __rshift__(value, /)
Return self>>value.
- __rxor__(value, /)
Return value^self.
- __sizeof__()
Returns size in memory, in bytes.
- __sub__(value, /)
Return self-value.
- __truediv__(value, /)
Return self/value.
- __xor__(value, /)
Return self^value.
- from_bytes(byteorder, *, signed=False)
Return the integer represented by the given array of bytes.
- bytes
Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.
- signed
Indicates whether two’s complement is used to represent the integer.
- to_bytes(length, byteorder, *, signed=False)
Return an array of bytes representing an integer.
- length
Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.
- signed
Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.
- Arbitrum = 42161
The Chain ID for Arbitrum One
- Aurora = 1313161554
The Chain ID for Aurora
- Avalanche = 43114
The Chain ID for Avalanche C-Chain
- Base = 8453
The Chain ID for Base
- BinanceSmartChain = 56
The Chain ID for Binance Smart Chain
- Cronos = 25
The Chain ID for Cronos Mainnet
- Fantom = 250
The Chain ID for Fantom Opera Network
- Gnosis = 100
The Chain ID for xDai Chain (now Gnosis Chain)
- Harmony = 1666600000
The Chain ID for Harmony Mainnet Shard 0
- Heco = 128
The Chain ID for Heco
- Mainnet = 1
The Chain ID for Ethereum Mainnet
- Moonriver = 1285
The Chain ID for Moonriver Network
- OKEx = 66
The Chain ID for OKEx Chain
- Optimism = 10
The Chain ID for Optimism
- Polygon = 137
The Chain ID for Polygon (formerly Matic) Network
- denominator
the denominator of a rational number in lowest terms
- numerator
the numerator of a rational number in lowest terms
- xDai = 100
The Chain ID for xDai Chain (now Gnosis Chain)
- ASyncFunctiony.balanceOf(call_address: str | hexbytes.main.HexBytes | AnyAddress | brownie.convert.datatypes.EthAddress | brownie.network.contract.Contract, input_address: str | hexbytes.main.HexBytes | AnyAddress | brownie.convert.datatypes.EthAddress | brownie.network.contract.Contract, block: int | eth_typing.evm.BlockNumber | NoneType = None, return_None_on_failure: bool = False) int | None [source]
Since balanceOf is an
ASyncFunctionSyncDefault
, you can optionally pass sync=False or asynchronous=True to force it to return a coroutine. Without either kwarg, it will run synchronously.- Parameters:
call_address (str | HexBytes | AnyAddress | EthAddress | Contract)
input_address (str | HexBytes | AnyAddress | EthAddress | Contract)
block (int | BlockNumber | None)
return_None_on_failure (bool)
- Return type:
int | None
- ASyncFunctiony.check_bucket(token: str | hexbytes.main.HexBytes | AnyAddress | brownie.convert.datatypes.EthAddress | brownie.network.contract.Contract | int) str [source]
Since check_bucket is an
ASyncFunctionSyncDefault
, you can optionally pass sync=False or asynchronous=True to force it to return a coroutine. Without either kwarg, it will run synchronously.- Parameters:
token (str | HexBytes | AnyAddress | EthAddress | Contract | int)
- Return type:
- ASyncFunctiony.contract_creation_block_async(address: str | hexbytes.main.HexBytes | AnyAddress | brownie.convert.datatypes.EthAddress | brownie.network.contract.Contract | int, when_no_history_return_0: bool = False) int [source]
Determine the block when a contract was created using binary search. NOTE Requires access to historical state. Doesn’t account for CREATE2 or SELFDESTRUCT.
- Args:
address: The address of the contract. when_no_history_return_0: If True, return 0 when no history is found instead of raising a
NodeNotSynced
exception. Default False.- Returns:
The block number at which the contract was created.
- Raises:
exceptions.NodeNotSynced: If the node is not fully synced. ValueError: If the contract creation block cannot be determined.
Since contract_creation_block_async is an
ASyncFunctionAsyncDefault
, you can optionally pass sync=True or asynchronous=False to force it to run synchronously and return a value. Without either kwarg, it will return a coroutine for you to await.- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int)
when_no_history_return_0 (bool)
- Return type:
- ASyncFunctiony.fetch_multicall(*calls: Any, block: int | eth_typing.evm.BlockNumber | NoneType = None) List[Any | None] [source]
Since fetch_multicall is an
ASyncFunctionSyncDefault
, you can optionally pass sync=False or asynchronous=True to force it to return a coroutine. Without either kwarg, it will run synchronously.- Parameters:
calls (Any)
block (int | BlockNumber | None)
- Return type:
- ASyncFunctiony.get_block_at_timestamp(timestamp: datetime.datetime) int [source]
Since get_block_at_timestamp is an
ASyncFunctionAsyncDefault
, you can optionally pass sync=True or asynchronous=False to force it to run synchronously and return a value. Without either kwarg, it will return a coroutine for you to await.
- ASyncFunctiony.get_block_timestamp_async(height: int) int [source]
Since get_block_timestamp_async is an
ASyncFunctionAsyncDefault
, you can optionally pass sync=True or asynchronous=False to force it to run synchronously and return a value. Without either kwarg, it will return a coroutine for you to await.
- ASyncFunctiony.get_price(token_address: Union[str, hexbytes.main.HexBytes, ~AnyAddress, brownie.convert.datatypes.EthAddress, brownie.network.contract.Contract, int], block: Union[int, eth_typing.evm.BlockNumber, NoneType] = None, *, fail_to_None: bool = False, skip_cache: bool = <EnvironmentVariable[name=`YPRICEMAGIC_SKIP_CACHE`, type=bool, default_value=False, current_value=False, using_default=True]>, ignore_pools: Tuple[Union[ForwardRef('UniswapV2Pool'), ForwardRef('CurvePool')], ...] = (), silent: bool = False) y.datatypes.UsdPrice | None [source]
Get the price of a token in USD.
- Args:
token_address: The address of the token to price. block (optional): The block number at which to get the price. If None, uses the latest block. fail_to_None (optional): If True, return None instead of raising a
yPriceMagicError
on failure. Default False. skip_cache (optional): If True, bypass the cache and fetch the price directly. Defaults toENVS.SKIP_CACHE
. ignore_pools (optional): A tuple of pool addresses to ignore when fetching the price. silent (optional): If True, suppress error logging. Default False.- Returns:
The price of the token in USD, or None if the price couldn’t be determined and fail_to_None is True.
- Raises:
yPriceMagicError: If the price couldn’t be determined and fail_to_None is False.
- Note:
Don’t pass an int like 123 into token_address please, that’s just silly. - ypricemagic accepts ints to allow you to pass y.get_price(0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e)
so you can save yourself some keystrokes while testing in a console
(as opposed to y.get_price(“0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e”))
Since get_price is an
ASyncFunctionSyncDefault
, you can optionally pass sync=False or asynchronous=True to force it to return a coroutine. Without either kwarg, it will run synchronously.- Parameters:
token_address (str | HexBytes | AnyAddress | EthAddress | Contract | int)
block (int | BlockNumber | None)
fail_to_None (bool)
skip_cache (bool)
ignore_pools (Tuple[UniswapV2Pool | CurvePool, ...])
silent (bool)
- Return type:
UsdPrice | None
- ASyncFunctiony.get_prices(token_addresses: Iterable[Union[str, hexbytes.main.HexBytes, ~AnyAddress, brownie.convert.datatypes.EthAddress, brownie.network.contract.Contract, int]], block: Union[int, eth_typing.evm.BlockNumber, NoneType] = None, *, fail_to_None: bool = False, skip_cache: bool = <EnvironmentVariable[name=`YPRICEMAGIC_SKIP_CACHE`, type=bool, default_value=False, current_value=False, using_default=True]>, silent: bool = False) List[y.datatypes.UsdPrice | None] [source]
Get prices for multiple tokens in USD.
You should use this function over
get_price()
where possible, it is better optimized for parallel execution.- Args:
token_addresses: An iterable of token addresses to price. block (optional): The block number at which to get the prices. Defaults to the latest block. fail_to_None (optional): If True, return None for tokens whose price couldn’t be determined. Default False. skip_cache (optional): If True, bypass the cache and fetch prices directly. Defaults to
ENVS.SKIP_CACHE
. silent (optional): If True, suppress progress bar and error logging. This kwarg is not currently implemented.- Returns:
A list of token prices in USD, in the same order as the input token_addresses.
Since get_prices is an
ASyncFunctionSyncDefault
, you can optionally pass sync=False or asynchronous=True to force it to return a coroutine. Without either kwarg, it will run synchronously.- Parameters:
token_addresses (Iterable[str | HexBytes | AnyAddress | EthAddress | Contract | int])
block (int | BlockNumber | None)
fail_to_None (bool)
skip_cache (bool)
silent (bool)
- Return type:
- ASyncFunctiony.has_method(address: str | hexbytes.main.HexBytes | AnyAddress | brownie.convert.datatypes.EthAddress, method: str, return_response: bool = False) bool | Any [source]
Checks to see if a contract has a method view method with no inputs. return_response=True will return response in bytes if response else False
- Args:
address: The address of the contract. method: The name of the method to check for. return_response: If True, return the response of the method call instead of a boolean. Default False.
- Returns:
A boolean indicating whether the contract has the method, or the response of the method call if return_response is True.
Since has_method is an
ASyncFunctionSyncDefault
, you can optionally pass sync=False or asynchronous=True to force it to return a coroutine. Without either kwarg, it will run synchronously.- Parameters:
address (str | HexBytes | AnyAddress | EthAddress)
method (str)
return_response (bool)
- Return type:
- async y.has_methods(address, methods, _func=<built-in function all>)[source]
Checks to see if a contract has each view method (with no inputs) in methods. Pass at_least_one=True to only verify a contract has at least one of the methods.
Since has_methods is an
ASyncFunctionSyncDefault
, you can optionally pass sync=False or asynchronous=True to force it to return a coroutine. Without either kwarg, it will run synchronously.- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int)
_func (Callable)
- Return type:
- y.map_prices(token_addresses, block, *, fail_to_None=False, skip_cache=<EnvironmentVariable[name=`YPRICEMAGIC_SKIP_CACHE`, type=bool, default_value=False, current_value=False, using_default=True]>, silent=False)[source]
Map token addresses to their prices asynchronously.
- Parameters:
token_addresses (Iterable[str | HexBytes | AnyAddress | EthAddress | Contract | int]) – An iterable of token addresses to price.
block (optional) – The block number at which to get the prices. Defaults to latest block.
fail_to_None (optional) – If True, map to None for tokens whose price couldn’t be determined. Default False.
skip_cache (optional) – If True, bypass the cache and fetch prices directly. Defaults to
ENVS.SKIP_CACHE
.silent (optional) – If True, suppress error logging. Default False.
- Returns:
An
a_sync.TaskMapping
object mapping token addresses to their prices.- Return type:
TaskMapping[str | HexBytes | AnyAddress | EthAddress | Contract | int, UsdPrice | None]
- ASyncFunctiony.raw_call(contract_address: str | hexbytes.main.HexBytes | AnyAddress | brownie.convert.datatypes.EthAddress | brownie.network.contract.Contract, method: str, block: int | eth_typing.evm.BlockNumber | NoneType = None, inputs=None, output: str = None, return_None_on_failure: bool = False) Any | None [source]
call a contract with only address and method. Bypasses brownie Contract object formation to save time only works with 1 input, ie balanceOf(address) or getPoolInfo(uint256)
Since raw_call is an
ASyncFunctionSyncDefault
, you can optionally pass sync=False or asynchronous=True to force it to return a coroutine. Without either kwarg, it will run synchronously.- Parameters:
contract_address (str | HexBytes | AnyAddress | EthAddress | Contract)
method (str)
block (int | BlockNumber | None)
output (str)
return_None_on_failure (bool)
- Return type:
Any | None