code
stringlengths 66
870k
| docstring
stringlengths 19
26.7k
| func_name
stringlengths 1
138
| language
stringclasses 1
value | repo
stringlengths 7
68
| path
stringlengths 5
324
| url
stringlengths 46
389
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def test_varlib_gvar_explicit_delta(self):
"""The variable font contains a composite glyph odieresis which does not
need a gvar entry.
"""
test_name = "BuildGvarCompositeExplicitDelta"
self._run_varlib_build_test(
designspace_name=test_name,
font_name="TestFamily4",
tables=["gvar"],
expected_ttx_name=test_name,
)
|
The variable font contains a composite glyph odieresis which does not
need a gvar entry.
|
test_varlib_gvar_explicit_delta
|
python
|
fonttools/fonttools
|
Tests/varLib/varLib_test.py
|
https://github.com/fonttools/fonttools/blob/master/Tests/varLib/varLib_test.py
|
MIT
|
def test_kerning_merging(self):
"""Test the correct merging of class-based pair kerning.
Problem description at https://github.com/fonttools/fonttools/pull/1638.
Test font and Designspace generated by
https://gist.github.com/madig/183d0440c9f7d05f04bd1280b9664bd1.
"""
ds_path = self.get_test_input("KerningMerging.designspace")
ttx_dir = self.get_test_input("master_kerning_merging")
ds = DesignSpaceDocument.fromfile(ds_path)
for source in ds.sources:
ttx_dump = TTFont()
ttx_dump.importXML(
os.path.join(
ttx_dir, os.path.basename(source.filename).replace(".ttf", ".ttx")
)
)
source.font = reload_font(ttx_dump)
varfont, _, _ = build(ds)
varfont = reload_font(varfont)
class_kerning_tables = [
t
for l in varfont["GPOS"].table.LookupList.Lookup
for t in l.SubTable
if t.Format == 2
]
assert len(class_kerning_tables) == 1
class_kerning_table = class_kerning_tables[0]
# Test that no class kerned against class zero (containing all glyphs not
# classed) has a `XAdvDevice` table attached, which in the variable font
# context is a "VariationIndex" table and points to kerning deltas in the GDEF
# table. Variation deltas of any kerning class against class zero should
# probably never exist.
for class1_record in class_kerning_table.Class1Record:
class2_zero = class1_record.Class2Record[0]
assert getattr(class2_zero.Value1, "XAdvDevice", None) is None
# Assert the variable font's kerning table (without deltas) is equal to the
# default font's kerning table. The bug fixed in
# https://github.com/fonttools/fonttools/pull/1638 caused rogue kerning
# values to be written to the variable font.
assert _extract_flat_kerning(varfont, class_kerning_table) == {
("A", ".notdef"): 0,
("A", "A"): 0,
("A", "B"): -20,
("A", "C"): 0,
("A", "D"): -20,
("B", ".notdef"): 0,
("B", "A"): 0,
("B", "B"): 0,
("B", "C"): 0,
("B", "D"): 0,
}
instance_thin = instantiateVariableFont(varfont, {"wght": 100})
instance_thin_kerning_table = (
instance_thin["GPOS"].table.LookupList.Lookup[0].SubTable[0]
)
assert _extract_flat_kerning(instance_thin, instance_thin_kerning_table) == {
("A", ".notdef"): 0,
("A", "A"): 0,
("A", "B"): 0,
("A", "C"): 10,
("A", "D"): 0,
("B", ".notdef"): 0,
("B", "A"): 0,
("B", "B"): 0,
("B", "C"): 10,
("B", "D"): 0,
}
instance_black = instantiateVariableFont(varfont, {"wght": 900})
instance_black_kerning_table = (
instance_black["GPOS"].table.LookupList.Lookup[0].SubTable[0]
)
assert _extract_flat_kerning(instance_black, instance_black_kerning_table) == {
("A", ".notdef"): 0,
("A", "A"): 0,
("A", "B"): 0,
("A", "C"): 0,
("A", "D"): 40,
("B", ".notdef"): 0,
("B", "A"): 0,
("B", "B"): 0,
("B", "C"): 0,
("B", "D"): 40,
}
|
Test the correct merging of class-based pair kerning.
Problem description at https://github.com/fonttools/fonttools/pull/1638.
Test font and Designspace generated by
https://gist.github.com/madig/183d0440c9f7d05f04bd1280b9664bd1.
|
test_kerning_merging
|
python
|
fonttools/fonttools
|
Tests/varLib/varLib_test.py
|
https://github.com/fonttools/fonttools/blob/master/Tests/varLib/varLib_test.py
|
MIT
|
def test_composite_glyph_not_in_gvar(self, varfont):
"""The 'minus' glyph is a composite glyph, which references 'hyphen' as a
component, but has no tuple variations in gvar table, so the component offset
and the phantom points do not change; however the sidebearings and bounding box
do change as a result of the parent glyph 'hyphen' changing.
"""
hmtx = varfont["hmtx"]
vmtx = varfont["vmtx"]
hyphenCoords = _get_coordinates(varfont, "hyphen")
assert hyphenCoords == [
(40, 229),
(40, 307),
(282, 307),
(282, 229),
(0, 0),
(322, 0),
(0, 536),
(0, 0),
]
assert hmtx["hyphen"] == (322, 40)
assert vmtx["hyphen"] == (536, 229)
minusCoords = _get_coordinates(varfont, "minus")
assert minusCoords == [(0, 0), (0, 0), (422, 0), (0, 536), (0, 0)]
assert hmtx["minus"] == (422, 40)
assert vmtx["minus"] == (536, 229)
location = instancer.NormalizedAxisLimits(wght=-1.0, wdth=-1.0)
instancer.instantiateGvar(varfont, location)
# check 'hyphen' coordinates changed
assert _get_coordinates(varfont, "hyphen") == [
(26, 259),
(26, 286),
(237, 286),
(237, 259),
(0, 0),
(263, 0),
(0, 536),
(0, 0),
]
# check 'minus' coordinates (i.e. component offset and phantom points)
# did _not_ change
assert _get_coordinates(varfont, "minus") == minusCoords
assert hmtx["hyphen"] == (263, 26)
assert vmtx["hyphen"] == (536, 250)
assert hmtx["minus"] == (422, 26) # 'minus' left sidebearing changed
assert vmtx["minus"] == (536, 250) # 'minus' top sidebearing too
|
The 'minus' glyph is a composite glyph, which references 'hyphen' as a
component, but has no tuple variations in gvar table, so the component offset
and the phantom points do not change; however the sidebearings and bounding box
do change as a result of the parent glyph 'hyphen' changing.
|
test_composite_glyph_not_in_gvar
|
python
|
fonttools/fonttools
|
Tests/varLib/instancer/instancer_test.py
|
https://github.com/fonttools/fonttools/blob/master/Tests/varLib/instancer/instancer_test.py
|
MIT
|
def test_rounds_before_iup():
"""Regression test for fonttools/fonttools#3634, with TTX based on
reproduction process there."""
varfont = ttLib.TTFont()
varfont.importXML(os.path.join(TESTDATA, "3634-VF.ttx"))
# Instantiate at a new default position, sufficient to cause differences
# when unrounded but not when rounded.
partial = instancer.instantiateVariableFont(varfont, {"wght": (401, 401, 900)})
# Save and reload actual result to recalculate bounding box values, etc.
bytes_out = BytesIO()
partial.save(bytes_out)
bytes_out.seek(0)
partial = ttLib.TTFont(bytes_out)
# Load expected result, then save and reload to normalise TTX output.
expected = ttLib.TTFont()
expected.importXML(os.path.join(TESTDATA, "test_results", "3634-VF-partial.ttx"))
bytes_out = BytesIO()
expected.save(bytes_out)
bytes_out.seek(0)
expected = ttLib.TTFont(bytes_out)
# Serialise actual and expected to TTX strings, and compare.
string_out = StringIO()
partial.saveXML(string_out)
partial_ttx = stripVariableItemsFromTTX(string_out.getvalue())
string_out = StringIO()
expected.saveXML(string_out)
expected_ttx = stripVariableItemsFromTTX(string_out.getvalue())
assert partial_ttx == expected_ttx
|
Regression test for fonttools/fonttools#3634, with TTX based on
reproduction process there.
|
test_rounds_before_iup
|
python
|
fonttools/fonttools
|
Tests/varLib/instancer/instancer_test.py
|
https://github.com/fonttools/fonttools/blob/master/Tests/varLib/instancer/instancer_test.py
|
MIT
|
def handle_ape_exception(err: ApeException, base_paths: Iterable[Union[Path, str]]) -> bool:
"""
Handle a transaction error by showing relevant stack frames,
including custom contract frames added to the exception.
This method must be called within an ``except`` block or with
an exception on the exc-stack.
Args:
err (:class:`~ape.exceptions.TransactionError`): The transaction error
being handled.
base_paths (Optional[Iterable[Union[Path, str]]]): Optionally include additional
source-path prefixes to use when finding relevant frames.
Returns:
bool: ``True`` if outputted something.
"""
home_str = str(Path.home())
if not (relevant_frames := _get_relevant_frames(base_paths)):
return False
formatted_tb = [x.replace(home_str, "$HOME") for x in relevant_frames]
rich_print(f"\n{''.join(formatted_tb)}")
# Prevent double logging of a traceback by using `show_traceback=False`.
logger.error(Abort.from_ape_exception(err, show_traceback=False))
return True
|
Handle a transaction error by showing relevant stack frames,
including custom contract frames added to the exception.
This method must be called within an ``except`` block or with
an exception on the exc-stack.
Args:
err (:class:`~ape.exceptions.TransactionError`): The transaction error
being handled.
base_paths (Optional[Iterable[Union[Path, str]]]): Optionally include additional
source-path prefixes to use when finding relevant frames.
Returns:
bool: ``True`` if outputted something.
|
handle_ape_exception
|
python
|
ApeWorX/ape
|
src/ape/exceptions.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/exceptions.py
|
Apache-2.0
|
def success(self, message, *args, **kws):
"""This method gets injected into python's `logging` module
to handle logging at this level."""
if self.isEnabledFor(LogLevel.SUCCESS.value):
# Yes, logger takes its '*args' as 'args'.
self._log(LogLevel.SUCCESS.value, message, args, **kws)
|
This method gets injected into python's `logging` module
to handle logging at this level.
|
success
|
python
|
ApeWorX/ape
|
src/ape/logging.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/logging.py
|
Apache-2.0
|
def _isatty(stream: IO) -> bool:
"""Returns ``True`` if the stream is part of a tty.
Borrowed from ``click._compat``."""
# noinspection PyBroadException
try:
return stream.isatty()
except Exception:
return False
|
Returns ``True`` if the stream is part of a tty.
Borrowed from ``click._compat``.
|
_isatty
|
python
|
ApeWorX/ape
|
src/ape/logging.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/logging.py
|
Apache-2.0
|
def _load_from_sys_argv(self, default: Optional[Union[str, int, LogLevel]] = None):
"""
Load from sys.argv to beat race condition with `click`.
"""
if self._did_parse_sys_argv:
# Already parsed.
return
log_level = _get_level(level=default)
level_names = [lvl.name for lvl in LogLevel]
# Minus 2 because if `-v` is the last arg, it is not our verbosity `-v`.
num_args = len(sys.argv) - 2
for arg_i in range(1, 1 + num_args):
if sys.argv[arg_i] == "-v" or sys.argv[arg_i] == "--verbosity":
try:
level = _get_level(sys.argv[arg_i + 1].upper())
except Exception:
# Let it fail in a better spot, or is not our level.
continue
if level in level_names:
self._sys_argv = level
log_level = level
break
else:
# Not our level.
continue
self.set_level(log_level)
self._did_parse_sys_argv = True
|
Load from sys.argv to beat race condition with `click`.
|
_load_from_sys_argv
|
python
|
ApeWorX/ape
|
src/ape/logging.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/logging.py
|
Apache-2.0
|
def set_level(self, level: Union[str, int, LogLevel]):
"""
Change the global ape logger log-level.
Args:
level (str): The name of the level or the value of the log-level.
"""
if level == self._logger.level:
return
elif isinstance(level, LogLevel):
level = level.value
elif isinstance(level, str) and level.lower().startswith("loglevel."):
# Seen in some environments.
level = level.split(".")[-1].strip()
self._logger.setLevel(level)
for _logger in self._extra_loggers.values():
_logger.setLevel(level)
|
Change the global ape logger log-level.
Args:
level (str): The name of the level or the value of the log-level.
|
set_level
|
python
|
ApeWorX/ape
|
src/ape/logging.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/logging.py
|
Apache-2.0
|
def at_level(self, level: Union[str, int, LogLevel]) -> Iterator:
"""
Change the log-level in a context.
Args:
level (Union[str, int, LogLevel]): The level to use.
Returns:
Iterator
"""
initial_level = self.level
self.set_level(level)
yield
self.set_level(initial_level)
|
Change the log-level in a context.
Args:
level (Union[str, int, LogLevel]): The level to use.
Returns:
Iterator
|
at_level
|
python
|
ApeWorX/ape
|
src/ape/logging.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/logging.py
|
Apache-2.0
|
def get_logger(
name: str,
fmt: Optional[str] = None,
handlers: Optional[Sequence[Callable[[str], str]]] = None,
) -> logging.Logger:
"""
Get a logger with the given ``name`` and configure it for usage with Ape.
Args:
name (str): The name of the logger.
fmt (Optional[str]): The format of the logger. Defaults to the Ape
logger's default format: ``"%(levelname)s%(plugin)s: %(message)s"``.
handlers (Optional[Sequence[Callable[[str], str]]]): Additional log message handlers.
Returns:
``logging.Logger``
"""
_logger = logging.getLogger(name)
_format_logger(_logger, fmt=fmt or DEFAULT_LOG_FORMAT, handlers=handlers)
return _logger
|
Get a logger with the given ``name`` and configure it for usage with Ape.
Args:
name (str): The name of the logger.
fmt (Optional[str]): The format of the logger. Defaults to the Ape
logger's default format: ``"%(levelname)s%(plugin)s: %(message)s"``.
handlers (Optional[Sequence[Callable[[str], str]]]): Additional log message handlers.
Returns:
``logging.Logger``
|
get_logger
|
python
|
ApeWorX/ape
|
src/ape/logging.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/logging.py
|
Apache-2.0
|
def sanitize_url(url: str) -> str:
"""Removes sensitive information from given URL"""
parsed = urlparse(url)
new_netloc = parsed.hostname or ""
if parsed.port:
new_netloc += f":{parsed.port}"
new_url = urlunparse(parsed._replace(netloc=new_netloc, path=""))
return f"{new_url}/{HIDDEN_MESSAGE}" if parsed.path else new_url
|
Removes sensitive information from given URL
|
sanitize_url
|
python
|
ApeWorX/ape
|
src/ape/logging.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/logging.py
|
Apache-2.0
|
def silenced(func: Callable):
"""
A decorator for ensuring a function does not output any logs.
Args:
func (Callable): The function to call silently.
"""
def wrapper(*args, **kwargs):
with logger.disabled():
return func(*args, **kwargs)
return wrapper
|
A decorator for ensuring a function does not output any logs.
Args:
func (Callable): The function to call silently.
|
silenced
|
python
|
ApeWorX/ape
|
src/ape/logging.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/logging.py
|
Apache-2.0
|
def __dir__(self) -> list[str]:
"""
Display methods to IPython on ``a.[TAB]`` tab completion.
Returns:
list[str]: Method names that IPython uses for tab completion.
"""
base_value_excludes = ("code", "codesize", "is_contract") # Not needed for accounts
base_values = [v for v in self._base_dir_values if v not in base_value_excludes]
return base_values + [
self.__class__.alias.fget.__name__, # type: ignore[attr-defined]
self.__class__.call.__name__,
self.__class__.deploy.__name__,
self.__class__.prepare_transaction.__name__,
self.__class__.sign_authorization.__name__,
self.__class__.sign_message.__name__,
self.__class__.sign_transaction.__name__,
self.__class__.transfer.__name__,
self.__class__.delegate.fget.__name__, # type: ignore[attr-defined]
self.__class__.set_delegate.__name__,
self.__class__.remove_delegate.__name__,
self.__class__.delegate_to.__name__,
]
|
Display methods to IPython on ``a.[TAB]`` tab completion.
Returns:
list[str]: Method names that IPython uses for tab completion.
|
__dir__
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def sign_raw_msghash(self, msghash: "HexBytes") -> Optional[MessageSignature]:
"""
Sign a raw message hash.
Args:
msghash (:class:`~eth_pydantic_types.HexBytes`):
The message hash to sign. Plugins may or may not support this operation.
Default implementation is to raise ``APINotImplementedError``.
Returns:
:class:`~ape.types.signatures.MessageSignature` (optional):
The signature corresponding to the message.
"""
raise APINotImplementedError(
f"Raw message signing is not supported by '{self.__class__.__name__}'"
)
|
Sign a raw message hash.
Args:
msghash (:class:`~eth_pydantic_types.HexBytes`):
The message hash to sign. Plugins may or may not support this operation.
Default implementation is to raise ``APINotImplementedError``.
Returns:
:class:`~ape.types.signatures.MessageSignature` (optional):
The signature corresponding to the message.
|
sign_raw_msghash
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def sign_authorization(
self,
address: Any,
chain_id: Optional[int] = None,
nonce: Optional[int] = None,
) -> Optional[MessageSignature]:
"""
Sign an `EIP-7702 <https://eips.ethereum.org/EIPS/eip-7702>`__ Authorization.
Args:
address (Any): A delegate address to sign the authorization for.
chain_id (Optional[int]):
The chain ID that the authorization should be valid for.
A value of ``0`` means that the authorization is valid for **any chain**.
Default tells implementation to use the currently connected network's ``chain_id``.
nonce (Optional[int]):
The nonce to use to sign authorization with. Defaults to account's current nonce.
Returns:
:class:`~ape.types.signatures.MessageSignature` (optional):
The signature corresponding to the message.
```{caution}
This action has the capability to be extremely destructive to the signer, and might lead to
full account compromise. All implementations are recommended to ensure that the signer be
made aware of the severity and impact of this action through some callout.
```
"""
raise APINotImplementedError(
f"Authorization signing is not supported by '{self.__class__.__name__}'"
)
|
Sign an `EIP-7702 <https://eips.ethereum.org/EIPS/eip-7702>`__ Authorization.
Args:
address (Any): A delegate address to sign the authorization for.
chain_id (Optional[int]):
The chain ID that the authorization should be valid for.
A value of ``0`` means that the authorization is valid for **any chain**.
Default tells implementation to use the currently connected network's ``chain_id``.
nonce (Optional[int]):
The nonce to use to sign authorization with. Defaults to account's current nonce.
Returns:
:class:`~ape.types.signatures.MessageSignature` (optional):
The signature corresponding to the message.
```{caution}
This action has the capability to be extremely destructive to the signer, and might lead to
full account compromise. All implementations are recommended to ensure that the signer be
made aware of the severity and impact of this action through some callout.
```
|
sign_authorization
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def sign_message(self, msg: Any, **signer_options) -> Optional[MessageSignature]:
"""
Sign a message.
Args:
msg (Any): The message to sign. Account plugins can handle various types of messages.
For example, :class:`~ape_accounts.accounts.KeyfileAccount` can handle
:class:`~ape.types.signatures.SignableMessage`, str, int, and bytes.
See these
`docs <https://eth-account.readthedocs.io/en/stable/eth_account.html#eth_account.messages.SignableMessage>`__ # noqa: E501
for more type information on the :class:`~ape.types.signatures.SignableMessage` type.
**signer_options: Additional kwargs given to the signer to modify the signing operation.
Returns:
:class:`~ape.types.signatures.MessageSignature` (optional): The signature corresponding to the message.
"""
|
Sign a message.
Args:
msg (Any): The message to sign. Account plugins can handle various types of messages.
For example, :class:`~ape_accounts.accounts.KeyfileAccount` can handle
:class:`~ape.types.signatures.SignableMessage`, str, int, and bytes.
See these
`docs <https://eth-account.readthedocs.io/en/stable/eth_account.html#eth_account.messages.SignableMessage>`__ # noqa: E501
for more type information on the :class:`~ape.types.signatures.SignableMessage` type.
**signer_options: Additional kwargs given to the signer to modify the signing operation.
Returns:
:class:`~ape.types.signatures.MessageSignature` (optional): The signature corresponding to the message.
|
sign_message
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def sign_transaction(self, txn: TransactionAPI, **signer_options) -> Optional[TransactionAPI]:
"""
Sign a transaction.
Args:
txn (:class:`~ape.api.transactions.TransactionAPI`): The transaction to sign.
**signer_options: Additional kwargs given to the signer to modify the signing operation.
Returns:
:class:`~ape.api.transactions.TransactionAPI` (optional): A signed transaction.
The ``TransactionAPI`` returned by this method may not correspond to ``txn`` given as
input, however returning a properly-formatted transaction here is meant to be executed.
Returns ``None`` if the account does not have a transaction it wishes to execute.
"""
|
Sign a transaction.
Args:
txn (:class:`~ape.api.transactions.TransactionAPI`): The transaction to sign.
**signer_options: Additional kwargs given to the signer to modify the signing operation.
Returns:
:class:`~ape.api.transactions.TransactionAPI` (optional): A signed transaction.
The ``TransactionAPI`` returned by this method may not correspond to ``txn`` given as
input, however returning a properly-formatted transaction here is meant to be executed.
Returns ``None`` if the account does not have a transaction it wishes to execute.
|
sign_transaction
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def call(
self,
txn: TransactionAPI,
send_everything: bool = False,
private: bool = False,
sign: bool = True,
**signer_options,
) -> ReceiptAPI:
"""
Make a transaction call.
Raises:
:class:`~ape.exceptions.AccountsError`: When the nonce is invalid or the sender does
not have enough funds.
:class:`~ape.exceptions.TransactionError`: When the required confirmations are negative.
:class:`~ape.exceptions.SignatureError`: When the user does not sign the transaction.
:class:`~ape.exceptions.APINotImplementedError`: When setting ``private=True`` and using
a provider that does not support private transactions.
Args:
txn (:class:`~ape.api.transactions.TransactionAPI`): An invoke-transaction.
send_everything (bool): ``True`` will send the difference from balance and fee.
Defaults to ``False``.
private (bool): ``True`` will use the
:meth:`~ape.api.providers.ProviderAPI.send_private_transaction` method.
sign (bool): ``False`` to not sign the transaction (useful for providers like Titanoboa
which still use a sender but don't need to sign).
**signer_options: Additional kwargs given to the signer to modify the signing operation.
Returns:
:class:`~ape.api.transactions.ReceiptAPI`
"""
txn = self.prepare_transaction(txn)
max_fee = txn.max_fee
gas_limit = txn.gas_limit
if not isinstance(gas_limit, int):
raise TransactionError("Transaction not prepared.")
# The conditions below should never reached but are here for mypy's sake.
# The `max_fee` was either set manually or from `prepare_transaction()`.
# The `gas_limit` was either set manually or from `prepare_transaction()`.
if max_fee is None:
raise TransactionError("`max_fee` failed to get set in transaction preparation.")
elif gas_limit is None:
raise TransactionError("`gas_limit` failed to get set in transaction preparation.")
total_fees = max_fee * gas_limit
# Send the whole balance.
if send_everything:
amount_to_send = self.balance - total_fees
if amount_to_send <= 0:
raise AccountsError(
f"Sender does not have enough to cover transaction value and gas: {total_fees}"
)
else:
txn.value = amount_to_send
if sign:
prepared_txn = self.sign_transaction(txn, **signer_options)
if not prepared_txn:
raise SignatureError("The transaction was not signed.", transaction=txn)
else:
prepared_txn = txn
if not prepared_txn.sender:
prepared_txn.sender = self.address
return (
self.provider.send_private_transaction(prepared_txn)
if private
else self.provider.send_transaction(prepared_txn)
)
|
Make a transaction call.
Raises:
:class:`~ape.exceptions.AccountsError`: When the nonce is invalid or the sender does
not have enough funds.
:class:`~ape.exceptions.TransactionError`: When the required confirmations are negative.
:class:`~ape.exceptions.SignatureError`: When the user does not sign the transaction.
:class:`~ape.exceptions.APINotImplementedError`: When setting ``private=True`` and using
a provider that does not support private transactions.
Args:
txn (:class:`~ape.api.transactions.TransactionAPI`): An invoke-transaction.
send_everything (bool): ``True`` will send the difference from balance and fee.
Defaults to ``False``.
private (bool): ``True`` will use the
:meth:`~ape.api.providers.ProviderAPI.send_private_transaction` method.
sign (bool): ``False`` to not sign the transaction (useful for providers like Titanoboa
which still use a sender but don't need to sign).
**signer_options: Additional kwargs given to the signer to modify the signing operation.
Returns:
:class:`~ape.api.transactions.ReceiptAPI`
|
call
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def transfer(
self,
account: Union[str, AddressType, BaseAddress],
value: Optional[Union[str, int]] = None,
data: Optional[Union[bytes, str]] = None,
private: bool = False,
**kwargs,
) -> ReceiptAPI:
"""
Send funds to an account.
Raises:
:class:`~ape.exceptions.APINotImplementedError`: When setting ``private=True``
and using a provider that does not support private transactions.
Args:
account (Union[str, AddressType, BaseAddress]): The receiver of the funds.
value (Optional[Union[str, int]]): The amount to send.
data (Optional[Union[bytes, str]]): Extra data to include in the transaction.
private (bool): ``True`` asks the provider to make the transaction
private. For example, EVM providers typically use the RPC
``eth_sendPrivateTransaction`` to achieve this. Local providers may ignore
this value.
**kwargs: Additional transaction kwargs passed to
:meth:`~ape.api.networks.EcosystemAPI.create_transaction`, such as ``gas``
``max_fee``, or ``max_priority_fee``. For a list of available transaction
kwargs, see :class:`~ape.api.transactions.TransactionAPI`.
Returns:
:class:`~ape.api.transactions.ReceiptAPI`
"""
if isinstance(account, int):
raise AccountsError(
"Cannot use integer-type for the `receiver` argument in the "
"`.transfer()` method (this protects against accidentally passing "
"the `value` as the `receiver`)."
)
try:
receiver = self.conversion_manager.convert(account, AddressType)
except ConversionError as err:
raise AccountsError(f"Invalid `receiver` value: '{account}'.") from err
txn = self.provider.network.ecosystem.create_transaction(
sender=self.address, receiver=receiver, **kwargs
)
if data:
txn.data = self.conversion_manager.convert(data, bytes)
if value is None and not kwargs.get("send_everything"):
raise AccountsError("Must provide 'VALUE' or use 'send_everything=True'")
elif value is not None and kwargs.get("send_everything"):
raise AccountsError("Cannot use 'send_everything=True' with 'VALUE'.")
elif value is not None:
txn.value = self.conversion_manager.convert(value, int)
if txn.value < 0:
raise AccountsError("Value cannot be negative.")
return self.call(txn, private=private, **kwargs)
|
Send funds to an account.
Raises:
:class:`~ape.exceptions.APINotImplementedError`: When setting ``private=True``
and using a provider that does not support private transactions.
Args:
account (Union[str, AddressType, BaseAddress]): The receiver of the funds.
value (Optional[Union[str, int]]): The amount to send.
data (Optional[Union[bytes, str]]): Extra data to include in the transaction.
private (bool): ``True`` asks the provider to make the transaction
private. For example, EVM providers typically use the RPC
``eth_sendPrivateTransaction`` to achieve this. Local providers may ignore
this value.
**kwargs: Additional transaction kwargs passed to
:meth:`~ape.api.networks.EcosystemAPI.create_transaction`, such as ``gas``
``max_fee``, or ``max_priority_fee``. For a list of available transaction
kwargs, see :class:`~ape.api.transactions.TransactionAPI`.
Returns:
:class:`~ape.api.transactions.ReceiptAPI`
|
transfer
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def deploy(
self, contract: "ContractContainer", *args, publish: bool = False, **kwargs
) -> "ContractInstance":
"""
Create a smart contract on the blockchain. The smart contract must compile before
deploying and a provider must be active.
Args:
contract (:class:`~ape.contracts.base.ContractContainer`): The type of contract to
deploy.
publish (bool): Set to ``True`` to attempt explorer contract verification.
Defaults to ``False``.
Returns:
:class:`~ape.contracts.ContractInstance`: An instance of the deployed contract.
"""
from ape.contracts import ContractContainer
if isinstance(contract, ContractType):
# Hack to allow deploying ContractTypes w/o being
# wrapped in a container first.
contract = ContractContainer(contract)
# NOTE: It is important to type check here to prevent cases where user
# may accidentally pass in a ContractInstance, which has a very
# different implementation for __call__ than ContractContainer.
elif not isinstance(contract, ContractContainer):
raise TypeError(
"contract argument must be a ContractContainer type, "
"such as 'project.MyContract' where 'MyContract' is the name of "
"a contract in your project."
)
bytecode = contract.contract_type.deployment_bytecode
if not bytecode or bytecode.bytecode in (None, "", "0x"):
raise MissingDeploymentBytecodeError(contract.contract_type)
txn = contract(*args, **kwargs)
if kwargs.get("value") and not contract.contract_type.constructor.is_payable:
raise MethodNonPayableError("Sending funds to a non-payable constructor.")
txn.sender = self.address
receipt = contract._cache_wrap(lambda: self.call(txn, **kwargs))
if not (address := receipt.contract_address):
raise AccountsError(f"'{receipt.txn_hash}' did not create a contract.")
contract_type = contract.contract_type
styled_address = click.style(receipt.contract_address, bold=True)
contract_name = contract_type.name or "<Unnamed Contract>"
logger.success(f"Contract '{contract_name}' deployed to: {styled_address}")
instance = self.chain_manager.contracts.instance_from_receipt(receipt, contract_type)
self.chain_manager.contracts.cache_deployment(instance)
if publish:
self.local_project.deployments.track(instance)
self.provider.network.publish_contract(address)
instance.base_path = contract.base_path or self.local_project.path
return instance
|
Create a smart contract on the blockchain. The smart contract must compile before
deploying and a provider must be active.
Args:
contract (:class:`~ape.contracts.base.ContractContainer`): The type of contract to
deploy.
publish (bool): Set to ``True`` to attempt explorer contract verification.
Defaults to ``False``.
Returns:
:class:`~ape.contracts.ContractInstance`: An instance of the deployed contract.
|
deploy
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def declare(self, contract: "ContractContainer", *args, **kwargs) -> ReceiptAPI:
"""
Deploy the "blueprint" of a contract type. For EVM providers, this likely means
using `EIP-5202 <https://eips.ethereum.org/EIPS/eip-5202>`__, which is implemented
in the core ``ape-ethereum`` plugin.
Args:
contract (:class:`~ape.contracts.base.ContractContainer`): The contract container
to declare.
Returns:
:class:`~ape.api.transactions.ReceiptAPI`: The receipt of the declare transaction.
"""
transaction = self.provider.network.ecosystem.encode_contract_blueprint(
contract.contract_type, *args, **kwargs
)
receipt = self.call(transaction)
if receipt.contract_address:
self.chain_manager.contracts.cache_blueprint(
receipt.contract_address, contract.contract_type
)
else:
logger.debug("Failed to cache contract declaration: missing contract address.")
return receipt
|
Deploy the "blueprint" of a contract type. For EVM providers, this likely means
using `EIP-5202 <https://eips.ethereum.org/EIPS/eip-5202>`__, which is implemented
in the core ``ape-ethereum`` plugin.
Args:
contract (:class:`~ape.contracts.base.ContractContainer`): The contract container
to declare.
Returns:
:class:`~ape.api.transactions.ReceiptAPI`: The receipt of the declare transaction.
|
declare
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def check_signature(
self,
data: Union[SignableMessage, TransactionAPI, str, EIP712Message, int, bytes],
signature: Optional[MessageSignature] = None, # TransactionAPI doesn't need it
recover_using_eip191: bool = True,
) -> bool:
"""
Verify a message or transaction was signed by this account.
Args:
data (Union[:class:`~ape.types.signatures.SignableMessage`, :class:`~ape.api.transactions.TransactionAPI`]): # noqa: E501
The message or transaction to verify.
signature (Optional[:class:`~ape.types.signatures.MessageSignature`]):
The signature to check. Defaults to ``None`` and is not needed when the first
argument is a transaction class.
recover_using_eip191 (bool):
Perform recovery using EIP-191 signed message check. If set False, then will attempt
recovery as raw hash. `data`` must be a 32 byte hash if this is set False.
Defaults to ``True``.
Returns:
bool: ``True`` if the data was signed by this account. ``False`` otherwise.
"""
if isinstance(data, str):
data = encode_defunct(text=data)
elif isinstance(data, int):
data = encode_defunct(hexstr=to_hex(data))
elif isinstance(data, bytes) and (len(data) != 32 or recover_using_eip191):
data = encode_defunct(data)
elif isinstance(data, EIP712Message):
data = data.signable_message
if isinstance(data, (SignableMessage, EIP712SignableMessage)):
if signature:
return self.address == Account.recover_message(data, vrs=signature)
else:
raise AccountsError(
"Parameter 'signature' required when verifying a 'SignableMessage'."
)
elif isinstance(data, TransactionAPI):
return self.address == Account.recover_transaction(data.serialize_transaction())
elif isinstance(data, bytes) and len(data) == 32 and not recover_using_eip191:
return self.address == Account._recover_hash(data, vrs=signature)
else:
raise AccountsError(f"Unsupported message type: {type(data)}.")
|
Verify a message or transaction was signed by this account.
Args:
data (Union[:class:`~ape.types.signatures.SignableMessage`, :class:`~ape.api.transactions.TransactionAPI`]): # noqa: E501
The message or transaction to verify.
signature (Optional[:class:`~ape.types.signatures.MessageSignature`]):
The signature to check. Defaults to ``None`` and is not needed when the first
argument is a transaction class.
recover_using_eip191 (bool):
Perform recovery using EIP-191 signed message check. If set False, then will attempt
recovery as raw hash. `data`` must be a 32 byte hash if this is set False.
Defaults to ``True``.
Returns:
bool: ``True`` if the data was signed by this account. ``False`` otherwise.
|
check_signature
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def get_deployment_address(self, nonce: Optional[int] = None) -> AddressType:
"""
Get a contract address before it is deployed. This is useful
when you need to pass the contract address to another contract
before deploying it.
Args:
nonce (int | None): Optionally provide a nonce. Defaults
the account's current nonce.
Returns:
AddressType: The contract address.
"""
# Use the connected network, if available. Else, default to Ethereum.
ecosystem = (
self.network_manager.active_provider.network.ecosystem
if self.network_manager.active_provider
else self.network_manager.ethereum
)
nonce = self.nonce if nonce is None else nonce
return ecosystem.get_deployment_address(self.address, nonce)
|
Get a contract address before it is deployed. This is useful
when you need to pass the contract address to another contract
before deploying it.
Args:
nonce (int | None): Optionally provide a nonce. Defaults
the account's current nonce.
Returns:
AddressType: The contract address.
|
get_deployment_address
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def delegate_to(
self,
new_delegate: Union[BaseAddress, AddressType, str],
set_txn_kwargs: Optional[dict] = None,
reset_txn_kwargs: Optional[dict] = None,
**txn_kwargs,
) -> Iterator[BaseAddress]:
"""
Temporarily override the value of ``delegate`` for the account inside of a context manager,
and yields a contract instance object whose interface matches that of ``new_delegate``.
This is useful for ensuring that delegation is only temporarily extended to an account when
doing a critical action temporarily, such as using an EIP7702 delegate module.
Args:
new_delegate (`:class:~ape.contracts.ContractInstance`):
The contract instance to override the `delegate` with.
set_txn_kwargs (dict | None): Additional transaction kwargs passed to
:meth:`~ape.api.networks.EcosystemAPI.create_transaction` for the
:meth:`AccountAPI.set_delegate` method, such as ``gas``, ``max_fee``, or
``max_priority_fee``. Overrides the values provided via ``txn_kwargs``. For a list of
available transaction kwargs, see :class:`~ape.api.transactions.TransactionAPI`.
reset_txn_kwargs (dict | None): Additional transaction kwargs passed to
:meth:`~ape.api.networks.EcosystemAPI.create_transaction` for the
:meth:`AccountAPI.remove_delegate` method, such as ``gas``, ``max_fee``, or
``max_priority_fee``. Overrides the values provided via ``txn_kwargs``. For a list of
available transaction kwargs, see :class:`~ape.api.transactions.TransactionAPI`.
**txn_kwargs: Additional transaction kwargs passed to
:meth:`~ape.api.networks.EcosystemAPI.create_transaction`, such as ``gas``
``max_fee``, or ``max_priority_fee``. For a list of available transaction
kwargs, see :class:`~ape.api.transactions.TransactionAPI`.
Returns:
`:class:~ape.contracts.ContractInstance`:
The contract instance of this account with the interface of `contract`.
"""
set_txn_kwargs = {**txn_kwargs, **(set_txn_kwargs or {})}
existing_delegate = self.delegate
self.set_delegate(new_delegate, **set_txn_kwargs)
# NOTE: Do not cache this type as it is temporary
from ape.contracts import ContractInstance
# This is helpful for using it immediately to send things as self
with self.account_manager.use_sender(self):
if isinstance(new_delegate, ContractInstance):
# NOTE: Do not cache this
yield ContractInstance(self.address, contract_type=new_delegate.contract_type)
else:
yield self
reset_txn_kwargs = {**txn_kwargs, **(reset_txn_kwargs or {})}
if existing_delegate:
self.set_delegate(existing_delegate, **reset_txn_kwargs)
else:
self.remove_delegate(**reset_txn_kwargs)
|
Temporarily override the value of ``delegate`` for the account inside of a context manager,
and yields a contract instance object whose interface matches that of ``new_delegate``.
This is useful for ensuring that delegation is only temporarily extended to an account when
doing a critical action temporarily, such as using an EIP7702 delegate module.
Args:
new_delegate (`:class:~ape.contracts.ContractInstance`):
The contract instance to override the `delegate` with.
set_txn_kwargs (dict | None): Additional transaction kwargs passed to
:meth:`~ape.api.networks.EcosystemAPI.create_transaction` for the
:meth:`AccountAPI.set_delegate` method, such as ``gas``, ``max_fee``, or
``max_priority_fee``. Overrides the values provided via ``txn_kwargs``. For a list of
available transaction kwargs, see :class:`~ape.api.transactions.TransactionAPI`.
reset_txn_kwargs (dict | None): Additional transaction kwargs passed to
:meth:`~ape.api.networks.EcosystemAPI.create_transaction` for the
:meth:`AccountAPI.remove_delegate` method, such as ``gas``, ``max_fee``, or
``max_priority_fee``. Overrides the values provided via ``txn_kwargs``. For a list of
available transaction kwargs, see :class:`~ape.api.transactions.TransactionAPI`.
**txn_kwargs: Additional transaction kwargs passed to
:meth:`~ape.api.networks.EcosystemAPI.create_transaction`, such as ``gas``
``max_fee``, or ``max_priority_fee``. For a list of available transaction
kwargs, see :class:`~ape.api.transactions.TransactionAPI`.
Returns:
`:class:~ape.contracts.ContractInstance`:
The contract instance of this account with the interface of `contract`.
|
delegate_to
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def aliases(self) -> Iterator[str]:
"""
All available aliases.
Returns:
Iterator[str]
"""
|
All available aliases.
Returns:
Iterator[str]
|
aliases
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def accounts(self) -> Iterator[AccountAPI]:
"""
All accounts.
Returns:
Iterator[:class:`~ape.api.accounts.AccountAPI`]
"""
|
All accounts.
Returns:
Iterator[:class:`~ape.api.accounts.AccountAPI`]
|
accounts
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def data_folder(self) -> Path:
"""
The path to the account data files.
Defaults to ``$HOME/.ape/<plugin_name>`` unless overridden.
"""
path = self.config_manager.DATA_FOLDER / self.name
path.mkdir(parents=True, exist_ok=True)
return path
|
The path to the account data files.
Defaults to ``$HOME/.ape/<plugin_name>`` unless overridden.
|
data_folder
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def __getitem__(self, address: AddressType) -> AccountAPI:
"""
Get an account by address.
Args:
address (:class:`~ape.types.address.AddressType`): The address to get. The type is an alias to
`ChecksumAddress <https://eth-typing.readthedocs.io/en/latest/types.html#checksumaddress>`__. # noqa: E501
Raises:
KeyError: When there is no local account with the given address.
Returns:
:class:`~ape.api.accounts.AccountAPI`
"""
for account in self.accounts:
if account.address == address:
return account
raise KeyError(f"No local account {address}.")
|
Get an account by address.
Args:
address (:class:`~ape.types.address.AddressType`): The address to get. The type is an alias to
`ChecksumAddress <https://eth-typing.readthedocs.io/en/latest/types.html#checksumaddress>`__. # noqa: E501
Raises:
KeyError: When there is no local account with the given address.
Returns:
:class:`~ape.api.accounts.AccountAPI`
|
__getitem__
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def append(self, account: AccountAPI):
"""
Add an account to the container.
Raises:
:class:`~ape.exceptions.AccountsError`: When the account is already in the container.
Args:
account (:class:`~ape.api.accounts.AccountAPI`): The account to add.
"""
self._verify_account_type(account)
if account.address in self:
raise AccountsError(f"Account '{account.address}' already in container.")
self._verify_unused_alias(account)
self.__setitem__(account.address, account)
|
Add an account to the container.
Raises:
:class:`~ape.exceptions.AccountsError`: When the account is already in the container.
Args:
account (:class:`~ape.api.accounts.AccountAPI`): The account to add.
|
append
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def remove(self, account: AccountAPI):
"""
Delete an account.
Raises:
:class:`~ape.exceptions.AccountsError`: When the account is not known to ``ape``.
Args:
account (:class:`~ape.accounts.AccountAPI`): The account to remove.
"""
self._verify_account_type(account)
if account.address not in self:
raise AccountsError(f"Account '{account.address}' not known.")
self.__delitem__(account.address)
|
Delete an account.
Raises:
:class:`~ape.exceptions.AccountsError`: When the account is not known to ``ape``.
Args:
account (:class:`~ape.accounts.AccountAPI`): The account to remove.
|
remove
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def __contains__(self, address: AddressType) -> bool:
"""
Check if the address is an existing account in ``ape``.
Raises:
IndexError: When the given account address is not in this container.
Args:
address (:class:`~ape.types.address.AddressType`): An account address.
Returns:
bool: ``True`` if ``ape`` manages the account with the given address.
"""
try:
self.__getitem__(address)
return True
except (IndexError, KeyError, AttributeError):
return False
|
Check if the address is an existing account in ``ape``.
Raises:
IndexError: When the given account address is not in this container.
Args:
address (:class:`~ape.types.address.AddressType`): An account address.
Returns:
bool: ``True`` if ``ape`` manages the account with the given address.
|
__contains__
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def get_test_account(self, index: int) -> "TestAccountAPI": # type: ignore[empty-body]
"""
Get the test account at the given index.
Args:
index (int): The index of the test account.
Returns:
:class:`~ape.api.accounts.TestAccountAPI`
"""
|
Get the test account at the given index.
Args:
index (int): The index of the test account.
Returns:
:class:`~ape.api.accounts.TestAccountAPI`
|
get_test_account
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def reset(self):
"""
Reset the account container to an original state.
"""
|
Reset the account container to an original state.
|
reset
|
python
|
ApeWorX/ape
|
src/ape/api/accounts.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/accounts.py
|
Apache-2.0
|
def _base_dir_values(self) -> list[str]:
"""
This exists because when you call ``dir(BaseAddress)``, you get the type's return
value and not the instances. This allows base-classes to make use of shared
``IPython`` ``__dir__`` values.
"""
# NOTE: mypy is confused by properties.
# https://github.com/python/typing/issues/1112
return [
str(BaseAddress.address.fget.__name__), # type: ignore[attr-defined]
str(BaseAddress.balance.fget.__name__), # type: ignore[attr-defined]
str(BaseAddress.code.fget.__name__), # type: ignore[attr-defined]
str(BaseAddress.codesize.fget.__name__), # type: ignore[attr-defined]
str(BaseAddress.nonce.fget.__name__), # type: ignore[attr-defined]
str(BaseAddress.is_contract.fget.__name__), # type: ignore[attr-defined]
"provider", # Is a class property
]
|
This exists because when you call ``dir(BaseAddress)``, you get the type's return
value and not the instances. This allows base-classes to make use of shared
``IPython`` ``__dir__`` values.
|
_base_dir_values
|
python
|
ApeWorX/ape
|
src/ape/api/address.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/address.py
|
Apache-2.0
|
def address(self) -> AddressType:
"""
The address of this account. Subclasses must override and provide this value.
"""
|
The address of this account. Subclasses must override and provide this value.
|
address
|
python
|
ApeWorX/ape
|
src/ape/api/address.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/address.py
|
Apache-2.0
|
def __eq__(self, other: object) -> bool:
"""
Compares :class:`~ape.api.BaseAddress` or ``str`` objects by converting to
:class:`~ape.types.address.AddressType`.
Returns:
bool: comparison result
"""
convert = self.conversion_manager.convert
try:
return convert(self, AddressType) == convert(other, AddressType)
except ConversionError:
# Check other __eq__
return NotImplemented
|
Compares :class:`~ape.api.BaseAddress` or ``str`` objects by converting to
:class:`~ape.types.address.AddressType`.
Returns:
bool: comparison result
|
__eq__
|
python
|
ApeWorX/ape
|
src/ape/api/address.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/address.py
|
Apache-2.0
|
def __call__(self, **kwargs) -> "ReceiptAPI":
"""
Call this address directly. For contracts, this may mean invoking their
default handler.
Args:
**kwargs: Transaction arguments, such as ``sender`` or ``data``.
Returns:
:class:`~ape.api.transactions.ReceiptAPI`
"""
txn = self.as_transaction(**kwargs)
if "sender" in kwargs:
if hasattr(kwargs["sender"], "call"):
# AccountAPI
sender = kwargs["sender"]
return sender.call(txn, **kwargs)
elif hasattr(kwargs["sender"], "prepare_transaction"):
# BaseAddress (likely, a ContractInstance)
prepare_transaction = kwargs["sender"].prepare_transaction(txn)
return self.provider.send_transaction(prepare_transaction)
elif "sender" not in kwargs and self.account_manager.default_sender is not None:
return self.account_manager.default_sender.call(txn, **kwargs)
return self.provider.send_transaction(txn)
|
Call this address directly. For contracts, this may mean invoking their
default handler.
Args:
**kwargs: Transaction arguments, such as ``sender`` or ``data``.
Returns:
:class:`~ape.api.transactions.ReceiptAPI`
|
__call__
|
python
|
ApeWorX/ape
|
src/ape/api/address.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/address.py
|
Apache-2.0
|
def balance(self) -> int:
"""
The total balance of the account.
"""
bal = self.provider.get_balance(self.address)
# By using CurrencyValue, we can compare with
# strings like "1 ether".
return CurrencyValue(bal)
|
The total balance of the account.
|
balance
|
python
|
ApeWorX/ape
|
src/ape/api/address.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/address.py
|
Apache-2.0
|
def codesize(self) -> int:
"""
The number of bytes in the smart contract.
"""
code = self.code
return len(code) if isinstance(code, bytes) else len(bytes.fromhex(code.lstrip("0x")))
|
The number of bytes in the smart contract.
|
codesize
|
python
|
ApeWorX/ape
|
src/ape/api/address.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/address.py
|
Apache-2.0
|
def prepare_transaction(self, txn: "TransactionAPI", **kwargs) -> "TransactionAPI":
"""
Set default values on a transaction.
Raises:
:class:`~ape.exceptions.AccountsError`: When the account cannot afford the transaction
or the nonce is invalid.
:class:`~ape.exceptions.TransactionError`: When given negative required confirmations.
Args:
txn (:class:`~ape.api.transactions.TransactionAPI`): The transaction to prepare.
**kwargs: Sub-classes, such as :class:`~ape.api.accounts.AccountAPI`, use additional kwargs.
Returns:
:class:`~ape.api.transactions.TransactionAPI`
"""
# NOTE: Allow overriding nonce, assume user understands what this does
if txn.nonce is None:
txn.nonce = self.nonce
elif txn.nonce < self.nonce:
raise AccountsError("Invalid nonce, will not publish.")
txn = self.provider.prepare_transaction(txn)
if (
txn.sender not in self.account_manager.test_accounts._impersonated_accounts
and txn.total_transfer_value > self.balance
):
raise AccountsError(
f"Transfer value meets or exceeds account balance "
f"for account '{self.address}' on chain '{self.provider.chain_id}' "
f"using provider '{self.provider.name}'.\n"
"Are you using the correct account / chain / provider combination?\n"
f"(transfer_value={txn.total_transfer_value}, balance={self.balance})."
)
txn.sender = txn.sender or self.address
return txn
|
Set default values on a transaction.
Raises:
:class:`~ape.exceptions.AccountsError`: When the account cannot afford the transaction
or the nonce is invalid.
:class:`~ape.exceptions.TransactionError`: When given negative required confirmations.
Args:
txn (:class:`~ape.api.transactions.TransactionAPI`): The transaction to prepare.
**kwargs: Sub-classes, such as :class:`~ape.api.accounts.AccountAPI`, use additional kwargs.
Returns:
:class:`~ape.api.transactions.TransactionAPI`
|
prepare_transaction
|
python
|
ApeWorX/ape
|
src/ape/api/address.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/address.py
|
Apache-2.0
|
def get_config(self, project: Optional["ProjectManager"] = None) -> "PluginConfig":
"""
The combination of settings from ``ape-config.yaml`` and ``.compiler_settings``.
Args:
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
Returns:
:class:`~ape.api.config.PluginConfig`
"""
pm = project or self.local_project
config = pm.config.get_config(self.name)
data = {**config.model_dump(mode="json", by_alias=True), **self.compiler_settings}
return config.model_validate(data)
|
The combination of settings from ``ape-config.yaml`` and ``.compiler_settings``.
Args:
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
Returns:
:class:`~ape.api.config.PluginConfig`
|
get_config
|
python
|
ApeWorX/ape
|
src/ape/api/compiler.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/compiler.py
|
Apache-2.0
|
def get_versions(self, all_paths: Iterable[Path]) -> set[str]: # type: ignore[empty-body]
"""
Retrieve the set of available compiler versions for this plugin to compile ``all_paths``.
Args:
all_paths (Iterable[pathlib.Path]): The list of paths.
Returns:
set[str]: A set of available compiler versions.
"""
|
Retrieve the set of available compiler versions for this plugin to compile ``all_paths``.
Args:
all_paths (Iterable[pathlib.Path]): The list of paths.
Returns:
set[str]: A set of available compiler versions.
|
get_versions
|
python
|
ApeWorX/ape
|
src/ape/api/compiler.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/compiler.py
|
Apache-2.0
|
def get_compiler_settings( # type: ignore[empty-body]
self,
contract_filepaths: Iterable[Path],
project: Optional["ProjectManager"] = None,
**overrides,
) -> dict["Version", dict]:
"""
Get a mapping of the settings that would be used to compile each of the sources
by the compiler version number.
Args:
contract_filepaths (Iterable[pathlib.Path]): The list of paths.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
**overrides: Settings overrides.
Returns:
dict[Version, dict]: A dict of compiler settings by compiler version.
"""
|
Get a mapping of the settings that would be used to compile each of the sources
by the compiler version number.
Args:
contract_filepaths (Iterable[pathlib.Path]): The list of paths.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
**overrides: Settings overrides.
Returns:
dict[Version, dict]: A dict of compiler settings by compiler version.
|
get_compiler_settings
|
python
|
ApeWorX/ape
|
src/ape/api/compiler.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/compiler.py
|
Apache-2.0
|
def compile(
self,
contract_filepaths: Iterable[Path],
project: Optional["ProjectManager"],
settings: Optional[dict] = None,
) -> Iterator["ContractType"]:
"""
Compile the given source files. All compiler plugins must implement this function.
Args:
contract_filepaths (Iterable[pathlib.Path]): A list of source file paths to compile.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
settings (Optional[dict]): Adhoc compiler settings.
Returns:
list[:class:`~ape.type.contract.ContractType`]
"""
|
Compile the given source files. All compiler plugins must implement this function.
Args:
contract_filepaths (Iterable[pathlib.Path]): A list of source file paths to compile.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
settings (Optional[dict]): Adhoc compiler settings.
Returns:
list[:class:`~ape.type.contract.ContractType`]
|
compile
|
python
|
ApeWorX/ape
|
src/ape/api/compiler.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/compiler.py
|
Apache-2.0
|
def compile_code( # type: ignore[empty-body]
self,
code: str,
project: Optional["ProjectManager"],
settings: Optional[dict] = None,
**kwargs,
) -> "ContractType":
"""
Compile a program.
Args:
code (str): The code to compile.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
settings (Optional[Dict]): Adhoc compiler settings.
**kwargs: Additional overrides for the ``ethpm_types.ContractType`` model.
Returns:
``ContractType``: A compiled contract artifact.
"""
|
Compile a program.
Args:
code (str): The code to compile.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
settings (Optional[Dict]): Adhoc compiler settings.
**kwargs: Additional overrides for the ``ethpm_types.ContractType`` model.
Returns:
``ContractType``: A compiled contract artifact.
|
compile_code
|
python
|
ApeWorX/ape
|
src/ape/api/compiler.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/compiler.py
|
Apache-2.0
|
def get_imports( # type: ignore[empty-body]
self, contract_filepaths: Iterable[Path], project: Optional["ProjectManager"]
) -> dict[str, list[str]]:
"""
Returns a list of imports as source_ids for each contract's source_id in a given
compiler.
Args:
contract_filepaths (Iterable[pathlib.Path]): A list of source file paths to compile.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
Returns:
dict[str, list[str]]: A dictionary like ``{source_id: [import_source_id, ...], ...}``
"""
|
Returns a list of imports as source_ids for each contract's source_id in a given
compiler.
Args:
contract_filepaths (Iterable[pathlib.Path]): A list of source file paths to compile.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
Returns:
dict[str, list[str]]: A dictionary like ``{source_id: [import_source_id, ...], ...}``
|
get_imports
|
python
|
ApeWorX/ape
|
src/ape/api/compiler.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/compiler.py
|
Apache-2.0
|
def get_version_map( # type: ignore[empty-body]
self,
contract_filepaths: Iterable[Path],
project: Optional["ProjectManager"] = None,
) -> dict["Version", set[Path]]:
"""
Get a map of versions to source paths.
Args:
contract_filepaths (Iterable[Path]): Input source paths. Defaults to all source paths
per compiler.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
Returns:
dict[Version, set[Path]]
"""
|
Get a map of versions to source paths.
Args:
contract_filepaths (Iterable[Path]): Input source paths. Defaults to all source paths
per compiler.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
Returns:
dict[Version, set[Path]]
|
get_version_map
|
python
|
ApeWorX/ape
|
src/ape/api/compiler.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/compiler.py
|
Apache-2.0
|
def supports_source_tracing(self) -> bool:
"""
Returns ``True`` if this compiler is able to provider a source
traceback for a given trace.
"""
try:
self.trace_source(None, None, None) # type: ignore
except APINotImplementedError:
return False
except Exception:
# Task failed successfully.
return True
return True
|
Returns ``True`` if this compiler is able to provider a source
traceback for a given trace.
|
supports_source_tracing
|
python
|
ApeWorX/ape
|
src/ape/api/compiler.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/compiler.py
|
Apache-2.0
|
def trace_source( # type: ignore[empty-body]
self, contract_source: "ContractSource", trace: "TraceAPI", calldata: "HexBytes"
) -> "SourceTraceback":
"""
Get a source-traceback for the given contract type.
The source traceback object contains all the control paths taken in the transaction.
When available, source-code location information is accessible from the object.
Args:
contract_source (``ContractSource``): A contract type with a local-source that was
compiled by this compiler.
trace (:class:`~ape.api.trace.TraceAPI`]): The resulting trace from executing a
function defined in the given contract type.
calldata (``HexBytes``): Calldata passed to the top-level call.
Returns:
:class:`~ape.types.trace.SourceTraceback`
"""
|
Get a source-traceback for the given contract type.
The source traceback object contains all the control paths taken in the transaction.
When available, source-code location information is accessible from the object.
Args:
contract_source (``ContractSource``): A contract type with a local-source that was
compiled by this compiler.
trace (:class:`~ape.api.trace.TraceAPI`]): The resulting trace from executing a
function defined in the given contract type.
calldata (``HexBytes``): Calldata passed to the top-level call.
Returns:
:class:`~ape.types.trace.SourceTraceback`
|
trace_source
|
python
|
ApeWorX/ape
|
src/ape/api/compiler.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/compiler.py
|
Apache-2.0
|
def flatten_contract( # type: ignore[empty-body]
self, path: Path, project: Optional["ProjectManager"] = None, **kwargs
) -> "Content":
"""
Get the content of a flattened contract via its source path.
Plugin implementations handle import resolution, SPDX de-duplication,
and anything else needed.
Args:
path (``pathlib.Path``): The source path of the contract.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
**kwargs (Any): Additional compiler-specific settings. See specific
compiler plugins when applicable.
Returns:
``ethpm_types.source.Content``: The flattened contract content.
"""
|
Get the content of a flattened contract via its source path.
Plugin implementations handle import resolution, SPDX de-duplication,
and anything else needed.
Args:
path (``pathlib.Path``): The source path of the contract.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
**kwargs (Any): Additional compiler-specific settings. See specific
compiler plugins when applicable.
Returns:
``ethpm_types.source.Content``: The flattened contract content.
|
flatten_contract
|
python
|
ApeWorX/ape
|
src/ape/api/compiler.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/compiler.py
|
Apache-2.0
|
def init_coverage_profile(
self, source_coverage: "ContractSourceCoverage", contract_source: "ContractSource"
): # type: ignore[empty-body]
"""
Initialize an empty report for the given source ID. Modifies the given source
coverage in-place.
Args:
source_coverage (:class:`~ape.types.coverage.SourceCoverage`): The source
to generate an empty coverage profile for.
contract_source (``ethpm_types.source.ContractSource``): The contract with
source content.
"""
|
Initialize an empty report for the given source ID. Modifies the given source
coverage in-place.
Args:
source_coverage (:class:`~ape.types.coverage.SourceCoverage`): The source
to generate an empty coverage profile for.
contract_source (``ethpm_types.source.ContractSource``): The contract with
source content.
|
init_coverage_profile
|
python
|
ApeWorX/ape
|
src/ape/api/compiler.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/compiler.py
|
Apache-2.0
|
def _find_config_yaml_files(base_path: Path) -> list[Path]:
"""
Find all ape config file in the given path.
"""
found: list[Path] = []
if (base_path / "ape-config.yaml").is_file():
found.append(base_path / "ape-config.yaml")
if (base_path / "ape-config.yml").is_file():
found.append(base_path / "ape-config.yml")
return found
|
Find all ape config file in the given path.
|
_find_config_yaml_files
|
python
|
ApeWorX/ape
|
src/ape/api/config.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/config.py
|
Apache-2.0
|
def validate_file(cls, path: Path, **overrides) -> "ApeConfig":
"""
Create an ApeConfig class using the given path.
Supports both pyproject.toml and ape-config.[.yml|.yaml|.json] files.
Raises:
:class:`~ape.exceptions.ConfigError`: When given an unknown file type
or the data is invalid.
Args:
path (Path): The path to the file.
**overrides: Config overrides.
Returns:
:class:`~ape.api.config.ApeConfig`
"""
data = {**load_config(path), **overrides}
# NOTE: We are including the project path here to assist
# in relative-path resolution, such as for local dependencies.
# You can use relative paths in local dependencies in your
# ape-config.yaml file but Ape needs to know the source to be
# relative from.
data["project"] = path.parent
try:
return cls.model_validate(data)
except ValidationError as err:
if path.suffix == ".json":
# TODO: Support JSON configs here.
raise ConfigError(f"{err}") from err
if final_msg := _get_problem_with_config(err.errors(), path):
raise ConfigError(final_msg)
else:
raise ConfigError(str(err)) from err
|
Create an ApeConfig class using the given path.
Supports both pyproject.toml and ape-config.[.yml|.yaml|.json] files.
Raises:
:class:`~ape.exceptions.ConfigError`: When given an unknown file type
or the data is invalid.
Args:
path (Path): The path to the file.
**overrides: Config overrides.
Returns:
:class:`~ape.api.config.ApeConfig`
|
validate_file
|
python
|
ApeWorX/ape
|
src/ape/api/config.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/config.py
|
Apache-2.0
|
def write_to_disk(self, destination: Path, replace: bool = False):
"""
Write this config to a file.
Args:
destination (Path): The path to write to.
replace (bool): Set to ``True`` to overwrite the file if it exists.
"""
if destination.exists() and not replace:
raise ValueError(f"Destination {destination} exists.")
elif replace:
destination.unlink(missing_ok=True)
if destination.suffix in (".yml", ".yaml"):
destination.parent.mkdir(parents=True, exist_ok=True)
with open(destination, "x") as file:
data = self.model_dump(by_alias=True, mode="json")
yaml.safe_dump(data, file)
elif destination.suffix == ".json":
destination.write_text(self.model_dump_json(by_alias=True), encoding="utf8")
else:
raise ConfigError(f"Unsupported destination file type '{destination}'.")
|
Write this config to a file.
Args:
destination (Path): The path to write to.
replace (bool): Set to ``True`` to overwrite the file if it exists.
|
write_to_disk
|
python
|
ApeWorX/ape
|
src/ape/api/config.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/config.py
|
Apache-2.0
|
def is_convertible(self, value: Any) -> bool:
"""
Returns ``True`` if string value provided by ``value`` is convertible using
:meth:`ape.api.convert.ConverterAPI.convert`.
Args:
value (Any): The value to check.
Returns:
bool: ``True`` when the given value can be converted.
"""
|
Returns ``True`` if string value provided by ``value`` is convertible using
:meth:`ape.api.convert.ConverterAPI.convert`.
Args:
value (Any): The value to check.
Returns:
bool: ``True`` when the given value can be converted.
|
is_convertible
|
python
|
ApeWorX/ape
|
src/ape/api/convert.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/convert.py
|
Apache-2.0
|
def convert(self, value: Any) -> ConvertedType:
"""
Convert the given value to the type specified as the generic for this class.
Implementations of this API must throw a :class:`~ape.exceptions.ConversionError`
when the item fails to convert properly.
Usage example::
from ape import convert
from ape.types import AddressType
convert("1 gwei", int)
# 1000000000
convert("1 ETH", int)
# 1000000000000000000
convert("0x283Af0B28c62C092C9727F1Ee09c02CA627EB7F5", bytes)
# HexBytes('0x283af0b28c62c092c9727f1ee09c02ca627eb7f5')
convert("vitalik.eth", AddressType) # with ape-ens plugin installed
# '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
"""
|
Convert the given value to the type specified as the generic for this class.
Implementations of this API must throw a :class:`~ape.exceptions.ConversionError`
when the item fails to convert properly.
Usage example::
from ape import convert
from ape.types import AddressType
convert("1 gwei", int)
# 1000000000
convert("1 ETH", int)
# 1000000000000000000
convert("0x283Af0B28c62C092C9727F1Ee09c02CA627EB7F5", bytes)
# HexBytes('0x283af0b28c62c092c9727f1ee09c02ca627eb7f5')
convert("vitalik.eth", AddressType) # with ape-ens plugin installed
# '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
|
convert
|
python
|
ApeWorX/ape
|
src/ape/api/convert.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/convert.py
|
Apache-2.0
|
def name(self) -> str:
"""
The calculated name of the converter class.
Typically, it is the lowered prefix of the class without
the "Converter" or "Conversions" suffix.
"""
class_name = self.__class__.__name__
name = class_name.replace("Converter", "").replace("Conversions", "")
return name.lower()
|
The calculated name of the converter class.
Typically, it is the lowered prefix of the class without
the "Converter" or "Conversions" suffix.
|
name
|
python
|
ApeWorX/ape
|
src/ape/api/convert.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/convert.py
|
Apache-2.0
|
def get_address_url(self, address: "AddressType") -> str:
"""
Get an address URL, such as for a transaction.
Args:
address (:class:`~ape.types.address.AddressType`): The address.
Returns:
str: The URL.
"""
|
Get an address URL, such as for a transaction.
Args:
address (:class:`~ape.types.address.AddressType`): The address.
Returns:
str: The URL.
|
get_address_url
|
python
|
ApeWorX/ape
|
src/ape/api/explorers.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/explorers.py
|
Apache-2.0
|
def get_transaction_url(self, transaction_hash: str) -> str:
"""
Get the transaction URL for the given transaction.
Args:
transaction_hash (str): The transaction hash.
Returns:
str: The URL.
"""
|
Get the transaction URL for the given transaction.
Args:
transaction_hash (str): The transaction hash.
Returns:
str: The URL.
|
get_transaction_url
|
python
|
ApeWorX/ape
|
src/ape/api/explorers.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/explorers.py
|
Apache-2.0
|
def get_contract_type(self, address: "AddressType") -> Optional["ContractType"]:
"""
Get the contract type for a given address if it has been published to this explorer.
Args:
address (:class:`~ape.types.address.AddressType`): The contract address.
Returns:
Optional[``ContractType``]: If not published, returns ``None``.
"""
|
Get the contract type for a given address if it has been published to this explorer.
Args:
address (:class:`~ape.types.address.AddressType`): The contract address.
Returns:
Optional[``ContractType``]: If not published, returns ``None``.
|
get_contract_type
|
python
|
ApeWorX/ape
|
src/ape/api/explorers.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/explorers.py
|
Apache-2.0
|
def publish_contract(self, address: "AddressType"):
"""
Publish a contract to the explorer.
Args:
address (:class:`~ape.types.address.AddressType`): The address of the deployed contract.
"""
|
Publish a contract to the explorer.
Args:
address (:class:`~ape.types.address.AddressType`): The address of the deployed contract.
|
publish_contract
|
python
|
ApeWorX/ape
|
src/ape/api/explorers.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/explorers.py
|
Apache-2.0
|
def custom_network(self) -> "NetworkAPI":
"""
A :class:`~ape.api.networks.NetworkAPI` for custom networks where the
network is either not known, unspecified, or does not have an Ape plugin.
"""
ethereum_class = None
for plugin_name, ecosystem_class in self.plugin_manager.ecosystems:
if plugin_name == "ethereum":
ethereum_class = ecosystem_class
break
if ethereum_class is None:
raise NetworkError("Core Ethereum plugin missing.")
init_kwargs = {"name": "ethereum"}
evm_ecosystem = ethereum_class(**init_kwargs) # type: ignore
return NetworkAPI(
name="custom",
ecosystem=evm_ecosystem,
_default_provider="node",
_is_custom=True,
)
|
A :class:`~ape.api.networks.NetworkAPI` for custom networks where the
network is either not known, unspecified, or does not have an Ape plugin.
|
custom_network
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def decode_address(cls, raw_address: "RawAddress") -> AddressType:
"""
Convert a raw address to the ecosystem's native address type.
Args:
raw_address (:class:`~ape.types.address.RawAddress`): The address to
convert.
Returns:
:class:`~ape.types.address.AddressType`
"""
|
Convert a raw address to the ecosystem's native address type.
Args:
raw_address (:class:`~ape.types.address.RawAddress`): The address to
convert.
Returns:
:class:`~ape.types.address.AddressType`
|
decode_address
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def encode_address(cls, address: AddressType) -> "RawAddress":
"""
Convert the ecosystem's native address type to a raw integer or str address.
Args:
address (:class:`~ape.types.address.AddressType`): The address to convert.
Returns:
:class:`~ape.types.address.RawAddress`
"""
|
Convert the ecosystem's native address type to a raw integer or str address.
Args:
address (:class:`~ape.types.address.AddressType`): The address to convert.
Returns:
:class:`~ape.types.address.RawAddress`
|
encode_address
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def encode_contract_blueprint( # type: ignore[empty-body]
self, contract_type: "ContractType", *args, **kwargs
) -> "TransactionAPI":
"""
Encode a unique type of transaction that allows contracts to be created
from other contracts, such as
`EIP-5202 <https://eips.ethereum.org/EIPS/eip-5202>`__
or Starknet's ``Declare`` transaction type.
Args:
contract_type (``ContractType``): The type of contract to create a blueprint for.
This is the type of contract that will get created by factory contracts.
*args (Any): Calldata, if applicable.
**kwargs (Any): Transaction specifications, such as ``value``.
Returns:
:class:`~ape.ape.transactions.TransactionAPI`
"""
|
Encode a unique type of transaction that allows contracts to be created
from other contracts, such as
`EIP-5202 <https://eips.ethereum.org/EIPS/eip-5202>`__
or Starknet's ``Declare`` transaction type.
Args:
contract_type (``ContractType``): The type of contract to create a blueprint for.
This is the type of contract that will get created by factory contracts.
*args (Any): Calldata, if applicable.
**kwargs (Any): Transaction specifications, such as ``value``.
Returns:
:class:`~ape.ape.transactions.TransactionAPI`
|
encode_contract_blueprint
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def decode_receipt(self, data: dict) -> "ReceiptAPI":
"""
Convert data to :class:`~ape.api.transactions.ReceiptAPI`.
Args:
data (Dict): A dictionary of Receipt properties.
Returns:
:class:`~ape.api.transactions.ReceiptAPI`
"""
|
Convert data to :class:`~ape.api.transactions.ReceiptAPI`.
Args:
data (Dict): A dictionary of Receipt properties.
Returns:
:class:`~ape.api.transactions.ReceiptAPI`
|
decode_receipt
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def decode_block(self, data: dict) -> "BlockAPI":
"""
Decode data to a :class:`~ape.api.providers.BlockAPI`.
Args:
data (Dict): A dictionary of data to decode.
Returns:
:class:`~ape.api.providers.BlockAPI`
"""
|
Decode data to a :class:`~ape.api.providers.BlockAPI`.
Args:
data (Dict): A dictionary of data to decode.
Returns:
:class:`~ape.api.providers.BlockAPI`
|
decode_block
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def networks(self) -> dict[str, "NetworkAPI"]:
"""
A dictionary of network names mapped to their API implementation.
Returns:
dict[str, :class:`~ape.api.networks.NetworkAPI`]
"""
return {
**self._networks_from_evmchains,
**self._networks_from_plugins,
**self._custom_networks,
}
|
A dictionary of network names mapped to their API implementation.
Returns:
dict[str, :class:`~ape.api.networks.NetworkAPI`]
|
networks
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def add_network(self, network_name: str, network: "NetworkAPI"):
"""
Attach a new network to an ecosystem (e.g. L2 networks like Optimism).
Raises:
:class:`~ape.exceptions.NetworkError`: When the network already exists.
Args:
network_name (str): The name of the network to add.
network (:class:`~ape.api.networks.NetworkAPI`): The network to add.
"""
if network_name in self.networks:
raise NetworkError(f"Unable to overwrite existing network '{network_name}'.")
else:
self.networks[network_name] = network
|
Attach a new network to an ecosystem (e.g. L2 networks like Optimism).
Raises:
:class:`~ape.exceptions.NetworkError`: When the network already exists.
Args:
network_name (str): The name of the network to add.
network (:class:`~ape.api.networks.NetworkAPI`): The network to add.
|
add_network
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def default_network_name(self) -> str:
"""
The name of the default network in this ecosystem.
Returns:
str
"""
if network := self._default_network:
# Was set programmatically.
return network
networks = self.networks
if network := self.config.get("default_network"):
# Default found in config. Ensure is an installed network.
if network in networks:
return network
if LOCAL_NETWORK_NAME in networks:
# Default to the LOCAL_NETWORK_NAME, at last resort.
return LOCAL_NETWORK_NAME
elif len(networks) >= 1:
# Use the first network.
key = next(iter(networks.keys()))
return networks[key].name
# Very unlikely scenario.
raise NetworkError("No networks found.")
|
The name of the default network in this ecosystem.
Returns:
str
|
default_network_name
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def set_default_network(self, network_name: str):
"""
Change the default network.
Raises:
:class:`~ape.exceptions.NetworkError`: When the network does not exist.
Args:
network_name (str): The name of the default network to switch to.
"""
if network_name in self.networks:
self._default_network = network_name
else:
raise NetworkNotFoundError(network_name, ecosystem=self.name, options=self.networks)
|
Change the default network.
Raises:
:class:`~ape.exceptions.NetworkError`: When the network does not exist.
Args:
network_name (str): The name of the default network to switch to.
|
set_default_network
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def encode_deployment(
self, deployment_bytecode: HexBytes, abi: "ConstructorABI", *args, **kwargs
) -> "TransactionAPI":
"""
Create a deployment transaction in the given ecosystem.
This may require connecting to other networks.
Args:
deployment_bytecode (HexBytes): The bytecode to deploy.
abi (ConstructorABI): The constructor interface of the contract.
*args (Any): Constructor arguments.
**kwargs (Any): Transaction arguments.
Returns:
class:`~ape.api.transactions.TransactionAPI`
"""
|
Create a deployment transaction in the given ecosystem.
This may require connecting to other networks.
Args:
deployment_bytecode (HexBytes): The bytecode to deploy.
abi (ConstructorABI): The constructor interface of the contract.
*args (Any): Constructor arguments.
**kwargs (Any): Transaction arguments.
Returns:
class:`~ape.api.transactions.TransactionAPI`
|
encode_deployment
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def encode_transaction(
self, address: AddressType, abi: "MethodABI", *args, **kwargs
) -> "TransactionAPI":
"""
Encode a transaction object from a contract function's ABI and call arguments.
Additionally, update the transaction arguments with the overrides in ``kwargs``.
Args:
address (:class:`~ape.types.address.AddressType`): The address of the contract.
abi (``MethodABI``): The function to call on the contract.
*args (Any): Function arguments.
**kwargs (Any): Transaction arguments.
Returns:
class:`~ape.api.transactions.TransactionAPI`
"""
|
Encode a transaction object from a contract function's ABI and call arguments.
Additionally, update the transaction arguments with the overrides in ``kwargs``.
Args:
address (:class:`~ape.types.address.AddressType`): The address of the contract.
abi (``MethodABI``): The function to call on the contract.
*args (Any): Function arguments.
**kwargs (Any): Transaction arguments.
Returns:
class:`~ape.api.transactions.TransactionAPI`
|
encode_transaction
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def decode_logs(self, logs: Sequence[dict], *events: "EventABI") -> Iterator["ContractLog"]:
"""
Decode any contract logs that match the given event ABI from the raw log data.
Args:
logs (Sequence[dict]): A list of raw log data from the chain.
*events (EventABI): Event definitions to decode.
Returns:
Iterator[:class:`~ape.types.ContractLog`]
"""
|
Decode any contract logs that match the given event ABI from the raw log data.
Args:
logs (Sequence[dict]): A list of raw log data from the chain.
*events (EventABI): Event definitions to decode.
Returns:
Iterator[:class:`~ape.types.ContractLog`]
|
decode_logs
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def create_transaction(self, **kwargs) -> "TransactionAPI":
"""
Create a transaction using key-value arguments.
Args:
**kwargs: Everything the transaction needs initialize.
Returns:
class:`~ape.api.transactions.TransactionAPI`
"""
|
Create a transaction using key-value arguments.
Args:
**kwargs: Everything the transaction needs initialize.
Returns:
class:`~ape.api.transactions.TransactionAPI`
|
create_transaction
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def decode_calldata(self, abi: Union["ConstructorABI", "MethodABI"], calldata: bytes) -> dict:
"""
Decode method calldata.
Args:
abi (Union[ConstructorABI, MethodABI]): The method called.
calldata (bytes): The raw calldata bytes.
Returns:
Dict: A mapping of input names to decoded values.
If an input is anonymous, it should use the stringified
index of the input as the key.
"""
|
Decode method calldata.
Args:
abi (Union[ConstructorABI, MethodABI]): The method called.
calldata (bytes): The raw calldata bytes.
Returns:
Dict: A mapping of input names to decoded values.
If an input is anonymous, it should use the stringified
index of the input as the key.
|
decode_calldata
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def encode_calldata(self, abi: Union["ConstructorABI", "MethodABI"], *args: Any) -> HexBytes:
"""
Encode method calldata.
Args:
abi (Union[ConstructorABI, MethodABI]): The ABI of the method called.
*args (Any): The arguments given to the method.
Returns:
HexBytes: The encoded calldata of the arguments to the given method.
"""
|
Encode method calldata.
Args:
abi (Union[ConstructorABI, MethodABI]): The ABI of the method called.
*args (Any): The arguments given to the method.
Returns:
HexBytes: The encoded calldata of the arguments to the given method.
|
encode_calldata
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def decode_returndata(self, abi: "MethodABI", raw_data: bytes) -> Any:
"""
Get the result of a contract call.
Arg:
abi (MethodABI): The method called.
raw_data (bytes): Raw returned data.
Returns:
Any: All of the values returned from the contract function.
"""
|
Get the result of a contract call.
Arg:
abi (MethodABI): The method called.
raw_data (bytes): Raw returned data.
Returns:
Any: All of the values returned from the contract function.
|
decode_returndata
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def get_deployment_address( # type: ignore[empty-body]
self,
address: AddressType,
nonce: int,
) -> AddressType:
"""
Calculate the deployment address of a contract before it is deployed.
This is useful if the address is an argument to another contract's deployment
and you have not yet deployed the first contract yet.
"""
|
Calculate the deployment address of a contract before it is deployed.
This is useful if the address is an argument to another contract's deployment
and you have not yet deployed the first contract yet.
|
get_deployment_address
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def get_network(self, network_name: str) -> "NetworkAPI":
"""
Get the network for the given name.
Args:
network_name (str): The name of the network to get.
Raises:
:class:`~ape.exceptions.NetworkNotFoundError`: When the network is not present.
Returns:
:class:`~ape.api.networks.NetworkAPI`
"""
names = {network_name, network_name.replace("-", "_"), network_name.replace("_", "-")}
networks = self.networks
for name in names:
if name in networks:
return networks[name]
elif name == "custom":
# Is an adhoc-custom network NOT from config.
return self.custom_network
raise NetworkNotFoundError(network_name, ecosystem=self.name, options=networks)
|
Get the network for the given name.
Args:
network_name (str): The name of the network to get.
Raises:
:class:`~ape.exceptions.NetworkNotFoundError`: When the network is not present.
Returns:
:class:`~ape.api.networks.NetworkAPI`
|
get_network
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def get_network_data(
self, network_name: str, provider_filter: Optional[Collection[str]] = None
) -> dict:
"""
Get a dictionary of data about providers in the network.
**NOTE**: The keys are added in an opinionated order for nicely
translating into ``yaml``.
Args:
network_name (str): The name of the network to get provider data from.
provider_filter (Optional[Collection[str]]): Optionally filter the providers
by name.
Returns:
dict: A dictionary containing the providers in a network.
"""
data: dict[str, Any] = {"name": str(network_name)}
# Only add isDefault key when True
if network_name == self.default_network_name:
data["isDefault"] = True
data["providers"] = []
network = self[network_name]
if network.explorer:
data["explorer"] = str(network.explorer.name)
for provider_name in network.providers:
if provider_filter and provider_name not in provider_filter:
continue
provider_data: dict = {"name": str(provider_name)}
# Only add isDefault key when True
if provider_name == network.default_provider_name:
provider_data["isDefault"] = True
data["providers"].append(provider_data)
return data
|
Get a dictionary of data about providers in the network.
**NOTE**: The keys are added in an opinionated order for nicely
translating into ``yaml``.
Args:
network_name (str): The name of the network to get provider data from.
provider_filter (Optional[Collection[str]]): Optionally filter the providers
by name.
Returns:
dict: A dictionary containing the providers in a network.
|
get_network_data
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def get_python_types( # type: ignore[empty-body]
self, abi_type: "ABIType"
) -> Union[type, Sequence]:
"""
Get the Python types for a given ABI type.
Args:
abi_type (``ABIType``): The ABI type to get the Python types for.
Returns:
Union[Type, Sequence]: The Python types for the given ABI type.
"""
|
Get the Python types for a given ABI type.
Args:
abi_type (``ABIType``): The ABI type to get the Python types for.
Returns:
Union[Type, Sequence]: The Python types for the given ABI type.
|
get_python_types
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def decode_custom_error(
self,
data: HexBytes,
address: AddressType,
**kwargs,
) -> Optional[CustomError]:
"""
Decode a custom error class from an ABI defined in a contract.
Args:
data (HexBytes): The error data containing the selector
and input data.
address (AddressType): The address of the contract containing
the error.
**kwargs: Additional init kwargs for the custom error class.
Returns:
Optional[CustomError]: If it able to decode one, else ``None``.
"""
|
Decode a custom error class from an ABI defined in a contract.
Args:
data (HexBytes): The error data containing the selector
and input data.
address (AddressType): The address of the contract containing
the error.
**kwargs: Additional init kwargs for the custom error class.
Returns:
Optional[CustomError]: If it able to decode one, else ``None``.
|
decode_custom_error
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def chain_id(self) -> int:
"""
The ID of the blockchain.
**NOTE**: Unless overridden, returns same as
:py:attr:`ape.api.providers.ProviderAPI.chain_id`.
"""
if (
self.provider.network.name == self.name
and self.provider.network.ecosystem.name == self.ecosystem.name
):
# Ensure 'active_provider' is actually (seemingly) connected
# to this network.
return self.provider.chain_id
raise NetworkError(
"Unable to reference provider to get `chain_id`: "
f"Network '{self.name}' is detached and information is missing."
)
|
The ID of the blockchain.
**NOTE**: Unless overridden, returns same as
:py:attr:`ape.api.providers.ProviderAPI.chain_id`.
|
chain_id
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def transaction_acceptance_timeout(self) -> int:
"""
The amount of time to wait for a transaction to be accepted on the network.
Does not include waiting for block-confirmations. Defaults to two minutes.
Local networks use smaller timeouts.
"""
return self.config.get(
"transaction_acceptance_timeout", DEFAULT_TRANSACTION_ACCEPTANCE_TIMEOUT
)
|
The amount of time to wait for a transaction to be accepted on the network.
Does not include waiting for block-confirmations. Defaults to two minutes.
Local networks use smaller timeouts.
|
transaction_acceptance_timeout
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def explorer(self) -> Optional["ExplorerAPI"]:
"""
The block-explorer for the given network.
Returns:
:class:`ape.api.explorers.ExplorerAPI`, optional
"""
chain_id = None if self.network_manager.active_provider is None else self.provider.chain_id
for plugin_name, plugin_tuple in self._plugin_explorers:
ecosystem_name, network_name, explorer_class = plugin_tuple
# Check for explicitly configured custom networks
plugin_config = self.config_manager.get_config(plugin_name)
has_explorer_config = (
plugin_config
and self.ecosystem.name in plugin_config
and self.name in plugin_config[self.ecosystem.name]
)
# Return the first registered explorer (skipping any others)
if self.ecosystem.name == ecosystem_name and (
self.name == network_name or has_explorer_config
):
return explorer_class(name=plugin_name, network=self)
elif chain_id is not None and explorer_class.supports_chain(chain_id):
# NOTE: Adhoc networks will likely reach here.
return explorer_class(name=plugin_name, network=self)
return None # May not have an block explorer
|
The block-explorer for the given network.
Returns:
:class:`ape.api.explorers.ExplorerAPI`, optional
|
explorer
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def is_mainnet(self) -> bool:
"""
True when the network is the mainnet network for the ecosystem.
"""
cfg_is_mainnet: Optional[bool] = self.config.get("is_mainnet")
if cfg_is_mainnet is not None:
return cfg_is_mainnet
return self.name == "mainnet"
|
True when the network is the mainnet network for the ecosystem.
|
is_mainnet
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def providers(self): # -> dict[str, Partial[ProviderAPI]]
"""
The providers of the network, such as Infura, Alchemy, or Node.
Returns:
dict[str, partial[:class:`~ape.api.providers.ProviderAPI`]]
"""
providers = {}
for _, plugin_tuple in self._get_plugin_providers():
ecosystem_name, network_name, provider_class = plugin_tuple
provider_name = (
provider_class.__module__.split(".")[0].replace("_", "-").replace("ape-", "")
)
is_custom_with_config = self._is_custom and self.default_provider_name == provider_name
# NOTE: Custom networks that are NOT from config must work with any provider.
# Also, ensure we are only adding forked providers for forked networks and
# non-forking providers for non-forked networks. For custom networks, it
# can be trickier (see last condition).
# TODO: In 0.9, add a better way for class-level ForkedProviders to define
# themselves as "Fork" providers.
if (
(self.ecosystem.name == ecosystem_name and self.name == network_name)
or self.is_adhoc
or (
is_custom_with_config
and (
(self.is_fork and "Fork" in provider_class.__name__)
or (not self.is_fork and "Fork" not in provider_class.__name__)
)
and provider_class.__name__
== "Node" # Ensure uses Node class instead of GethDev
)
):
# NOTE: Lazily load provider config
provider_name = provider_class.NAME or provider_name
providers[provider_name] = partial(
provider_class,
name=provider_name,
network=self,
)
# Any EVM-chain works with node provider.
if "node" not in providers and self.name in self.ecosystem._networks_from_evmchains:
# NOTE: Arbitrarily using sepolia to access the Node class.
node_provider_cls = self.network_manager.ethereum.sepolia.get_provider("node").__class__
providers["node"] = partial(node_provider_cls, name="node", network=self)
return providers
|
The providers of the network, such as Infura, Alchemy, or Node.
Returns:
dict[str, partial[:class:`~ape.api.providers.ProviderAPI`]]
|
providers
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def get_provider(
self,
provider_name: Optional[str] = None,
provider_settings: Optional[dict] = None,
connect: bool = False,
):
"""
Get a provider for the given name. If given ``None``, returns the default provider.
Args:
provider_name (str, optional): The name of the provider to get. Defaults to ``None``.
When ``None``, returns the default provider.
provider_settings (dict, optional): Settings to apply to the provider. Defaults to
``None``.
connect (bool): Set to ``True`` when you also want the provider to connect.
Returns:
:class:`~ape.api.providers.ProviderAPI`
"""
if not (provider_name := provider_name or self.default_provider_name):
raise NetworkError(
f"No default provider for network '{self.name}'. "
"Set one in your pyproject.toml/ape-config.yaml file:\n"
f"\n{self.ecosystem.name}:"
f"\n {self.name}:"
"\n default_provider: <DEFAULT_PROVIDER>"
)
provider_settings = provider_settings or {}
if ":" in provider_name:
# NOTE: Shortcut that allows `--network ecosystem:network:http://...` to work
provider_settings["uri"] = provider_name
provider_name = "node"
elif provider_name.endswith(".ipc"):
provider_settings["ipc_path"] = provider_name
provider_name = "node"
if provider_name in self.providers:
provider = self.providers[provider_name](provider_settings=provider_settings)
return _connect_provider(provider) if connect else provider
elif self.is_fork:
# If it can fork Ethereum (and we are asking for it) assume it can fork this one.
# TODO: Refactor this approach to work for custom-forked non-EVM networks.
common_forking_providers = self.network_manager.ethereum.mainnet_fork.providers
if provider_name in common_forking_providers:
provider = common_forking_providers[provider_name](
provider_settings=provider_settings,
network=self,
)
return _connect_provider(provider) if connect else provider
raise ProviderNotFoundError(
provider_name,
network=self.name,
ecosystem=self.ecosystem.name,
options=self.providers,
)
|
Get a provider for the given name. If given ``None``, returns the default provider.
Args:
provider_name (str, optional): The name of the provider to get. Defaults to ``None``.
When ``None``, returns the default provider.
provider_settings (dict, optional): Settings to apply to the provider. Defaults to
``None``.
connect (bool): Set to ``True`` when you also want the provider to connect.
Returns:
:class:`~ape.api.providers.ProviderAPI`
|
get_provider
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def use_provider(
self,
provider: Union[str, "ProviderAPI"],
provider_settings: Optional[dict] = None,
disconnect_after: bool = False,
disconnect_on_exit: bool = True,
) -> ProviderContextManager:
"""
Use and connect to a provider in a temporary context. When entering the context, it calls
method :meth:`ape.api.providers.ProviderAPI.connect` and when exiting, it calls
method :meth:`ape.api.providers.ProviderAPI.disconnect`.
Usage example::
from ape import networks
mainnet = networks.ethereum.mainnet # An instance of NetworkAPI
with mainnet.use_provider("infura"):
...
Args:
provider (Union[str, :class:`~ape.api.providers.ProviderAPI`]): The provider
instance or the name of the provider to use.
provider_settings (dict, optional): Settings to apply to the provider.
Defaults to ``None``.
disconnect_after (bool): Set to ``True`` to force a disconnect after ending
the context. This defaults to ``False`` so you can re-connect to the
same network, such as in a multi-chain testing scenario.
disconnect_on_exit (bool): Whether to disconnect on the exit of the python
session. Defaults to ``True``.
Returns:
:class:`~ape.api.networks.ProviderContextManager`
"""
settings = provider_settings or {}
# NOTE: The main reason we allow a provider instance here is to avoid unnecessarily
# re-initializing the class.
provider_obj = (
self.get_provider(provider_name=provider, provider_settings=settings, connect=True)
if isinstance(provider, str)
else provider
)
return ProviderContextManager(
provider=provider_obj,
disconnect_after=disconnect_after,
disconnect_on_exit=disconnect_on_exit,
)
|
Use and connect to a provider in a temporary context. When entering the context, it calls
method :meth:`ape.api.providers.ProviderAPI.connect` and when exiting, it calls
method :meth:`ape.api.providers.ProviderAPI.disconnect`.
Usage example::
from ape import networks
mainnet = networks.ethereum.mainnet # An instance of NetworkAPI
with mainnet.use_provider("infura"):
...
Args:
provider (Union[str, :class:`~ape.api.providers.ProviderAPI`]): The provider
instance or the name of the provider to use.
provider_settings (dict, optional): Settings to apply to the provider.
Defaults to ``None``.
disconnect_after (bool): Set to ``True`` to force a disconnect after ending
the context. This defaults to ``False`` so you can re-connect to the
same network, such as in a multi-chain testing scenario.
disconnect_on_exit (bool): Whether to disconnect on the exit of the python
session. Defaults to ``True``.
Returns:
:class:`~ape.api.networks.ProviderContextManager`
|
use_provider
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def default_provider_name(self) -> Optional[str]:
"""
The name of the default provider or ``None``.
Returns:
Optional[str]
"""
provider_from_config: str
if provider := self._default_provider:
# Was set programmatically.
return provider
elif provider_from_config := self.config.get("default_provider"):
# The default is found in the Network's config class.
return provider_from_config
elif len(self.providers) > 0:
# No default set anywhere - use the first installed.
return list(self.providers)[0]
# There are no providers at all for this network.
return None
|
The name of the default provider or ``None``.
Returns:
Optional[str]
|
default_provider_name
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def set_default_provider(self, provider_name: str):
"""
Change the default provider.
Raises:
:class:`~ape.exceptions.NetworkError`: When the given provider is not found.
Args:
provider_name (str): The name of the provider to switch to.
"""
if provider_name in self.providers:
self._default_provider = provider_name
else:
raise NetworkError(f"Provider '{provider_name}' not found in network '{self.choice}'.")
|
Change the default provider.
Raises:
:class:`~ape.exceptions.NetworkError`: When the given provider is not found.
Args:
provider_name (str): The name of the provider to switch to.
|
set_default_provider
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def use_default_provider(
self,
provider_settings: Optional[dict] = None,
disconnect_after: bool = False,
) -> ProviderContextManager:
"""
Temporarily connect and use the default provider. When entering the context, it calls
method :meth:`ape.api.providers.ProviderAPI.connect` and when exiting, it calls
method :meth:`ape.api.providers.ProviderAPI.disconnect`.
**NOTE**: If multiple providers exist, uses whatever was "first" registered.
Usage example::
from ape import networks
mainnet = networks.ethereum.mainnet # An instance of NetworkAPI
with mainnet.use_default_provider():
...
Args:
provider_settings (dict, optional): Settings to override the provider.
disconnect_after (bool): Set to ``True`` to force a disconnect after ending
the context. This defaults to ``False`` so you can re-connect to the
same network, such as in a multi-chain testing scenario.
Returns:
:class:`~ape.api.networks.ProviderContextManager`
"""
if self.default_provider:
settings = provider_settings or {}
return self.use_provider(
self.default_provider.name,
provider_settings=settings,
disconnect_after=disconnect_after,
)
raise NetworkError(f"No providers for network '{self.name}'.")
|
Temporarily connect and use the default provider. When entering the context, it calls
method :meth:`ape.api.providers.ProviderAPI.connect` and when exiting, it calls
method :meth:`ape.api.providers.ProviderAPI.disconnect`.
**NOTE**: If multiple providers exist, uses whatever was "first" registered.
Usage example::
from ape import networks
mainnet = networks.ethereum.mainnet # An instance of NetworkAPI
with mainnet.use_default_provider():
...
Args:
provider_settings (dict, optional): Settings to override the provider.
disconnect_after (bool): Set to ``True`` to force a disconnect after ending
the context. This defaults to ``False`` so you can re-connect to the
same network, such as in a multi-chain testing scenario.
Returns:
:class:`~ape.api.networks.ProviderContextManager`
|
use_default_provider
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def publish_contract(self, address: AddressType):
"""
A convenience method to publish a contract to the explorer.
Raises:
:class:`~ape.exceptions.NetworkError`: When there is no explorer for this network.
Args:
address (:class:`~ape.types.address.AddressType`): The address of the contract.
"""
if not self.explorer:
raise NetworkError("Unable to publish contract - no explorer plugin installed.")
logger.info(f"Publishing and verifying contract using '{self.explorer.name}'.")
self.explorer.publish_contract(address)
|
A convenience method to publish a contract to the explorer.
Raises:
:class:`~ape.exceptions.NetworkError`: When there is no explorer for this network.
Args:
address (:class:`~ape.types.address.AddressType`): The address of the contract.
|
publish_contract
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def verify_chain_id(self, chain_id: int):
"""
Verify a chain ID for this network.
Args:
chain_id (int): The chain ID to verify.
Raises:
:class:`~ape.exceptions.NetworkMismatchError`: When the network is
not local or adhoc and has a different hardcoded chain ID than
the given one.
"""
if self.name not in ("custom", LOCAL_NETWORK_NAME) and self.chain_id != chain_id:
raise NetworkMismatchError(chain_id, self)
|
Verify a chain ID for this network.
Args:
chain_id (int): The chain ID to verify.
Raises:
:class:`~ape.exceptions.NetworkMismatchError`: When the network is
not local or adhoc and has a different hardcoded chain ID than
the given one.
|
verify_chain_id
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def upstream_provider(self) -> "UpstreamProvider":
"""
The provider used when requesting data before the local fork.
Set this in your config under the network settings.
When not set, will attempt to use the default provider, if one
exists.
"""
config_choice: str = self.config.get("upstream_provider")
if provider_name := config_choice or self.upstream_network.default_provider_name:
return self.upstream_network.get_provider(provider_name)
raise NetworkError(f"Upstream network '{self.upstream_network}' has no providers.")
|
The provider used when requesting data before the local fork.
Set this in your config under the network settings.
When not set, will attempt to use the default provider, if one
exists.
|
upstream_provider
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def create_network_type(chain_id: int, network_id: int, is_fork: bool = False) -> type[NetworkAPI]:
"""
Easily create a :class:`~ape.api.networks.NetworkAPI` subclass.
"""
BaseNetwork = ForkedNetworkAPI if is_fork else NetworkAPI
class network_def(BaseNetwork): # type: ignore
@property
def chain_id(self) -> int:
return chain_id
@property
def network_id(self) -> int:
return network_id
return network_def
|
Easily create a :class:`~ape.api.networks.NetworkAPI` subclass.
|
create_network_type
|
python
|
ApeWorX/ape
|
src/ape/api/networks.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/networks.py
|
Apache-2.0
|
def package_id(self) -> str:
"""
The full name of the package, used for storage.
Example: ``OpenZeppelin/openzeppelin-contracts``.
"""
|
The full name of the package, used for storage.
Example: ``OpenZeppelin/openzeppelin-contracts``.
|
package_id
|
python
|
ApeWorX/ape
|
src/ape/api/projects.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/projects.py
|
Apache-2.0
|
def version_id(self) -> str:
"""
The ID to use as the sub-directory in the download cache.
Most often, this is either a version number or a branch name.
"""
|
The ID to use as the sub-directory in the download cache.
Most often, this is either a version number or a branch name.
|
version_id
|
python
|
ApeWorX/ape
|
src/ape/api/projects.py
|
https://github.com/ApeWorX/ape/blob/master/src/ape/api/projects.py
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.