Welcome to ypricemagic’s documentation!
Time to price some shitcoins!
There is a lot of stuff in ypricemagic’s docs that you probably won’t need as a typical user. I’ve collected the most interesting components of the library here for your convenience.
The main use case for this library is the pricing of shitcoins. y.get_price handles that for you.
- y.get_price(token_address: AnyAddressType, block: Block | None = None, *, fail_to_None: Literal[True], skip_cache: bool = ENVS.SKIP_CACHE, ignore_pools: Tuple[Pool, ...] = (), silent: bool = False) UsdPrice | None [source]
- y.get_price(token_address: AnyAddressType, block: Block | None = None, *, fail_to_None: bool = False, skip_cache: bool = ENVS.SKIP_CACHE, ignore_pools: Tuple[Pool, ...] = (), silent: bool = False) UsdPrice
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.
If you do not know the block number but you know the timestamp at which you need your price, you first need to calculate it using this function:
- y.get_block_at_timestamp(timestamp)[source]
Get the block number just before a specific timestamp.
This function returns the block number at the given timestamp, which is the block number just before the specified timestamp.
- Args:
timestamp: The timestamp to find the block for.
- Returns:
The block number just before the given timestamp.
- Example:
>>> await get_block_at_timestamp(datetime.datetime(2023, 1, 1)) 12345678
- See Also:
get_block_timestamp()
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.
Usually, if you need one price you need more than one. The next two functions enable you to price multiple tokens in a streamlined, concurrent manner.
- y.get_prices(token_addresses: Iterable[AnyAddressType], block: Block | None = None, *, fail_to_None: Literal[True], skip_cache: bool = ENVS.SKIP_CACHE, silent: bool = False) List[UsdPrice | None] [source]
- y.get_prices(token_addresses: Iterable[AnyAddressType], block: Block | None = None, *, fail_to_None: bool = False, skip_cache: bool = ENVS.SKIP_CACHE, silent: bool = False) List[UsdPrice]
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.
- y.map_prices(token_addresses: Iterable[str | HexBytes | AnyAddress | EthAddress | Contract | int], block: int | BlockNumber, *, fail_to_None: Literal[True], skip_cache: bool = ENVS.SKIP_CACHE, silent: bool = False) TaskMapping[str | HexBytes | AnyAddress | EthAddress | Contract | int, UsdPrice | None] [source]
- y.map_prices(token_addresses: Iterable[str | HexBytes | AnyAddress | EthAddress | Contract | int], block: int | BlockNumber, *, fail_to_None: bool = False, skip_cache: bool = ENVS.SKIP_CACHE, silent: bool = False) TaskMapping[str | HexBytes | AnyAddress | EthAddress | Contract | int, UsdPrice]
Map token addresses to their prices asynchronously.
- Parameters:
token_addresses – 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.
There are some powerful tools for interacting with deployed contracts in the contracts module.
- class y.contracts.Contract[source]
A
Contract
object with several modifications for enhanced functionality.This class provides a modified contract object with additional features and optimizations:
- 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. This is enabled by inheriting from
Contract
, which provides the coroutine method for eachContractCall
object. These asynchronous calls are intelligently batched in the background bydank_mids
to reduce overhead.- 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
Examples
>>> 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
- __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 a
Contract
instance.Note
autofetch-sources: false
- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int) – The address of the contract.
owner (optional) – The owner of the contract. Default None.
require_success (optional) – If True, require successful contract verification. Default True.
cache_ttl (optional) – The time-to-live for the contract cache in seconds. Default set in
ENVIRONMENT_VARIABLES
.
- Raises:
ContractNotFound – If the address is not a contract.
exceptions.ContractNotVerified – If the contract is not verified and require_success is True.
- Return type:
None
- __post_init__(cache_ttl=None)[source]
Get rid of the contract call objects so we can materialize them on a JIT basis.
This method sets up lazy initialization for contract methods.
- Parameters:
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.
- Return type:
str | None
Example
>>> contract = Contract("0x6B175474E89094C44Da98b954EedeAC495271d0F") >>> await contract.build_name() 'Dai Stablecoin'
- async classmethod coroutine(address, owner=None, persist=True, require_success=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 asynchronously.- Parameters:
address (str | HexBytes | AnyAddress | EthAddress | Contract | int) – The address 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.
require_success (optional) – If True, require successful contract verification. Default True.
cache_ttl (optional) – The time-to-live for the contract cache in seconds. Default set in
ENVIRONMENT_VARIABLES
.
- Return type:
Self
Example
>>> contract = await Contract.coroutine("0x6B175474E89094C44Da98b954EedeAC495271d0F") >>> contract.symbol() 'DAI'
- 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
.- Example:
>>> abi = [{"constant":True,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":False,"stateMutability":"view","type":"function"}] >>> contract = Contract.from_abi("MyContract", "0x6B175474E89094C44Da98b954EedeAC495271d0F", abi) >>> contract.name() 'Dai Stablecoin'
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.
- Return type:
Example
>>> contract = Contract("0x6B175474E89094C44Da98b954EedeAC495271d0F") >>> await contract.get_code() HexBytes('0x...')
- 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.
- Return type:
Example
>>> contract = Contract("0x6B175474E89094C44Da98b954EedeAC495271d0F") >>> contract.has_method("name()") True
- async has_methods(methods, _func=<built-in function all>)[source]
Check if the contract has all the specified methods.
- Parameters:
- Return type:
Example
>>> contract = Contract("0x6B175474E89094C44Da98b954EedeAC495271d0F") >>> await contract.has_methods(["name()", "symbol()"]) True
- 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]
-
- __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:
Example
>>> contract = Contract_erc20("0x6B175474E89094C44Da98b954EedeAC495271d0F") >>> contract.name() 'Dai Stablecoin'
- 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:
Example
>>> contract = Contract_with_erc20_fallback("0x6B175474E89094C44Da98b954EedeAC495271d0F") >>> contract.symbol() 'DAI'
- 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.
- Example:
>>> await build_name("0x6B175474E89094C44Da98b954EedeAC495271d0F") 'Dai Stablecoin'
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.- Raises:
exceptions.NodeNotSynced: If the node is not fully synced. ValueError: If the contract creation block cannot be determined.
- Example:
>>> block = await contract_creation_block_async("0x6B175474E89094C44Da98b954EedeAC495271d0F") >>> print(block) 1234567
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.
- Example:
>>> await has_method("0x6B175474E89094C44Da98b954EedeAC495271d0F", "name()") 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.
- Return type:
str | HexBytes | AnyAddress | EthAddress
Example
>>> await proxy_implementation("0x6B175474E89094C44Da98b954EedeAC495271d0F") '0x1234567890abcdef1234567890abcdef12345678'
To learn about the rest of ypricemagic’s capabilities, navigate the library structure below.