code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
from __future__ import annotations from sklearn.preprocessing import StandardScaler as sk_StandardScaler from safeds.data.tabular.containers import Table from safeds.data.tabular.transformation._table_transformer import InvertibleTableTransformer from safeds.exceptions import NonNumericColumnError, TransformerNotFittedError, UnknownColumnNameError class StandardScaler(InvertibleTableTransformer): """The StandardScaler transforms column values to a range by removing the mean and scaling to unit variance.""" def __init__(self) -> None: self._column_names: list[str] | None = None self._wrapped_transformer: sk_StandardScaler | None = None def fit(self, table: Table, column_names: list[str] | None) -> StandardScaler: """ Learn a transformation for a set of columns in a table. This transformer is not modified. Parameters ---------- table : Table The table used to fit the transformer. column_names : list[str] | None The list of columns from the table used to fit the transformer. If `None`, all columns are used. Returns ------- fitted_transformer : TableTransformer The fitted transformer. Raises ------ UnknownColumnNameError If column_names contain a column name that is missing in the table. NonNumericColumnError If at least one of the specified columns in the table contains non-numerical data. ValueError If the table contains 0 rows. """ if column_names is None: column_names = table.column_names else: missing_columns = sorted(set(column_names) - set(table.column_names)) if len(missing_columns) > 0: raise UnknownColumnNameError(missing_columns) if table.number_of_rows == 0: raise ValueError("The StandardScaler cannot be fitted because the table contains 0 rows") if ( table.keep_only_columns(column_names).remove_columns_with_non_numerical_values().number_of_columns < table.keep_only_columns(column_names).number_of_columns ): raise NonNumericColumnError( str( sorted( set(table.keep_only_columns(column_names).column_names) - set( table.keep_only_columns(column_names) .remove_columns_with_non_numerical_values() .column_names, ), ), ), ) wrapped_transformer = sk_StandardScaler() wrapped_transformer.fit(table._data[column_names]) result = StandardScaler() result._wrapped_transformer = wrapped_transformer result._column_names = column_names return result def transform(self, table: Table) -> Table: """ Apply the learned transformation to a table. The table is not modified. Parameters ---------- table : Table The table to which the learned transformation is applied. Returns ------- transformed_table : Table The transformed table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. UnknownColumnNameError If the input table does not contain all columns used to fit the transformer. NonNumericColumnError If at least one of the columns in the input table that is used to fit contains non-numerical data. ValueError If the table contains 0 rows. """ # Transformer has not been fitted yet if self._wrapped_transformer is None or self._column_names is None: raise TransformerNotFittedError # Input table does not contain all columns used to fit the transformer missing_columns = sorted(set(self._column_names) - set(table.column_names)) if len(missing_columns) > 0: raise UnknownColumnNameError(missing_columns) if table.number_of_rows == 0: raise ValueError("The StandardScaler cannot transform the table because it contains 0 rows") if ( table.keep_only_columns(self._column_names).remove_columns_with_non_numerical_values().number_of_columns < table.keep_only_columns(self._column_names).number_of_columns ): raise NonNumericColumnError( str( sorted( set(table.keep_only_columns(self._column_names).column_names) - set( table.keep_only_columns(self._column_names) .remove_columns_with_non_numerical_values() .column_names, ), ), ), ) data = table._data.copy() data.columns = table.column_names data[self._column_names] = self._wrapped_transformer.transform(data[self._column_names]) return Table._from_pandas_dataframe(data) def inverse_transform(self, transformed_table: Table) -> Table: """ Undo the learned transformation. The table is not modified. Parameters ---------- transformed_table : Table The table to be transformed back to the original version. Returns ------- table : Table The original table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. UnknownColumnNameError If the input table does not contain all columns used to fit the transformer. NonNumericColumnError If the transformed columns of the input table contain non-numerical data. ValueError If the table contains 0 rows. """ # Transformer has not been fitted yet if self._wrapped_transformer is None or self._column_names is None: raise TransformerNotFittedError missing_columns = sorted(set(self._column_names) - set(transformed_table.column_names)) if len(missing_columns) > 0: raise UnknownColumnNameError(missing_columns) if transformed_table.number_of_rows == 0: raise ValueError("The StandardScaler cannot transform the table because it contains 0 rows") if ( transformed_table.keep_only_columns(self._column_names) .remove_columns_with_non_numerical_values() .number_of_columns < transformed_table.keep_only_columns(self._column_names).number_of_columns ): raise NonNumericColumnError( str( sorted( set(transformed_table.keep_only_columns(self._column_names).column_names) - set( transformed_table.keep_only_columns(self._column_names) .remove_columns_with_non_numerical_values() .column_names, ), ), ), ) data = transformed_table._data.copy() data.columns = transformed_table.column_names data[self._column_names] = self._wrapped_transformer.inverse_transform(data[self._column_names]) return Table._from_pandas_dataframe(data) def is_fitted(self) -> bool: """ Check if the transformer is fitted. Returns ------- is_fitted : bool Whether the transformer is fitted. """ return self._wrapped_transformer is not None def get_names_of_added_columns(self) -> list[str]: """ Get the names of all new columns that have been added by the StandardScaler. Returns ------- added_columns : list[str] A list of names of the added columns, ordered as they will appear in the table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ if not self.is_fitted(): raise TransformerNotFittedError return [] # (Must implement abstract method, cannot instantiate class otherwise.) def get_names_of_changed_columns(self) -> list[str]: """ Get the names of all columns that may have been changed by the StandardScaler. Returns ------- changed_columns : list[str] The list of (potentially) changed column names, as passed to fit. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ if self._column_names is None: raise TransformerNotFittedError return self._column_names def get_names_of_removed_columns(self) -> list[str]: """ Get the names of all columns that have been removed by the StandardScaler. Returns ------- removed_columns : list[str] A list of names of the removed columns, ordered as they appear in the table the StandardScaler was fitted on. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ if not self.is_fitted(): raise TransformerNotFittedError return []
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/data/tabular/transformation/_standard_scaler.py
0.964422
0.495667
_standard_scaler.py
pypi
from __future__ import annotations import warnings from collections import Counter from typing import Any import numpy as np from safeds.data.tabular.containers import Column, Table from safeds.data.tabular.transformation._table_transformer import ( InvertibleTableTransformer, ) from safeds.exceptions import ( NonNumericColumnError, TransformerNotFittedError, UnknownColumnNameError, ValueNotPresentWhenFittedError, ) class OneHotEncoder(InvertibleTableTransformer): """ A way to deal with categorical features that is particularly useful for unordered (i.e. nominal) data. It replaces a column with a set of columns, each representing a unique value in the original column. The value of each new column is 1 if the original column had that value, and 0 otherwise. Take the following table as an example: | col1 | |------| | "a" | | "b" | | "c" | | "a" | The one-hot encoding of this table is: | col1__a | col1__b | col1__c | |---------|---------|---------| | 1 | 0 | 0 | | 0 | 1 | 0 | | 0 | 0 | 1 | | 1 | 0 | 0 | The name "one-hot" comes from the fact that each row has exactly one 1 in it, and the rest of the values are 0s. One-hot encoding is closely related to dummy variable / indicator variables, which are used in statistics. Examples -------- >>> from safeds.data.tabular.containers import Table >>> from safeds.data.tabular.transformation import OneHotEncoder >>> table = Table({"col1": ["a", "b", "c", "a"]}) >>> transformer = OneHotEncoder() >>> transformer.fit_and_transform(table, ["col1"]) col1__a col1__b col1__c 0 1.0 0.0 0.0 1 0.0 1.0 0.0 2 0.0 0.0 1.0 3 1.0 0.0 0.0 """ def __init__(self) -> None: # Maps each old column to (list of) new columns created from it: self._column_names: dict[str, list[str]] | None = None # Maps concrete values (tuples of old column and value) to corresponding new column names: self._value_to_column: dict[tuple[str, Any], str] | None = None # Maps nan values (str of old column) to corresponding new column name self._value_to_column_nans: dict[str, str] | None = None # noinspection PyProtectedMember def fit(self, table: Table, column_names: list[str] | None) -> OneHotEncoder: """ Learn a transformation for a set of columns in a table. This transformer is not modified. Parameters ---------- table : Table The table used to fit the transformer. column_names : list[str] | None The list of columns from the table used to fit the transformer. If `None`, all columns are used. Returns ------- fitted_transformer : TableTransformer The fitted transformer. Raises ------ UnknownColumnNameError If column_names contain a column name that is missing in the table. ValueError If the table contains 0 rows. """ if column_names is None: column_names = table.column_names else: missing_columns = sorted(set(column_names) - set(table.column_names)) if len(missing_columns) > 0: raise UnknownColumnNameError(missing_columns) if table.number_of_rows == 0: raise ValueError("The OneHotEncoder cannot be fitted because the table contains 0 rows") if ( table._as_table() .keep_only_columns(column_names) .remove_columns_with_non_numerical_values() .number_of_columns > 0 ): warnings.warn( ( "The columns" f" {table._as_table().keep_only_columns(column_names).remove_columns_with_non_numerical_values().column_names} contain" " numerical data. The OneHotEncoder is designed to encode non-numerical values into numerical" " values" ), UserWarning, stacklevel=2, ) data = table._data.copy() data.columns = table.column_names result = OneHotEncoder() result._column_names = {} result._value_to_column = {} result._value_to_column_nans = {} # Keep track of number of occurrences of column names; # initially all old column names appear exactly once: name_counter = Counter(data.columns) # Iterate through all columns to-be-changed: for column in column_names: result._column_names[column] = [] for element in table.get_column(column).get_unique_values(): base_name = f"{column}__{element}" name_counter[base_name] += 1 new_column_name = base_name # Check if newly created name matches some other existing column name: if name_counter[base_name] > 1: new_column_name += f"#{name_counter[base_name]}" # Update dictionary entries: result._column_names[column] += [new_column_name] if isinstance(element, float) and np.isnan(element): result._value_to_column_nans[column] = new_column_name else: result._value_to_column[(column, element)] = new_column_name return result # noinspection PyProtectedMember def transform(self, table: Table) -> Table: """ Apply the learned transformation to a table. The table is not modified. Parameters ---------- table : Table The table to which the learned transformation is applied. Returns ------- transformed_table : Table The transformed table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. UnknownColumnNameError If the input table does not contain all columns used to fit the transformer. ValueError If the table contains 0 rows. ValueNotPresentWhenFittedError If a column in the to-be-transformed table contains a new value that was not already present in the table the OneHotEncoder was fitted on. """ # Transformer has not been fitted yet if self._column_names is None or self._value_to_column is None or self._value_to_column_nans is None: raise TransformerNotFittedError # Input table does not contain all columns used to fit the transformer missing_columns = sorted(set(self._column_names.keys()) - set(table.column_names)) if len(missing_columns) > 0: raise UnknownColumnNameError(missing_columns) if table.number_of_rows == 0: raise ValueError("The LabelEncoder cannot transform the table because it contains 0 rows") encoded_values = {} for new_column_name in self._value_to_column.values(): encoded_values[new_column_name] = [0.0 for _ in range(table.number_of_rows)] for new_column_name in self._value_to_column_nans.values(): encoded_values[new_column_name] = [0.0 for _ in range(table.number_of_rows)] values_not_present_when_fitted = [] for old_column_name in self._column_names: for i in range(table.number_of_rows): value = table.get_column(old_column_name).get_value(i) try: if isinstance(value, float) and np.isnan(value): new_column_name = self._value_to_column_nans[old_column_name] else: new_column_name = self._value_to_column[(old_column_name, value)] encoded_values[new_column_name][i] = 1.0 except KeyError: # This happens when a column in the to-be-transformed table contains a new value that was not # already present in the table the OneHotEncoder was fitted on. values_not_present_when_fitted.append((value, old_column_name)) for new_column in self._column_names[old_column_name]: table = table.add_column(Column(new_column, encoded_values[new_column])) if len(values_not_present_when_fitted) > 0: raise ValueNotPresentWhenFittedError(values_not_present_when_fitted) # New columns may not be sorted: column_names = [] for name in table.column_names: if name not in self._column_names.keys(): column_names.append(name) else: column_names.extend( [f_name for f_name in self._value_to_column.values() if f_name.startswith(name)] + [f_name for f_name in self._value_to_column_nans.values() if f_name.startswith(name)], ) # Drop old, non-encoded columns: # (Don't do this earlier - we need the old column nams for sorting, # plus we need to prevent the table from possibly having 0 columns temporarily.) table = table.remove_columns(list(self._column_names.keys())) # Apply sorting and return: return table.sort_columns(lambda col1, col2: column_names.index(col1.name) - column_names.index(col2.name)) # noinspection PyProtectedMember def inverse_transform(self, transformed_table: Table) -> Table: """ Undo the learned transformation. The table is not modified. Parameters ---------- transformed_table : Table The table to be transformed back to the original version. Returns ------- table : Table The original table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. UnknownColumnNameError If the input table does not contain all columns used to fit the transformer. NonNumericColumnError If the transformed columns of the input table contain non-numerical data. ValueError If the table contains 0 rows. """ # Transformer has not been fitted yet if self._column_names is None or self._value_to_column is None or self._value_to_column_nans is None: raise TransformerNotFittedError _transformed_column_names = [item for sublist in self._column_names.values() for item in sublist] missing_columns = sorted(set(_transformed_column_names) - set(transformed_table.column_names)) if len(missing_columns) > 0: raise UnknownColumnNameError(missing_columns) if transformed_table.number_of_rows == 0: raise ValueError("The OneHotEncoder cannot inverse transform the table because it contains 0 rows") if transformed_table._as_table().keep_only_columns( _transformed_column_names, ).remove_columns_with_non_numerical_values().number_of_columns < len(_transformed_column_names): raise NonNumericColumnError( str( sorted( set(_transformed_column_names) - set( transformed_table.keep_only_columns(_transformed_column_names) .remove_columns_with_non_numerical_values() .column_names, ), ), ), ) original_columns = {} for original_column_name in self._column_names: original_columns[original_column_name] = [None for _ in range(transformed_table.number_of_rows)] for original_column_name, value in self._value_to_column: constructed_column = self._value_to_column[(original_column_name, value)] for i in range(transformed_table.number_of_rows): if transformed_table.get_column(constructed_column)[i] == 1.0: original_columns[original_column_name][i] = value for original_column_name in self._value_to_column_nans: constructed_column = self._value_to_column_nans[original_column_name] for i in range(transformed_table.number_of_rows): if transformed_table.get_column(constructed_column)[i] == 1.0: original_columns[original_column_name][i] = np.nan table = transformed_table for column_name, encoded_column in original_columns.items(): table = table.add_column(Column(column_name, encoded_column)) column_names = [ ( name if name not in [value for value_list in list(self._column_names.values()) for value in value_list] else list(self._column_names.keys())[ [ list(self._column_names.values()).index(value) for value in list(self._column_names.values()) if name in value ][0] ] ) for name in table.column_names ] # Drop old column names: table = table.remove_columns(list(self._value_to_column.values())) table = table.remove_columns(list(self._value_to_column_nans.values())) return table.sort_columns(lambda col1, col2: column_names.index(col1.name) - column_names.index(col2.name)) def is_fitted(self) -> bool: """ Check if the transformer is fitted. Returns ------- is_fitted : bool Whether the transformer is fitted. """ return ( self._column_names is not None and self._value_to_column is not None and self._value_to_column_nans is not None ) def get_names_of_added_columns(self) -> list[str]: """ Get the names of all new columns that have been added by the OneHotEncoder. Returns ------- added_columns : list[str] A list of names of the added columns, ordered as they will appear in the table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ if self._column_names is None: raise TransformerNotFittedError return [name for column_names in self._column_names.values() for name in column_names] # (Must implement abstract method, cannot instantiate class otherwise.) def get_names_of_changed_columns(self) -> list[str]: """ Get the names of all columns that have been changed by the OneHotEncoder (none). Returns ------- changed_columns : list[str] The empty list. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ if not self.is_fitted(): raise TransformerNotFittedError return [] def get_names_of_removed_columns(self) -> list[str]: """ Get the names of all columns that have been removed by the OneHotEncoder. Returns ------- removed_columns : list[str] A list of names of the removed columns, ordered as they appear in the table the OneHotEncoder was fitted on. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ if self._column_names is None: raise TransformerNotFittedError return list(self._column_names.keys())
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/data/tabular/transformation/_one_hot_encoder.py
0.942639
0.444746
_one_hot_encoder.py
pypi
from __future__ import annotations from sklearn.preprocessing import MinMaxScaler as sk_MinMaxScaler from safeds.data.tabular.containers import Table from safeds.data.tabular.transformation._table_transformer import InvertibleTableTransformer from safeds.exceptions import NonNumericColumnError, TransformerNotFittedError, UnknownColumnNameError class RangeScaler(InvertibleTableTransformer): """ The RangeScaler transforms column values by scaling each value to a given range. Parameters ---------- minimum : float The minimum of the new range after the transformation maximum : float The maximum of the new range after the transformation Raises ------ ValueError If the given minimum is greater or equal to the given maximum """ def __init__(self, minimum: float = 0.0, maximum: float = 1.0): self._column_names: list[str] | None = None self._wrapped_transformer: sk_MinMaxScaler | None = None if minimum >= maximum: raise ValueError('Parameter "maximum" must be higher than parameter "minimum".') self._minimum = minimum self._maximum = maximum def fit(self, table: Table, column_names: list[str] | None) -> RangeScaler: """ Learn a transformation for a set of columns in a table. This transformer is not modified. Parameters ---------- table : Table The table used to fit the transformer. column_names : list[str] | None The list of columns from the table used to fit the transformer. If `None`, all columns are used. Returns ------- fitted_transformer : TableTransformer The fitted transformer. Raises ------ UnknownColumnNameError If column_names contain a column name that is missing in the table. NonNumericColumnError If at least one of the specified columns in the table contains non-numerical data. ValueError If the table contains 0 rows. """ if column_names is None: column_names = table.column_names else: missing_columns = sorted(set(column_names) - set(table.column_names)) if len(missing_columns) > 0: raise UnknownColumnNameError(missing_columns) if table.number_of_rows == 0: raise ValueError("The RangeScaler cannot be fitted because the table contains 0 rows") if ( table.keep_only_columns(column_names).remove_columns_with_non_numerical_values().number_of_columns < table.keep_only_columns(column_names).number_of_columns ): raise NonNumericColumnError( str( sorted( set(table.keep_only_columns(column_names).column_names) - set( table.keep_only_columns(column_names) .remove_columns_with_non_numerical_values() .column_names, ), ), ), ) wrapped_transformer = sk_MinMaxScaler((self._minimum, self._maximum)) wrapped_transformer.fit(table._data[column_names]) result = RangeScaler() result._wrapped_transformer = wrapped_transformer result._column_names = column_names return result def transform(self, table: Table) -> Table: """ Apply the learned transformation to a table. The table is not modified. Parameters ---------- table : Table The table to which the learned transformation is applied. Returns ------- transformed_table : Table The transformed table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. UnknownColumnNameError If the input table does not contain all columns used to fit the transformer. NonNumericColumnError If at least one of the columns in the input table that is used to fit contains non-numerical data. ValueError If the table contains 0 rows. """ # Transformer has not been fitted yet if self._wrapped_transformer is None or self._column_names is None: raise TransformerNotFittedError # Input table does not contain all columns used to fit the transformer missing_columns = sorted(set(self._column_names) - set(table.column_names)) if len(missing_columns) > 0: raise UnknownColumnNameError(missing_columns) if table.number_of_rows == 0: raise ValueError("The RangeScaler cannot transform the table because it contains 0 rows") if ( table.keep_only_columns(self._column_names).remove_columns_with_non_numerical_values().number_of_columns < table.keep_only_columns(self._column_names).number_of_columns ): raise NonNumericColumnError( str( sorted( set(table.keep_only_columns(self._column_names).column_names) - set( table.keep_only_columns(self._column_names) .remove_columns_with_non_numerical_values() .column_names, ), ), ), ) data = table._data.copy() data.columns = table.column_names data[self._column_names] = self._wrapped_transformer.transform(data[self._column_names]) return Table._from_pandas_dataframe(data) def inverse_transform(self, transformed_table: Table) -> Table: """ Undo the learned transformation. The table is not modified. Parameters ---------- transformed_table : Table The table to be transformed back to the original version. Returns ------- table : Table The original table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. UnknownColumnNameError If the input table does not contain all columns used to fit the transformer. NonNumericColumnError If the transformed columns of the input table contain non-numerical data. ValueError If the table contains 0 rows. """ # Transformer has not been fitted yet if self._wrapped_transformer is None or self._column_names is None: raise TransformerNotFittedError missing_columns = sorted(set(self._column_names) - set(transformed_table.column_names)) if len(missing_columns) > 0: raise UnknownColumnNameError(missing_columns) if transformed_table.number_of_rows == 0: raise ValueError("The RangeScaler cannot transform the table because it contains 0 rows") if ( transformed_table.keep_only_columns(self._column_names) .remove_columns_with_non_numerical_values() .number_of_columns < transformed_table.keep_only_columns(self._column_names).number_of_columns ): raise NonNumericColumnError( str( sorted( set(transformed_table.keep_only_columns(self._column_names).column_names) - set( transformed_table.keep_only_columns(self._column_names) .remove_columns_with_non_numerical_values() .column_names, ), ), ), ) data = transformed_table._data.copy() data.columns = transformed_table.column_names data[self._column_names] = self._wrapped_transformer.inverse_transform(data[self._column_names]) return Table._from_pandas_dataframe(data) def is_fitted(self) -> bool: """ Check if the transformer is fitted. Returns ------- is_fitted : bool Whether the transformer is fitted. """ return self._wrapped_transformer is not None def get_names_of_added_columns(self) -> list[str]: """ Get the names of all new columns that have been added by the RangeScaler. Returns ------- added_columns : list[str] A list of names of the added columns, ordered as they will appear in the table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ if not self.is_fitted(): raise TransformerNotFittedError return [] # (Must implement abstract method, cannot instantiate class otherwise.) def get_names_of_changed_columns(self) -> list[str]: """ Get the names of all columns that may have been changed by the RangeScaler. Returns ------- changed_columns : list[str] The list of (potentially) changed column names, as passed to fit. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ if self._column_names is None: raise TransformerNotFittedError return self._column_names def get_names_of_removed_columns(self) -> list[str]: """ Get the names of all columns that have been removed by the RangeScaler. Returns ------- removed_columns : list[str] A list of names of the removed columns, ordered as they appear in the table the RangeScaler was fitted on. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ if not self.is_fitted(): raise TransformerNotFittedError return []
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/data/tabular/transformation/_range_scaler.py
0.969728
0.483344
_range_scaler.py
pypi
from __future__ import annotations import warnings from sklearn.preprocessing import OrdinalEncoder as sk_OrdinalEncoder from safeds.data.tabular.containers import Table from safeds.data.tabular.transformation._table_transformer import ( InvertibleTableTransformer, ) from safeds.exceptions import NonNumericColumnError, TransformerNotFittedError, UnknownColumnNameError # noinspection PyProtectedMember class LabelEncoder(InvertibleTableTransformer): """The LabelEncoder encodes one or more given columns into labels.""" def __init__(self) -> None: self._wrapped_transformer: sk_OrdinalEncoder | None = None self._column_names: list[str] | None = None def fit(self, table: Table, column_names: list[str] | None) -> LabelEncoder: """ Learn a transformation for a set of columns in a table. This transformer is not modified. Parameters ---------- table : Table The table used to fit the transformer. column_names : list[str] | None The list of columns from the table used to fit the transformer. If `None`, all columns are used. Returns ------- fitted_transformer : TableTransformer The fitted transformer. Raises ------ UnknownColumnNameError If column_names contain a column name that is missing in the table. ValueError If the table contains 0 rows. """ if column_names is None: column_names = table.column_names else: missing_columns = sorted(set(column_names) - set(table.column_names)) if len(missing_columns) > 0: raise UnknownColumnNameError(missing_columns) if table.number_of_rows == 0: raise ValueError("The LabelEncoder cannot transform the table because it contains 0 rows") if table.keep_only_columns(column_names).remove_columns_with_non_numerical_values().number_of_columns > 0: warnings.warn( ( "The columns" f" {table.keep_only_columns(column_names).remove_columns_with_non_numerical_values().column_names} contain" " numerical data. The LabelEncoder is designed to encode non-numerical values into numerical" " values" ), UserWarning, stacklevel=2, ) wrapped_transformer = sk_OrdinalEncoder() wrapped_transformer.fit(table._data[column_names]) result = LabelEncoder() result._wrapped_transformer = wrapped_transformer result._column_names = column_names return result def transform(self, table: Table) -> Table: """ Apply the learned transformation to a table. The table is not modified. Parameters ---------- table : Table The table to which the learned transformation is applied. Returns ------- transformed_table : Table The transformed table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. UnknownColumnNameError If the input table does not contain all columns used to fit the transformer. ValueError If the table contains 0 rows. """ # Transformer has not been fitted yet if self._wrapped_transformer is None or self._column_names is None: raise TransformerNotFittedError # Input table does not contain all columns used to fit the transformer missing_columns = sorted(set(self._column_names) - set(table.column_names)) if len(missing_columns) > 0: raise UnknownColumnNameError(missing_columns) if table.number_of_rows == 0: raise ValueError("The LabelEncoder cannot transform the table because it contains 0 rows") data = table._data.copy() data.columns = table.column_names data[self._column_names] = self._wrapped_transformer.transform(data[self._column_names]) return Table._from_pandas_dataframe(data) def inverse_transform(self, transformed_table: Table) -> Table: """ Undo the learned transformation. The table is not modified. Parameters ---------- transformed_table : Table The table to be transformed back to the original version. Returns ------- table : Table The original table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. UnknownColumnNameError If the input table does not contain all columns used to fit the transformer. NonNumericColumnError If the specified columns of the input table contain non-numerical data. ValueError If the table contains 0 rows. """ # Transformer has not been fitted yet if self._wrapped_transformer is None or self._column_names is None: raise TransformerNotFittedError missing_columns = sorted(set(self._column_names) - set(transformed_table.column_names)) if len(missing_columns) > 0: raise UnknownColumnNameError(missing_columns) if transformed_table.number_of_rows == 0: raise ValueError("The LabelEncoder cannot inverse transform the table because it contains 0 rows") if transformed_table.keep_only_columns( self._column_names, ).remove_columns_with_non_numerical_values().number_of_columns < len(self._column_names): raise NonNumericColumnError( str( sorted( set(self._column_names) - set( transformed_table.keep_only_columns(self._column_names) .remove_columns_with_non_numerical_values() .column_names, ), ), ), ) data = transformed_table._data.copy() data.columns = transformed_table.column_names data[self._column_names] = self._wrapped_transformer.inverse_transform(data[self._column_names]) return Table._from_pandas_dataframe(data) def is_fitted(self) -> bool: """ Check if the transformer is fitted. Returns ------- is_fitted : bool Whether the transformer is fitted. """ return self._wrapped_transformer is not None def get_names_of_added_columns(self) -> list[str]: """ Get the names of all new columns that have been added by the LabelEncoder. Returns ------- added_columns : list[str] A list of names of the added columns, ordered as they will appear in the table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ if not self.is_fitted(): raise TransformerNotFittedError return [] # (Must implement abstract method, cannot instantiate class otherwise.) def get_names_of_changed_columns(self) -> list[str]: """ Get the names of all columns that may have been changed by the LabelEncoder. Returns ------- changed_columns : list[str] The list of (potentially) changed column names, as passed to fit. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ if self._column_names is None: raise TransformerNotFittedError return self._column_names def get_names_of_removed_columns(self) -> list[str]: """ Get the names of all columns that have been removed by the LabelEncoder. Returns ------- removed_columns : list[str] A list of names of the removed columns, ordered as they appear in the table the LabelEncoder was fitted on. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ if not self.is_fitted(): raise TransformerNotFittedError return []
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/data/tabular/transformation/_label_encoder.py
0.963754
0.537284
_label_encoder.py
pypi
from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING if TYPE_CHECKING: from safeds.data.tabular.containers import Table class TableTransformer(ABC): """Learn a transformation for a set of columns in a `Table` and transform another `Table` with the same columns.""" @abstractmethod def fit(self, table: Table, column_names: list[str] | None) -> TableTransformer: """ Learn a transformation for a set of columns in a table. This transformer is not modified. Parameters ---------- table : Table The table used to fit the transformer. column_names : list[str] | None The list of columns from the table used to fit the transformer. If `None`, all columns are used. Returns ------- fitted_transformer : TableTransformer The fitted transformer. """ @abstractmethod def transform(self, table: Table) -> Table: """ Apply the learned transformation to a table. The table is not modified. Parameters ---------- table : Table The table to which the learned transformation is applied. Returns ------- transformed_table : Table The transformed table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ @abstractmethod def get_names_of_added_columns(self) -> list[str]: """ Get the names of all new columns that have been added by the transformer. Returns ------- added_columns : list[str] A list of names of the added columns, ordered as they will appear in the table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ @abstractmethod def get_names_of_changed_columns(self) -> list[str]: """ Get the names of all columns that have been changed by the transformer. Returns ------- changed_columns : list[str] A list of names of changed columns, ordered as they appear in the table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ @abstractmethod def get_names_of_removed_columns(self) -> list[str]: """ Get the names of all columns that have been removed by the transformer. Returns ------- removed_columns : list[str] A list of names of the removed columns, ordered as they appear in the table the transformer was fitted on. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ @abstractmethod def is_fitted(self) -> bool: """ Check if the transformer is fitted. Returns ------- is_fitted : bool Whether the transformer is fitted. """ def fit_and_transform(self, table: Table, column_names: list[str] | None = None) -> Table: """ Learn a transformation for a set of columns in a table and apply the learned transformation to the same table. The table is not modified. If you also need the fitted transformer, use `fit` and `transform` separately. Parameters ---------- table : Table The table used to fit the transformer. The transformer is then applied to this table. column_names : list[str] | None The list of columns from the table used to fit the transformer. If `None`, all columns are used. Returns ------- transformed_table : Table The transformed table. """ return self.fit(table, column_names).transform(table) class InvertibleTableTransformer(TableTransformer): """A `TableTransformer` that can also undo the learned transformation after it has been applied.""" @abstractmethod def fit(self, table: Table, column_names: list[str] | None) -> InvertibleTableTransformer: """ Learn a transformation for a set of columns in a table. Parameters ---------- table : Table The table used to fit the transformer. column_names : list[str] | None The list of columns from the table used to fit the transformer. If `None`, all columns are used. Returns ------- fitted_transformer : InvertibleTableTransformer The fitted transformer. """ @abstractmethod def inverse_transform(self, transformed_table: Table) -> Table: """ Undo the learned transformation. The table is not modified. Parameters ---------- transformed_table : Table The table to be transformed back to the original version. Returns ------- table : Table The original table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/data/tabular/transformation/_table_transformer.py
0.968291
0.694471
_table_transformer.py
pypi
from __future__ import annotations import warnings from typing import Any import pandas as pd from sklearn.impute import SimpleImputer as sk_SimpleImputer from safeds.data.tabular.containers import Table from safeds.data.tabular.transformation._table_transformer import TableTransformer from safeds.data.tabular.typing import ImputerStrategy from safeds.exceptions import NonNumericColumnError, TransformerNotFittedError, UnknownColumnNameError class Imputer(TableTransformer): """ Replace missing values with the given strategy. Parameters ---------- strategy : ImputerStrategy The strategy used to impute missing values. Use the classes nested inside `Imputer.Strategy` to specify it. Examples -------- >>> from safeds.data.tabular.containers import Column, Table >>> from safeds.data.tabular.transformation import Imputer >>> >>> table = Table.from_columns( ... [ ... Column("a", [1, 3, None]), ... Column("b", [None, 2, 3]), ... ], ... ) >>> transformer = Imputer(Imputer.Strategy.Constant(0)) >>> transformed_table = transformer.fit_and_transform(table) """ class Strategy: class Constant(ImputerStrategy): """ An imputation strategy for imputing missing data with given constant values. Parameters ---------- value : The given value to impute missing values. """ def __init__(self, value: Any): self._value = value def __str__(self) -> str: return f"Constant({self._value})" def _augment_imputer(self, imputer: sk_SimpleImputer) -> None: imputer.strategy = "constant" imputer.fill_value = self._value class Mean(ImputerStrategy): """An imputation strategy for imputing missing data with mean values.""" def __str__(self) -> str: return "Mean" def _augment_imputer(self, imputer: sk_SimpleImputer) -> None: imputer.strategy = "mean" class Median(ImputerStrategy): """An imputation strategy for imputing missing data with median values.""" def __str__(self) -> str: return "Median" def _augment_imputer(self, imputer: sk_SimpleImputer) -> None: imputer.strategy = "median" class Mode(ImputerStrategy): """An imputation strategy for imputing missing data with mode values. The lowest value will be used if there are multiple values with the same highest count.""" def __str__(self) -> str: return "Mode" def _augment_imputer(self, imputer: sk_SimpleImputer) -> None: imputer.strategy = "most_frequent" def __init__(self, strategy: ImputerStrategy): self._strategy = strategy self._wrapped_transformer: sk_SimpleImputer | None = None self._column_names: list[str] | None = None # noinspection PyProtectedMember def fit(self, table: Table, column_names: list[str] | None) -> Imputer: """ Learn a transformation for a set of columns in a table. This transformer is not modified. Parameters ---------- table : Table The table used to fit the transformer. column_names : list[str] | None The list of columns from the table used to fit the transformer. If `None`, all columns are used. Returns ------- fitted_transformer : TableTransformer The fitted transformer. Raises ------ UnknownColumnNameError If column_names contain a column name that is missing in the table ValueError If the table contains 0 rows NonNumericColumnError If the strategy is set to either Mean or Median and the specified columns of the table contain non-numerical data. """ if column_names is None: column_names = table.column_names else: missing_columns = sorted(set(column_names) - set(table.column_names)) if len(missing_columns) > 0: raise UnknownColumnNameError(missing_columns) if table.number_of_rows == 0: raise ValueError("The Imputer cannot be fitted because the table contains 0 rows") if (isinstance(self._strategy, Imputer.Strategy.Mean | Imputer.Strategy.Median)) and table.keep_only_columns( column_names, ).remove_columns_with_non_numerical_values().number_of_columns < len( column_names, ): raise NonNumericColumnError( str( sorted( set(table.keep_only_columns(column_names).column_names) - set( table.keep_only_columns(column_names) .remove_columns_with_non_numerical_values() .column_names, ), ), ), ) if isinstance(self._strategy, Imputer.Strategy.Mode): multiple_most_frequent = {} for name in column_names: if len(table.get_column(name).mode()) > 1: multiple_most_frequent[name] = table.get_column(name).mode() if len(multiple_most_frequent) > 0: warnings.warn( ( "There are multiple most frequent values in a column given to the Imputer.\nThe lowest values" " are being chosen in this cases. The following columns have multiple most frequent" f" values:\n{multiple_most_frequent}" ), UserWarning, stacklevel=2, ) wrapped_transformer = sk_SimpleImputer() self._strategy._augment_imputer(wrapped_transformer) wrapped_transformer.fit(table._data[column_names]) result = Imputer(self._strategy) result._wrapped_transformer = wrapped_transformer result._column_names = column_names return result # noinspection PyProtectedMember def transform(self, table: Table) -> Table: """ Apply the learned transformation to a table. The table is not modified. Parameters ---------- table : Table The table to which the learned transformation is applied. Returns ------- transformed_table : Table The transformed table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. UnknownColumnNameError If the input table does not contain all columns used to fit the transformer. ValueError If the table contains 0 rows. """ # Transformer has not been fitted yet if self._wrapped_transformer is None or self._column_names is None: raise TransformerNotFittedError # Input table does not contain all columns used to fit the transformer missing_columns = sorted(set(self._column_names) - set(table.column_names)) if len(missing_columns) > 0: raise UnknownColumnNameError(missing_columns) if table.number_of_rows == 0: raise ValueError("The Imputer cannot transform the table because it contains 0 rows") data = table._data.copy() data[self._column_names] = pd.DataFrame( self._wrapped_transformer.transform(data[self._column_names]), columns=self._column_names, ) return Table._from_pandas_dataframe(data, table.schema) def is_fitted(self) -> bool: """ Check if the transformer is fitted. Returns ------- is_fitted : bool Whether the transformer is fitted. """ return self._wrapped_transformer is not None def get_names_of_added_columns(self) -> list[str]: """ Get the names of all new columns that have been added by the Imputer. Returns ------- added_columns : list[str] A list of names of the added columns, ordered as they will appear in the table. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ if not self.is_fitted(): raise TransformerNotFittedError return [] # (Must implement abstract method, cannot instantiate class otherwise.) def get_names_of_changed_columns(self) -> list[str]: """ Get the names of all columns that may have been changed by the Imputer. Returns ------- changed_columns : list[str] The list of (potentially) changed column names, as passed to fit. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ if self._column_names is None: raise TransformerNotFittedError return self._column_names def get_names_of_removed_columns(self) -> list[str]: """ Get the names of all columns that have been removed by the Imputer. Returns ------- removed_columns : list[str] A list of names of the removed columns, ordered as they appear in the table the Imputer was fitted on. Raises ------ TransformerNotFittedError If the transformer has not been fitted yet. """ if not self.is_fitted(): raise TransformerNotFittedError return []
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/data/tabular/transformation/_imputer.py
0.964279
0.433742
_imputer.py
pypi
from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING from safeds.data.tabular.typing import Anything, Integer, Nothing, RealNumber from safeds.data.tabular.typing._column_type import ColumnType from safeds.exceptions import UnknownColumnNameError if TYPE_CHECKING: import pandas as pd @dataclass class Schema: """ Store column names and corresponding data types for a `Table` or `Row`. Parameters ---------- schema : dict[str, ColumnType] Map from column names to data types. Examples -------- >>> from safeds.data.tabular.typing import Integer, Schema, String >>> schema = Schema({"A": Integer(), "B": String()}) """ _schema: dict[str, ColumnType] # ------------------------------------------------------------------------------------------------------------------ # Creation # ------------------------------------------------------------------------------------------------------------------ @staticmethod def _from_pandas_dataframe(dataframe: pd.DataFrame) -> Schema: """ Create a schema from a `pandas.DataFrame`. Parameters ---------- dataframe : pd.DataFrame The dataframe. Returns ------- schema : Schema The schema. """ names = dataframe.columns # noinspection PyProtectedMember types = [] for col in dataframe: types.append(ColumnType._data_type(dataframe[col])) return Schema(dict(zip(names, types, strict=True))) # ------------------------------------------------------------------------------------------------------------------ # Dunder methods # ------------------------------------------------------------------------------------------------------------------ def __init__(self, schema: dict[str, ColumnType]): self._schema = dict(schema) # Defensive copy def __hash__(self) -> int: """ Return a hash value for the schema. Returns ------- hash : int The hash value. Examples -------- >>> from safeds.data.tabular.typing import Integer, Schema, String >>> schema = Schema({"A": Integer(), "B": String()}) >>> hash_value = hash(schema) """ column_names = self._schema.keys() column_types = map(repr, self._schema.values()) return hash(tuple(zip(column_names, column_types, strict=True))) def __repr__(self) -> str: """ Return an unambiguous string representation of this row. Returns ------- representation : str The string representation. Examples -------- >>> from safeds.data.tabular.typing import Integer, Schema, String >>> schema = Schema({"A": Integer()}) >>> repr(schema) "Schema({'A': Integer})" """ return f"Schema({self!s})" def __str__(self) -> str: """ Return a user-friendly string representation of the schema. Returns ------- string : str The string representation. Examples -------- >>> from safeds.data.tabular.typing import Integer, Schema, String >>> schema = Schema({"A": Integer()}) >>> str(schema) "{'A': Integer}" """ match len(self._schema): case 0: return "{}" case 1: return str(self._schema) case _: lines = (f" {name!r}: {type_}" for name, type_ in self._schema.items()) joined = ",\n".join(lines) return f"{{\n{joined}\n}}" @property def column_names(self) -> list[str]: """ Return a list of all column names saved in this schema. Returns ------- column_names : list[str] The column names. Examples -------- >>> from safeds.data.tabular.typing import Integer, Schema, String >>> schema = Schema({"A": Integer(), "B": String()}) >>> schema.column_names ['A', 'B'] """ return list(self._schema.keys()) def has_column(self, column_name: str) -> bool: """ Return whether the schema contains a given column. Parameters ---------- column_name : str The name of the column. Returns ------- contains : bool True if the schema contains the column. Examples -------- >>> from safeds.data.tabular.typing import Integer, Schema, String >>> schema = Schema({"A": Integer(), "B": String()}) >>> schema.has_column("A") True >>> schema.has_column("C") False """ return column_name in self._schema def get_column_type(self, column_name: str) -> ColumnType: """ Return the type of the given column. Parameters ---------- column_name : str The name of the column. Returns ------- type : ColumnType The type of the column. Raises ------ UnknownColumnNameError If the specified column name does not exist. Examples -------- >>> from safeds.data.tabular.typing import Integer, Schema, String >>> schema = Schema({"A": Integer(), "B": String()}) >>> schema.get_column_type("A") Integer """ if not self.has_column(column_name): raise UnknownColumnNameError([column_name]) return self._schema[column_name] # ------------------------------------------------------------------------------------------------------------------ # Conversion # ------------------------------------------------------------------------------------------------------------------ def to_dict(self) -> dict[str, ColumnType]: """ Return a dictionary that maps column names to column types. Returns ------- data : dict[str, ColumnType] Dictionary representation of the schema. Examples -------- >>> from safeds.data.tabular.typing import Integer, Schema, String >>> schema = Schema({"A": Integer(), "B": String()}) >>> schema.to_dict() {'A': Integer, 'B': String} """ return dict(self._schema) # defensive copy @staticmethod def merge_multiple_schemas(schemas: list[Schema]) -> Schema: """ Merge multiple schemas into one. For each type missmatch the new schema will have the least common supertype. The type hierarchy is as follows: * Anything * RealNumber * Integer * Boolean * String Parameters ---------- schemas : list[Schema] the list of schemas you want to merge Returns ------- schema : Schema the new merged schema Raises ------ UnknownColumnNameError if not all schemas have the same column names """ schema_dict = schemas[0]._schema missing_col_names = set() for schema in schemas: missing_col_names.update(set(schema.column_names) - set(schema_dict.keys())) if len(missing_col_names) > 0: raise UnknownColumnNameError(list(missing_col_names)) for schema in schemas: if schema_dict != schema._schema: for col_name in schema_dict: nullable = False if schema_dict[col_name].is_nullable() or schema.get_column_type(col_name).is_nullable(): nullable = True if isinstance(schema_dict[col_name], type(schema.get_column_type(col_name))): if schema.get_column_type(col_name).is_nullable() and not schema_dict[col_name].is_nullable(): schema_dict[col_name] = type(schema.get_column_type(col_name))(nullable) continue if ( isinstance(schema_dict[col_name], RealNumber) and isinstance(schema.get_column_type(col_name), Integer) ) or ( isinstance(schema_dict[col_name], Integer) and isinstance(schema.get_column_type(col_name), RealNumber) ): schema_dict[col_name] = RealNumber(nullable) continue if isinstance(schema_dict[col_name], Nothing): schema_dict[col_name] = type(schema.get_column_type(col_name))(nullable) continue if isinstance(schema.get_column_type(col_name), Nothing): schema_dict[col_name] = type(schema_dict[col_name])(nullable) continue schema_dict[col_name] = Anything(nullable) return Schema(schema_dict) # ------------------------------------------------------------------------------------------------------------------ # IPython Integration # ------------------------------------------------------------------------------------------------------------------ def _repr_markdown_(self) -> str: """ Return a Markdown representation of the schema. Returns ------- markdown : str The Markdown representation. """ if len(self._schema) == 0: return "Empty Schema" lines = (f"| {name} | {type_} |" for name, type_ in self._schema.items()) joined = "\n".join(lines) return f"| Column Name | Column Type |\n| --- | --- |\n{joined}"
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/data/tabular/typing/_schema.py
0.946126
0.483466
_schema.py
pypi
from __future__ import annotations from abc import ABC, abstractmethod from dataclasses import dataclass from types import NoneType from typing import TYPE_CHECKING, Any import numpy as np if TYPE_CHECKING: import pandas as pd class ColumnType(ABC): """Abstract base class for column types.""" _is_nullable: bool # This line is just here so the linter doesn't throw an error @abstractmethod def __init__(self, is_nullable: bool = False) -> None: """ Abstract initializer for ColumnType. Parameters ---------- is_nullable Whether the columntype is nullable. """ @staticmethod def _data_type(data: pd.Series) -> ColumnType: """ Return the column type for a given `Series` from `pandas`. Parameters ---------- data : pd.Series The data to be checked. Returns ------- column_type : ColumnType The ColumnType. Raises ------ NotImplementedError If the given data type is not supported. """ def column_type_of_type(cell_type: Any) -> ColumnType: if cell_type == int or cell_type == np.int64 or cell_type == np.int32: return Integer(is_nullable) if cell_type == float or cell_type == np.float64 or cell_type == np.float32: return RealNumber(is_nullable) if cell_type == bool: return Boolean(is_nullable) if cell_type == str: return String(is_nullable) if cell_type is NoneType: return Nothing() else: message = f"Unsupported numpy data type '{cell_type}'." raise NotImplementedError(message) result: ColumnType = Nothing() is_nullable = False for cell in data: if result == Nothing(): result = column_type_of_type(type(cell)) if type(cell) is NoneType: is_nullable = True result._is_nullable = is_nullable if result != column_type_of_type(type(cell)): if type(cell) is NoneType: is_nullable = True result._is_nullable = is_nullable elif (isinstance(result, Integer) and isinstance(column_type_of_type(type(cell)), RealNumber)) or ( isinstance(result, RealNumber) and isinstance(column_type_of_type(type(cell)), Integer) ): result = RealNumber(is_nullable) else: result = Anything(is_nullable) if isinstance(cell, float) and np.isnan(cell): is_nullable = True result._is_nullable = is_nullable if isinstance(result, RealNumber) and all( data.apply(lambda c: bool(isinstance(c, float) and np.isnan(c) or c == float(int(c)))), ): result = Integer(is_nullable) return result @abstractmethod def is_nullable(self) -> bool: """ Return whether the given column type is nullable. Returns ------- is_nullable : bool True if the column is nullable. """ @abstractmethod def is_numeric(self) -> bool: """ Return whether the given column type is numeric. Returns ------- is_numeric : bool True if the column is numeric. """ @dataclass class Anything(ColumnType): """ Type for a column that contains anything. Parameters ---------- is_nullable : bool Whether the type also allows null values. """ _is_nullable: bool def __init__(self, is_nullable: bool = False) -> None: self._is_nullable = is_nullable def __repr__(self) -> str: result = "Anything" if self._is_nullable: result += "?" return result def is_nullable(self) -> bool: """ Return whether the given column type is nullable. Returns ------- is_nullable : bool True if the column is nullable. """ return self._is_nullable def is_numeric(self) -> bool: """ Return whether the given column type is numeric. Returns ------- is_numeric : bool True if the column is numeric. """ return False @dataclass class Boolean(ColumnType): """ Type for a column that only contains booleans. Parameters ---------- is_nullable : bool Whether the type also allows null values. """ _is_nullable: bool def __init__(self, is_nullable: bool = False) -> None: self._is_nullable = is_nullable def __repr__(self) -> str: result = "Boolean" if self._is_nullable: result += "?" return result def is_nullable(self) -> bool: """ Return whether the given column type is nullable. Returns ------- is_nullable : bool True if the column is nullable. """ return self._is_nullable def is_numeric(self) -> bool: """ Return whether the given column type is numeric. Returns ------- is_numeric : bool True if the column is numeric. """ return False @dataclass class RealNumber(ColumnType): """ Type for a column that only contains real numbers. Parameters ---------- is_nullable : bool Whether the type also allows null values. """ _is_nullable: bool def __init__(self, is_nullable: bool = False) -> None: self._is_nullable = is_nullable def __repr__(self) -> str: result = "RealNumber" if self._is_nullable: result += "?" return result def is_nullable(self) -> bool: """ Return whether the given column type is nullable. Returns ------- is_nullable : bool True if the column is nullable. """ return self._is_nullable def is_numeric(self) -> bool: """ Return whether the given column type is numeric. Returns ------- is_numeric : bool True if the column is numeric. """ return True @dataclass class Integer(ColumnType): """ Type for a column that only contains integers. Parameters ---------- is_nullable : bool Whether the type also allows null values. """ _is_nullable: bool def __init__(self, is_nullable: bool = False) -> None: self._is_nullable = is_nullable def __repr__(self) -> str: result = "Integer" if self._is_nullable: result += "?" return result def is_nullable(self) -> bool: """ Return whether the given column type is nullable. Returns ------- is_nullable : bool True if the column is nullable. """ return self._is_nullable def is_numeric(self) -> bool: """ Return whether the given column type is numeric. Returns ------- is_numeric : bool True if the column is numeric. """ return True @dataclass class String(ColumnType): """ Type for a column that only contains strings. Parameters ---------- is_nullable : bool Whether the type also allows null values. """ _is_nullable: bool def __init__(self, is_nullable: bool = False) -> None: self._is_nullable = is_nullable def __repr__(self) -> str: result = "String" if self._is_nullable: result += "?" return result def is_nullable(self) -> bool: """ Return whether the given column type is nullable. Returns ------- is_nullable : bool True if the column is nullable. """ return self._is_nullable def is_numeric(self) -> bool: """ Return whether the given column type is numeric. Returns ------- is_numeric : bool True if the column is numeric. """ return False @dataclass class Nothing(ColumnType): """Type for a column that contains None Values only.""" _is_nullable: bool def __init__(self) -> None: self._is_nullable = True def __repr__(self) -> str: result = "Nothing" if self._is_nullable: result += "?" return result def is_nullable(self) -> bool: """ Return whether the given column type is nullable. Returns ------- is_nullable : bool True if the column is nullable. """ return True def is_numeric(self) -> bool: """ Return whether the given column type is numeric. Returns ------- is_numeric : bool True if the column is numeric. """ return False
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/data/tabular/typing/_column_type.py
0.961561
0.45175
_column_type.py
pypi
import warnings from typing import Any from safeds.data.tabular.containers import Table, TaggedTable from safeds.exceptions import ( DatasetContainsTargetError, DatasetMissesDataError, DatasetMissesFeaturesError, LearningError, MissingValuesColumnError, ModelNotFittedError, NonNumericColumnError, PredictionError, UntaggedTableError, ) # noinspection PyProtectedMember def fit(model: Any, tagged_table: TaggedTable) -> None: """ Fit a model for a given tagged table. Parameters ---------- model Classifier or Regression from scikit-learn. tagged_table : TaggedTable The tagged table containing the feature and target vectors. Raises ------ LearningError If the tagged table contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ if not isinstance(tagged_table, TaggedTable) and isinstance(tagged_table, Table): raise UntaggedTableError if tagged_table.number_of_rows == 0: raise DatasetMissesDataError non_numerical_column_names = set(tagged_table.features.column_names) - set( tagged_table.features.remove_columns_with_non_numerical_values().column_names, ) if len(non_numerical_column_names) != 0: raise NonNumericColumnError( str(non_numerical_column_names), ( "You can use the LabelEncoder or OneHotEncoder to transform your non-numerical data to numerical" " data.\nThe OneHotEncoder should be used if you work with nominal data. If your data contains too many" " different values\nor is ordinal, you should use the LabelEncoder." ), ) null_containing_column_names = set(tagged_table.features.column_names) - set( tagged_table.features.remove_columns_with_missing_values().column_names, ) if len(null_containing_column_names) != 0: raise MissingValuesColumnError( str(null_containing_column_names), ( "You can use the Imputer to replace the missing values based on different strategies.\nIf you want to" " remove the missing values entirely you can use the method `Table.remove_rows_with_missing_values`." ), ) try: model.fit( tagged_table.features._data, tagged_table.target._data, ) except ValueError as exception: raise LearningError(str(exception)) from exception # noinspection PyProtectedMember def predict(model: Any, dataset: Table, feature_names: list[str] | None, target_name: str | None) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- model Classifier or regressor from scikit-learn. dataset : Table The dataset containing the features. target_name : str | None The name of the target column. feature_names : list[str] | None The names of the feature columns. Returns ------- table : TaggedTable A dataset containing the given features and the predicted target. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ # Validation if model is None or target_name is None or feature_names is None: raise ModelNotFittedError if dataset.has_column(target_name): raise DatasetContainsTargetError(target_name) missing_feature_names = [feature_name for feature_name in feature_names if not dataset.has_column(feature_name)] if missing_feature_names: raise DatasetMissesFeaturesError(missing_feature_names) if isinstance(dataset, TaggedTable): dataset = dataset.features # Cast to Table type, so Python will call the right methods... if dataset.number_of_rows == 0: raise DatasetMissesDataError non_numerical_column_names = set(dataset.keep_only_columns(feature_names).column_names) - set( dataset.keep_only_columns(feature_names).remove_columns_with_non_numerical_values().column_names, ) if len(non_numerical_column_names) != 0: raise NonNumericColumnError( str(non_numerical_column_names), ( "You can use the LabelEncoder or OneHotEncoder to transform your non-numerical data to numerical" " data.\nThe OneHotEncoder should be used if you work with nominal data. If your data contains too many" " different values\nor is ordinal, you should use the LabelEncoder.\n" ), ) null_containing_column_names = set(dataset.keep_only_columns(feature_names).column_names) - set( dataset.keep_only_columns(feature_names).remove_columns_with_missing_values().column_names, ) if len(null_containing_column_names) != 0: raise MissingValuesColumnError( str(null_containing_column_names), ( "You can use the Imputer to replace the missing values based on different strategies.\nIf you want to" " remove the missing values entirely you can use the method `Table.remove_rows_with_missing_values`." ), ) dataset_df = dataset.keep_only_columns(feature_names)._data dataset_df.columns = feature_names result_set = dataset._data.copy(deep=True) result_set.columns = dataset.column_names try: with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="X does not have valid feature names") predicted_target_vector = model.predict(dataset_df.values) result_set[target_name] = predicted_target_vector return Table._from_pandas_dataframe(result_set).tag_columns( target_name=target_name, feature_names=feature_names, ) except ValueError as exception: raise PredictionError(str(exception)) from exception
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/_util_sklearn.py
0.898
0.679418
_util_sklearn.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING from sklearn.ensemble import GradientBoostingRegressor as sk_GradientBoostingRegressor from safeds.exceptions import ClosedBound, OpenBound, OutOfBoundsError from safeds.ml.classical._util_sklearn import fit, predict from ._regressor import Regressor if TYPE_CHECKING: from sklearn.base import RegressorMixin from safeds.data.tabular.containers import Table, TaggedTable class GradientBoosting(Regressor): """ Gradient boosting regression. Parameters ---------- number_of_trees: int The number of boosting stages to perform. Gradient boosting is fairly robust to over-fitting so a large number usually results in better performance. learning_rate : float The larger the value, the more the model is influenced by each additional tree. If the learning rate is too low, the model might underfit. If the learning rate is too high, the model might overfit. Raises ------ OutOfBoundsError If `number_of_trees` or `learning_rate` are less than or equal to 0. """ def __init__(self, *, number_of_trees: int = 100, learning_rate: float = 0.1) -> None: # Validation if number_of_trees < 1: raise OutOfBoundsError(number_of_trees, name="number_of_trees", lower_bound=ClosedBound(1)) if learning_rate <= 0: raise OutOfBoundsError(learning_rate, name="learning_rate", lower_bound=OpenBound(0)) # Hyperparameters self._number_of_trees = number_of_trees self._learning_rate = learning_rate # Internal state self._wrapped_regressor: sk_GradientBoostingRegressor | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None @property def number_of_trees(self) -> int: """ Get the number of trees (estimators) in the ensemble. Returns ------- result: int The number of trees. """ return self._number_of_trees @property def learning_rate(self) -> float: """ Get the learning rate. Returns ------- result: float The learning rate. """ return self._learning_rate def fit(self, training_set: TaggedTable) -> GradientBoosting: """ Create a copy of this regressor and fit it with the given training data. This regressor is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_regressor : GradientBoosting The fitted regressor. Raises ------ LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ wrapped_regressor = self._get_sklearn_regressor() fit(wrapped_regressor, training_set) result = GradientBoosting(number_of_trees=self._number_of_trees, learning_rate=self._learning_rate) result._wrapped_regressor = wrapped_regressor result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_regressor, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the regressor is fitted. Returns ------- is_fitted : bool Whether the regressor is fitted. """ return self._wrapped_regressor is not None def _get_sklearn_regressor(self) -> RegressorMixin: """ Return a new wrapped Regressor from sklearn. Returns ------- wrapped_regressor: RegressorMixin The sklearn Regressor. """ return sk_GradientBoostingRegressor(n_estimators=self._number_of_trees, learning_rate=self._learning_rate)
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/regression/_gradient_boosting.py
0.965299
0.675147
_gradient_boosting.py
pypi
from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING from sklearn.svm import SVR as sk_SVR # noqa: N811 from safeds.exceptions import ClosedBound, OpenBound, OutOfBoundsError from safeds.ml.classical._util_sklearn import fit, predict from safeds.ml.classical.regression import Regressor if TYPE_CHECKING: from sklearn.base import RegressorMixin from safeds.data.tabular.containers import Table, TaggedTable class SupportVectorMachineKernel(ABC): """The abstract base class of the different subclasses supported by the `Kernel`.""" @abstractmethod def get_sklearn_kernel(self) -> object: """ Get the kernel of the given SupportVectorMachine. Returns ------- object The kernel of the SupportVectorMachine. """ class SupportVectorMachine(Regressor): """ Support vector machine. Parameters ---------- c: float The strength of regularization. Must be strictly positive. kernel: SupportVectorMachineKernel | None The type of kernel to be used. Defaults to None. Raises ------ OutOfBoundsError If `c` is less than or equal to 0. """ def __init__(self, *, c: float = 1.0, kernel: SupportVectorMachineKernel | None = None) -> None: # Internal state self._wrapped_regressor: sk_SVR | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None # Hyperparameters if c <= 0: raise OutOfBoundsError(c, name="c", lower_bound=OpenBound(0)) self._c = c self._kernel = kernel @property def c(self) -> float: """ Get the regularization strength. Returns ------- result: float The regularization strength. """ return self._c @property def kernel(self) -> SupportVectorMachineKernel | None: """ Get the type of kernel used. Returns ------- result: SupportVectorMachineKernel | None The type of kernel used. """ return self._kernel class Kernel: class Linear(SupportVectorMachineKernel): def get_sklearn_kernel(self) -> str: """ Get the name of the linear kernel. Returns ------- result: str The name of the linear kernel. """ return "linear" class Polynomial(SupportVectorMachineKernel): def __init__(self, degree: int): if degree < 1: raise OutOfBoundsError(degree, name="degree", lower_bound=ClosedBound(1)) self._degree = degree def get_sklearn_kernel(self) -> str: """ Get the name of the polynomial kernel. Returns ------- result: str The name of the polynomial kernel. """ return "poly" class Sigmoid(SupportVectorMachineKernel): def get_sklearn_kernel(self) -> str: """ Get the name of the sigmoid kernel. Returns ------- result: str The name of the sigmoid kernel. """ return "sigmoid" class RadialBasisFunction(SupportVectorMachineKernel): def get_sklearn_kernel(self) -> str: """ Get the name of the radial basis function (RBF) kernel. Returns ------- result: str The name of the RBF kernel. """ return "rbf" def _get_kernel_name(self) -> str: """ Get the name of the kernel. Returns ------- result: str The name of the kernel. Raises ------ TypeError If the kernel type is invalid. """ if isinstance(self.kernel, SupportVectorMachine.Kernel.Linear): return "linear" elif isinstance(self.kernel, SupportVectorMachine.Kernel.Polynomial): return "poly" elif isinstance(self.kernel, SupportVectorMachine.Kernel.Sigmoid): return "sigmoid" elif isinstance(self.kernel, SupportVectorMachine.Kernel.RadialBasisFunction): return "rbf" else: raise TypeError("Invalid kernel type.") def fit(self, training_set: TaggedTable) -> SupportVectorMachine: """ Create a copy of this regressor and fit it with the given training data. This regressor is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_regressor : SupportVectorMachine The fitted regressor. Raises ------ LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ wrapped_regressor = self._get_sklearn_regressor() fit(wrapped_regressor, training_set) result = SupportVectorMachine(c=self._c, kernel=self._kernel) result._wrapped_regressor = wrapped_regressor result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_regressor, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the regressor is fitted. Returns ------- is_fitted : bool Whether the regressor is fitted. """ return self._wrapped_regressor is not None def _get_sklearn_regressor(self) -> RegressorMixin: """ Return a new wrapped Regressor from sklearn. Returns ------- wrapped_regressor: RegressorMixin The sklearn Regressor. """ return sk_SVR(C=self._c)
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/regression/_support_vector_machine.py
0.965365
0.59564
_support_vector_machine.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING from sklearn.ensemble import AdaBoostRegressor as sk_AdaBoostRegressor from safeds.exceptions import ClosedBound, OpenBound, OutOfBoundsError from safeds.ml.classical._util_sklearn import fit, predict from ._regressor import Regressor if TYPE_CHECKING: from sklearn.base import RegressorMixin from safeds.data.tabular.containers import Table, TaggedTable class AdaBoost(Regressor): """ Ada Boost regression. Parameters ---------- learner: Regressor | None The learner from which the boosted ensemble is built. maximum_number_of_learners: int The maximum number of learners at which boosting is terminated. In case of perfect fit, the learning procedure is stopped early. Has to be greater than 0. learning_rate : float Weight applied to each regressor at each boosting iteration. A higher learning rate increases the contribution of each regressor. Has to be greater than 0. Raises ------ OutOfBoundsError If `maximum_number_of_learners` or `learning_rate` are less than or equal to 0. """ def __init__( self, *, learner: Regressor | None = None, maximum_number_of_learners: int = 50, learning_rate: float = 1.0, ) -> None: # Validation if maximum_number_of_learners < 1: raise OutOfBoundsError( maximum_number_of_learners, name="maximum_number_of_learners", lower_bound=ClosedBound(1), ) if learning_rate <= 0: raise OutOfBoundsError(learning_rate, name="learning_rate", lower_bound=OpenBound(0)) # Hyperparameters self._learner = learner self._maximum_number_of_learners = maximum_number_of_learners self._learning_rate = learning_rate # Internal state self._wrapped_regressor: sk_AdaBoostRegressor | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None @property def learner(self) -> Regressor | None: """ Get the base learner used for training the ensemble. Returns ------- result: Regressor | None The base learner. """ return self._learner @property def maximum_number_of_learners(self) -> int: """ Get the maximum number of learners in the ensemble. Returns ------- result: int The maximum number of learners. """ return self._maximum_number_of_learners @property def learning_rate(self) -> float: """ Get the learning rate. Returns ------- result: float The learning rate. """ return self._learning_rate def fit(self, training_set: TaggedTable) -> AdaBoost: """ Create a copy of this regressor and fit it with the given training data. This regressor is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_regressor : AdaBoost The fitted regressor. Raises ------ LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ wrapped_regressor = self._get_sklearn_regressor() fit(wrapped_regressor, training_set) result = AdaBoost( learner=self._learner, maximum_number_of_learners=self._maximum_number_of_learners, learning_rate=self._learning_rate, ) result._wrapped_regressor = wrapped_regressor result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_regressor, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the regressor is fitted. Returns ------- is_fitted : bool Whether the regressor is fitted. """ return self._wrapped_regressor is not None def _get_sklearn_regressor(self) -> RegressorMixin: """ Return a new wrapped Regressor from sklearn. Returns ------- wrapped_regressor: RegressorMixin The sklearn Regressor. """ learner = self._learner._get_sklearn_regressor() if self._learner is not None else None return sk_AdaBoostRegressor( estimator=learner, n_estimators=self._maximum_number_of_learners, learning_rate=self._learning_rate, )
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/regression/_ada_boost.py
0.975331
0.59355
_ada_boost.py
pypi
from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING from sklearn.metrics import mean_absolute_error as sk_mean_absolute_error from sklearn.metrics import mean_squared_error as sk_mean_squared_error from safeds.data.tabular.containers import Column, Table, TaggedTable from safeds.exceptions import ColumnLengthMismatchError, UntaggedTableError if TYPE_CHECKING: from sklearn.base import RegressorMixin class Regressor(ABC): """Abstract base class for all regressors.""" @abstractmethod def fit(self, training_set: TaggedTable) -> Regressor: """ Create a copy of this regressor and fit it with the given training data. This regressor is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_regressor : Regressor The fitted regressor. Raises ------ LearningError If the training data contains invalid values or if the training failed. """ @abstractmethod def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. """ @abstractmethod def is_fitted(self) -> bool: """ Check if the classifier is fitted. Returns ------- is_fitted : bool Whether the regressor is fitted. """ @abstractmethod def _get_sklearn_regressor(self) -> RegressorMixin: """ Return a new wrapped Regressor from sklearn. Returns ------- wrapped_regressor: RegressorMixin The sklearn Regressor. """ # noinspection PyProtectedMember def mean_squared_error(self, validation_or_test_set: TaggedTable) -> float: """ Compute the mean squared error (MSE) on the given data. Parameters ---------- validation_or_test_set : TaggedTable The validation or test set. Returns ------- mean_squared_error : float The calculated mean squared error (the average of the distance of each individual row squared). Raises ------ UntaggedTableError If the table is untagged. """ if not isinstance(validation_or_test_set, TaggedTable) and isinstance(validation_or_test_set, Table): raise UntaggedTableError expected = validation_or_test_set.target predicted = self.predict(validation_or_test_set.features).target _check_metrics_preconditions(predicted, expected) return sk_mean_squared_error(expected._data, predicted._data) # noinspection PyProtectedMember def mean_absolute_error(self, validation_or_test_set: TaggedTable) -> float: """ Compute the mean absolute error (MAE) of the regressor on the given data. Parameters ---------- validation_or_test_set : TaggedTable The validation or test set. Returns ------- mean_absolute_error : float The calculated mean absolute error (the average of the distance of each individual row). Raises ------ UntaggedTableError If the table is untagged. """ if not isinstance(validation_or_test_set, TaggedTable) and isinstance(validation_or_test_set, Table): raise UntaggedTableError expected = validation_or_test_set.target predicted = self.predict(validation_or_test_set.features).target _check_metrics_preconditions(predicted, expected) return sk_mean_absolute_error(expected._data, predicted._data) # noinspection PyProtectedMember def _check_metrics_preconditions(actual: Column, expected: Column) -> None: if not actual.type.is_numeric(): raise TypeError(f"Column 'actual' is not numerical but {actual.type}.") if not expected.type.is_numeric(): raise TypeError(f"Column 'expected' is not numerical but {expected.type}.") if actual._data.size != expected._data.size: raise ColumnLengthMismatchError( "\n".join([f"{column.name}: {column._data.size}" for column in [actual, expected]]), )
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/regression/_regressor.py
0.971966
0.640566
_regressor.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING from warnings import warn from sklearn.linear_model import Lasso as sk_Lasso from safeds.exceptions import ClosedBound, OutOfBoundsError from safeds.ml.classical._util_sklearn import fit, predict from ._regressor import Regressor if TYPE_CHECKING: from sklearn.base import RegressorMixin from safeds.data.tabular.containers import Table, TaggedTable class LassoRegression(Regressor): """Lasso regression. Parameters ---------- alpha : float Controls the regularization of the model. The higher the value, the more regularized it becomes. Raises ------ OutOfBoundsError If `alpha` is negative. """ def __init__(self, *, alpha: float = 1.0) -> None: # Validation if alpha < 0: raise OutOfBoundsError(alpha, name="alpha", lower_bound=ClosedBound(0)) if alpha == 0: warn( ( "Setting alpha to zero makes this model equivalent to LinearRegression. You should use " "LinearRegression instead for better numerical stability." ), UserWarning, stacklevel=2, ) # Hyperparameters self._alpha = alpha # Internal state self._wrapped_regressor: sk_Lasso | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None @property def alpha(self) -> float: """ Get the regularization of the model. Returns ------- result: float The regularization of the model. """ return self._alpha def fit(self, training_set: TaggedTable) -> LassoRegression: """ Create a copy of this regressor and fit it with the given training data. This regressor is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_regressor : LassoRegression The fitted regressor. Raises ------ LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ wrapped_regressor = self._get_sklearn_regressor() fit(wrapped_regressor, training_set) result = LassoRegression(alpha=self._alpha) result._wrapped_regressor = wrapped_regressor result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_regressor, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the regressor is fitted. Returns ------- is_fitted : bool Whether the regressor is fitted. """ return self._wrapped_regressor is not None def _get_sklearn_regressor(self) -> RegressorMixin: """ Return a new wrapped Regressor from sklearn. Returns ------- wrapped_regressor: RegressorMixin The sklearn Regressor. """ return sk_Lasso(alpha=self._alpha)
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/regression/_lasso_regression.py
0.967854
0.631353
_lasso_regression.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING from sklearn.linear_model import LinearRegression as sk_LinearRegression from safeds.ml.classical._util_sklearn import fit, predict from ._regressor import Regressor if TYPE_CHECKING: from sklearn.base import RegressorMixin from safeds.data.tabular.containers import Table, TaggedTable class LinearRegression(Regressor): """Linear regression.""" def __init__(self) -> None: # Internal state self._wrapped_regressor: sk_LinearRegression | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None def fit(self, training_set: TaggedTable) -> LinearRegression: """ Create a copy of this regressor and fit it with the given training data. This regressor is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_regressor : LinearRegression The fitted regressor. Raises ------ LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ wrapped_regressor = self._get_sklearn_regressor() fit(wrapped_regressor, training_set) result = LinearRegression() result._wrapped_regressor = wrapped_regressor result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_regressor, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the regressor is fitted. Returns ------- is_fitted : bool Whether the regressor is fitted. """ return self._wrapped_regressor is not None def _get_sklearn_regressor(self) -> RegressorMixin: """ Return a new wrapped Regressor from sklearn. Returns ------- wrapped_regressor: RegressorMixin The sklearn Regressor. """ return sk_LinearRegression(n_jobs=-1)
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/regression/_linear_regression.py
0.970183
0.638215
_linear_regression.py
pypi
from __future__ import annotations import warnings from typing import TYPE_CHECKING from warnings import warn from sklearn.linear_model import ElasticNet as sk_ElasticNet from safeds.exceptions import ClosedBound, OutOfBoundsError from safeds.ml.classical._util_sklearn import fit, predict from ._regressor import Regressor if TYPE_CHECKING: from sklearn.base import RegressorMixin from safeds.data.tabular.containers import Table, TaggedTable class ElasticNetRegression(Regressor): """Elastic net regression. Parameters ---------- alpha : float Controls the regularization of the model. The higher the value, the more regularized it becomes. lasso_ratio: float Number between 0 and 1 that controls the ratio between Lasso and Ridge regularization. If 0, only Ridge regularization is used. If 1, only Lasso regularization is used. Raises ------ OutOfBoundsError If `alpha` is negative or `lasso_ratio` is not between 0 and 1. """ def __init__(self, *, alpha: float = 1.0, lasso_ratio: float = 0.5) -> None: # Validation if alpha < 0: raise OutOfBoundsError(alpha, name="alpha", lower_bound=ClosedBound(0)) if alpha == 0: warn( ( "Setting alpha to zero makes this model equivalent to LinearRegression. You should use " "LinearRegression instead for better numerical stability." ), UserWarning, stacklevel=2, ) if lasso_ratio < 0 or lasso_ratio > 1: raise OutOfBoundsError( lasso_ratio, name="lasso_ratio", lower_bound=ClosedBound(0), upper_bound=ClosedBound(1), ) elif lasso_ratio == 0: warnings.warn( ( "ElasticNetRegression with lasso_ratio = 0 is essentially RidgeRegression." " Use RidgeRegression instead for better numerical stability." ), stacklevel=2, ) elif lasso_ratio == 1: warnings.warn( ( "ElasticNetRegression with lasso_ratio = 0 is essentially LassoRegression." " Use LassoRegression instead for better numerical stability." ), stacklevel=2, ) # Hyperparameters self._alpha = alpha self._lasso_ratio = lasso_ratio # Internal state self._wrapped_regressor: sk_ElasticNet | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None @property def alpha(self) -> float: """ Get the regularization of the model. Returns ------- result: float The regularization of the model. """ return self._alpha @property def lasso_ratio(self) -> float: """ Get the ratio between Lasso and Ridge regularization. Returns ------- result: float The ratio between Lasso and Ridge regularization. """ return self._lasso_ratio def fit(self, training_set: TaggedTable) -> ElasticNetRegression: """ Create a copy of this regressor and fit it with the given training data. This regressor is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_regressor : ElasticNetRegression The fitted regressor. Raises ------ LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ wrapped_regressor = self._get_sklearn_regressor() fit(wrapped_regressor, training_set) result = ElasticNetRegression(alpha=self._alpha, lasso_ratio=self._lasso_ratio) result._wrapped_regressor = wrapped_regressor result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_regressor, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the regressor is fitted. Returns ------- is_fitted : bool Whether the regressor is fitted. """ return self._wrapped_regressor is not None def _get_sklearn_regressor(self) -> RegressorMixin: """ Return a new wrapped Regressor from sklearn. Returns ------- wrapped_regressor: RegressorMixin The sklearn Regressor. """ return sk_ElasticNet(alpha=self._alpha, l1_ratio=self._lasso_ratio)
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/regression/_elastic_net_regression.py
0.966789
0.596815
_elastic_net_regression.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING from sklearn.neighbors import KNeighborsRegressor as sk_KNeighborsRegressor from safeds.exceptions import ClosedBound, DatasetMissesDataError, OutOfBoundsError from safeds.ml.classical._util_sklearn import fit, predict from ._regressor import Regressor if TYPE_CHECKING: from sklearn.base import RegressorMixin from safeds.data.tabular.containers import Table, TaggedTable class KNearestNeighbors(Regressor): """ K-nearest-neighbors regression. Parameters ---------- number_of_neighbors : int The number of neighbors to use for interpolation. Has to be greater than 0 (validated in the constructor) and less than or equal to the sample size (validated when calling `fit`). Raises ------ OutOfBoundsError If `number_of_neighbors` is less than 1. """ def __init__(self, number_of_neighbors: int) -> None: # Validation if number_of_neighbors < 1: raise OutOfBoundsError(number_of_neighbors, name="number_of_neighbors", lower_bound=ClosedBound(1)) # Hyperparameters self._number_of_neighbors = number_of_neighbors # Internal state self._wrapped_regressor: sk_KNeighborsRegressor | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None @property def number_of_neighbors(self) -> int: """ Get the number of neighbors used for interpolation. Returns ------- result: int The number of neighbors. """ return self._number_of_neighbors def fit(self, training_set: TaggedTable) -> KNearestNeighbors: """ Create a copy of this regressor and fit it with the given training data. This regressor is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_regressor : KNearestNeighbors The fitted regressor. Raises ------ ValueError If `number_of_neighbors` is greater than the sample size. LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ if training_set.number_of_rows == 0: raise DatasetMissesDataError if self._number_of_neighbors > training_set.number_of_rows: raise ValueError( ( f"The parameter 'number_of_neighbors' ({self._number_of_neighbors}) has to be less than or equal to" f" the sample size ({training_set.number_of_rows})." ), ) wrapped_regressor = self._get_sklearn_regressor() fit(wrapped_regressor, training_set) result = KNearestNeighbors(self._number_of_neighbors) result._wrapped_regressor = wrapped_regressor result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_regressor, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the regressor is fitted. Returns ------- is_fitted : bool Whether the regressor is fitted. """ return self._wrapped_regressor is not None def _get_sklearn_regressor(self) -> RegressorMixin: """ Return a new wrapped Regressor from sklearn. Returns ------- wrapped_regressor: RegressorMixin The sklearn Regressor. """ return sk_KNeighborsRegressor(self._number_of_neighbors, n_jobs=-1)
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/regression/_k_nearest_neighbors.py
0.96799
0.641605
_k_nearest_neighbors.py
pypi
from __future__ import annotations import warnings from typing import TYPE_CHECKING from sklearn.linear_model import Ridge as sk_Ridge from safeds.exceptions import ClosedBound, OutOfBoundsError from safeds.ml.classical._util_sklearn import fit, predict from ._regressor import Regressor if TYPE_CHECKING: from sklearn.base import RegressorMixin from safeds.data.tabular.containers import Table, TaggedTable class RidgeRegression(Regressor): """ Ridge regression. Parameters ---------- alpha : float Controls the regularization of the model. The higher the value, the more regularized it becomes. Raises ------ OutOfBoundsError If `alpha` is negative. """ def __init__(self, *, alpha: float = 1.0) -> None: # Validation if alpha < 0: raise OutOfBoundsError(alpha, name="alpha", lower_bound=ClosedBound(0)) if alpha == 0.0: warnings.warn( ( "Setting alpha to zero makes this model equivalent to LinearRegression. You should use " "LinearRegression instead for better numerical stability." ), UserWarning, stacklevel=2, ) # Hyperparameters self._alpha = alpha # Internal state self._wrapped_regressor: sk_Ridge | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None @property def alpha(self) -> float: """ Get the regularization of the model. Returns ------- result: float The regularization of the model. """ return self._alpha def fit(self, training_set: TaggedTable) -> RidgeRegression: """ Create a copy of this regressor and fit it with the given training data. This regressor is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_regressor : RidgeRegression The fitted regressor. Raises ------ LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ wrapped_regressor = self._get_sklearn_regressor() fit(wrapped_regressor, training_set) result = RidgeRegression(alpha=self._alpha) result._wrapped_regressor = wrapped_regressor result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_regressor, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the regressor is fitted. Returns ------- is_fitted : bool Whether the regressor is fitted. """ return self._wrapped_regressor is not None def _get_sklearn_regressor(self) -> RegressorMixin: """ Return a new wrapped Regressor from sklearn. Returns ------- wrapped_regressor: RegressorMixin The sklearn Regressor. """ return sk_Ridge(alpha=self._alpha)
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/regression/_ridge_regression.py
0.964905
0.613468
_ridge_regression.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING from sklearn.ensemble import RandomForestRegressor as sk_RandomForestRegressor from safeds.exceptions import ClosedBound, OutOfBoundsError from safeds.ml.classical._util_sklearn import fit, predict from ._regressor import Regressor if TYPE_CHECKING: from sklearn.base import RegressorMixin from safeds.data.tabular.containers import Table, TaggedTable class RandomForest(Regressor): """Random forest regression. Parameters ---------- number_of_trees : int The number of trees to be used in the random forest. Has to be greater than 0. Raises ------ OutOfBoundsError If `number_of_trees` is less than 1. """ def __init__(self, *, number_of_trees: int = 100) -> None: # Validation if number_of_trees < 1: raise OutOfBoundsError(number_of_trees, name="number_of_trees", lower_bound=ClosedBound(1)) # Hyperparameters self._number_of_trees = number_of_trees # Internal state self._wrapped_regressor: sk_RandomForestRegressor | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None @property def number_of_trees(self) -> int: """ Get the number of trees used in the random forest. Returns ------- result: int The number of trees. """ return self._number_of_trees def fit(self, training_set: TaggedTable) -> RandomForest: """ Create a copy of this regressor and fit it with the given training data. This regressor is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_regressor : RandomForest The fitted regressor. Raises ------ LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ wrapped_regressor = self._get_sklearn_regressor() fit(wrapped_regressor, training_set) result = RandomForest(number_of_trees=self._number_of_trees) result._wrapped_regressor = wrapped_regressor result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_regressor, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the regressor is fitted. Returns ------- is_fitted : bool Whether the regressor is fitted. """ return self._wrapped_regressor is not None def _get_sklearn_regressor(self) -> RegressorMixin: """ Return a new wrapped Regressor from sklearn. Returns ------- wrapped_regressor: RegressorMixin The sklearn Regressor. """ return sk_RandomForestRegressor(self._number_of_trees, n_jobs=-1)
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/regression/_random_forest.py
0.966108
0.548069
_random_forest.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING from sklearn.tree import DecisionTreeRegressor as sk_DecisionTreeRegressor from safeds.ml.classical._util_sklearn import fit, predict from ._regressor import Regressor if TYPE_CHECKING: from sklearn.base import RegressorMixin from safeds.data.tabular.containers import Table, TaggedTable class DecisionTree(Regressor): """Decision tree regression.""" def __init__(self) -> None: # Internal state self._wrapped_regressor: sk_DecisionTreeRegressor | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None def fit(self, training_set: TaggedTable) -> DecisionTree: """ Create a copy of this regressor and fit it with the given training data. This regressor is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_regressor : DecisionTree The fitted regressor. Raises ------ LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ wrapped_regressor = self._get_sklearn_regressor() fit(wrapped_regressor, training_set) result = DecisionTree() result._wrapped_regressor = wrapped_regressor result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_regressor, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the regressor is fitted. Returns ------- is_fitted : bool Whether the regressor is fitted. """ return self._wrapped_regressor is not None def _get_sklearn_regressor(self) -> RegressorMixin: """ Return a new wrapped Regressor from sklearn. Returns ------- wrapped_regressor: RegressorMixin The sklearn Regressor. """ return sk_DecisionTreeRegressor()
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/regression/_decision_tree.py
0.965714
0.66326
_decision_tree.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING from sklearn.ensemble import GradientBoostingClassifier as sk_GradientBoostingClassifier from safeds.exceptions import ClosedBound, OpenBound, OutOfBoundsError from safeds.ml.classical._util_sklearn import fit, predict from ._classifier import Classifier if TYPE_CHECKING: from sklearn.base import ClassifierMixin from safeds.data.tabular.containers import Table, TaggedTable class GradientBoosting(Classifier): """ Gradient boosting classification. Parameters ---------- number_of_trees: int The number of boosting stages to perform. Gradient boosting is fairly robust to over-fitting so a large number usually results in better performance. learning_rate : float The larger the value, the more the model is influenced by each additional tree. If the learning rate is too low, the model might underfit. If the learning rate is too high, the model might overfit. Raises ------ OutOfBoundsError If `number_of_trees` or `learning_rate` is less than or equal to 0. """ def __init__(self, *, number_of_trees: int = 100, learning_rate: float = 0.1) -> None: # Validation if number_of_trees < 1: raise OutOfBoundsError(number_of_trees, name="number_of_trees", lower_bound=ClosedBound(1)) if learning_rate <= 0: raise OutOfBoundsError(learning_rate, name="learning_rate", lower_bound=OpenBound(0)) # Hyperparameters self._number_of_trees = number_of_trees self._learning_rate = learning_rate # Internal state self._wrapped_classifier: sk_GradientBoostingClassifier | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None @property def number_of_trees(self) -> int: """ Get the number of trees (estimators) in the ensemble. Returns ------- result: int The number of trees. """ return self._number_of_trees @property def learning_rate(self) -> float: """ Get the learning rate. Returns ------- result: float The learning rate. """ return self._learning_rate def fit(self, training_set: TaggedTable) -> GradientBoosting: """ Create a copy of this classifier and fit it with the given training data. This classifier is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_classifier : GradientBoosting The fitted classifier. Raises ------ LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ wrapped_classifier = self._get_sklearn_classifier() fit(wrapped_classifier, training_set) result = GradientBoosting(number_of_trees=self._number_of_trees, learning_rate=self._learning_rate) result._wrapped_classifier = wrapped_classifier result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_classifier, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the classifier is fitted. Returns ------- is_fitted : bool Whether the classifier is fitted. """ return self._wrapped_classifier is not None def _get_sklearn_classifier(self) -> ClassifierMixin: """ Return a new wrapped Classifier from sklearn. Returns ------- wrapped_classifier: ClassifierMixin The sklearn Classifier. """ return sk_GradientBoostingClassifier(n_estimators=self._number_of_trees, learning_rate=self._learning_rate)
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/classification/_gradient_boosting.py
0.964263
0.620219
_gradient_boosting.py
pypi
from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING from sklearn.svm import SVC as sk_SVC # noqa: N811 from safeds.exceptions import ClosedBound, OpenBound, OutOfBoundsError from safeds.ml.classical._util_sklearn import fit, predict from safeds.ml.classical.classification import Classifier if TYPE_CHECKING: from sklearn.base import ClassifierMixin from safeds.data.tabular.containers import Table, TaggedTable class SupportVectorMachineKernel(ABC): """The abstract base class of the different subclasses supported by the `Kernel`.""" @abstractmethod def get_sklearn_kernel(self) -> object: """ Get the kernel of the given SupportVectorMachine. Returns ------- object The kernel of the SupportVectorMachine. """ class SupportVectorMachine(Classifier): """ Support vector machine. Parameters ---------- c: float The strength of regularization. Must be strictly positive. kernel: SupportVectorMachineKernel | None The type of kernel to be used. Defaults to None. Raises ------ OutOfBoundsError If `c` is less than or equal to 0. """ def __init__(self, *, c: float = 1.0, kernel: SupportVectorMachineKernel | None = None) -> None: # Internal state self._wrapped_classifier: sk_SVC | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None # Hyperparameters if c <= 0: raise OutOfBoundsError(c, name="c", lower_bound=OpenBound(0)) self._c = c self._kernel = kernel @property def c(self) -> float: """ Get the regularization strength. Returns ------- result: float The regularization strength. """ return self._c @property def kernel(self) -> SupportVectorMachineKernel | None: """ Get the type of kernel used. Returns ------- result: SupportVectorMachineKernel | None The type of kernel used. """ return self._kernel class Kernel: class Linear(SupportVectorMachineKernel): def get_sklearn_kernel(self) -> str: """ Get the name of the linear kernel. Returns ------- result: str The name of the linear kernel. """ return "linear" class Polynomial(SupportVectorMachineKernel): def __init__(self, degree: int): if degree < 1: raise OutOfBoundsError(degree, name="degree", lower_bound=ClosedBound(1)) self._degree = degree def get_sklearn_kernel(self) -> str: """ Get the name of the polynomial kernel. Returns ------- result: str The name of the polynomial kernel. """ return "poly" class Sigmoid(SupportVectorMachineKernel): def get_sklearn_kernel(self) -> str: """ Get the name of the sigmoid kernel. Returns ------- result: str The name of the sigmoid kernel. """ return "sigmoid" class RadialBasisFunction(SupportVectorMachineKernel): def get_sklearn_kernel(self) -> str: """ Get the name of the radial basis function (RBF) kernel. Returns ------- result: str The name of the RBF kernel. """ return "rbf" def _get_kernel_name(self) -> str: """ Get the name of the kernel. Returns ------- result: str The name of the kernel. Raises ------ TypeError If the kernel type is invalid. """ if isinstance(self.kernel, SupportVectorMachine.Kernel.Linear): return "linear" elif isinstance(self.kernel, SupportVectorMachine.Kernel.Polynomial): return "poly" elif isinstance(self.kernel, SupportVectorMachine.Kernel.Sigmoid): return "sigmoid" elif isinstance(self.kernel, SupportVectorMachine.Kernel.RadialBasisFunction): return "rbf" else: raise TypeError("Invalid kernel type.") def fit(self, training_set: TaggedTable) -> SupportVectorMachine: """ Create a copy of this classifier and fit it with the given training data. This classifier is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_classifier : SupportVectorMachine The fitted classifier. Raises ------ LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ wrapped_classifier = self._get_sklearn_classifier() fit(wrapped_classifier, training_set) result = SupportVectorMachine(c=self._c, kernel=self._kernel) result._wrapped_classifier = wrapped_classifier result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_classifier, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the classifier is fitted. Returns ------- is_fitted : bool Whether the classifier is fitted. """ return self._wrapped_classifier is not None def _get_sklearn_classifier(self) -> ClassifierMixin: """ Return a new wrapped Classifier from sklearn. Returns ------- wrapped_classifier: ClassifierMixin The sklearn Classifier. """ return sk_SVC(C=self._c)
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/classification/_support_vector_machine.py
0.96372
0.567757
_support_vector_machine.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING from sklearn.linear_model import LogisticRegression as sk_LogisticRegression from safeds.ml.classical._util_sklearn import fit, predict from ._classifier import Classifier if TYPE_CHECKING: from sklearn.base import ClassifierMixin from safeds.data.tabular.containers import Table, TaggedTable class LogisticRegression(Classifier): """Regularized logistic regression.""" def __init__(self) -> None: # Internal state self._wrapped_classifier: sk_LogisticRegression | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None def fit(self, training_set: TaggedTable) -> LogisticRegression: """ Create a copy of this classifier and fit it with the given training data. This classifier is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_classifier : LogisticRegression The fitted classifier. Raises ------ LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ wrapped_classifier = self._get_sklearn_classifier() fit(wrapped_classifier, training_set) result = LogisticRegression() result._wrapped_classifier = wrapped_classifier result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_classifier, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the classifier is fitted. Returns ------- is_fitted : bool Whether the classifier is fitted. """ return self._wrapped_classifier is not None def _get_sklearn_classifier(self) -> ClassifierMixin: """ Return a new wrapped Classifier from sklearn. Returns ------- wrapped_classifier: ClassifierMixin The sklearn Classifier. """ return sk_LogisticRegression(n_jobs=-1)
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/classification/_logistic_regression.py
0.966418
0.55441
_logistic_regression.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING from sklearn.ensemble import AdaBoostClassifier as sk_AdaBoostClassifier from safeds.exceptions import ClosedBound, OpenBound, OutOfBoundsError from safeds.ml.classical._util_sklearn import fit, predict from ._classifier import Classifier if TYPE_CHECKING: from sklearn.base import ClassifierMixin from safeds.data.tabular.containers import Table, TaggedTable class AdaBoost(Classifier): """ Ada Boost classification. Parameters ---------- learner: Classifier | None The learner from which the boosted ensemble is built. maximum_number_of_learners: int The maximum number of learners at which boosting is terminated. In case of perfect fit, the learning procedure is stopped early. Has to be greater than 0. learning_rate : float Weight applied to each classifier at each boosting iteration. A higher learning rate increases the contribution of each classifier. Has to be greater than 0. Raises ------ OutOfBoundsError If `maximum_number_of_learners` or `learning_rate` are less than or equal to 0. """ def __init__( self, *, learner: Classifier | None = None, maximum_number_of_learners: int = 50, learning_rate: float = 1.0, ) -> None: # Validation if maximum_number_of_learners < 1: raise OutOfBoundsError( maximum_number_of_learners, name="maximum_number_of_learners", lower_bound=ClosedBound(1), ) if learning_rate <= 0: raise OutOfBoundsError(learning_rate, name="learning_rate", lower_bound=OpenBound(0)) # Hyperparameters self._learner = learner self._maximum_number_of_learners = maximum_number_of_learners self._learning_rate = learning_rate # Internal state self._wrapped_classifier: sk_AdaBoostClassifier | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None @property def learner(self) -> Classifier | None: """ Get the base learner used for training the ensemble. Returns ------- result: Classifier | None The base learner. """ return self._learner @property def maximum_number_of_learners(self) -> int: """ Get the maximum number of learners in the ensemble. Returns ------- result: int The maximum number of learners. """ return self._maximum_number_of_learners @property def learning_rate(self) -> float: """ Get the learning rate. Returns ------- result: float The learning rate. """ return self._learning_rate def fit(self, training_set: TaggedTable) -> AdaBoost: """ Create a copy of this classifier and fit it with the given training data. This classifier is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_classifier : AdaBoost The fitted classifier. Raises ------ LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ wrapped_classifier = self._get_sklearn_classifier() fit(wrapped_classifier, training_set) result = AdaBoost( learner=self.learner, maximum_number_of_learners=self.maximum_number_of_learners, learning_rate=self._learning_rate, ) result._wrapped_classifier = wrapped_classifier result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_classifier, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the classifier is fitted. Returns ------- is_fitted : bool Whether the classifier is fitted. """ return self._wrapped_classifier is not None def _get_sklearn_classifier(self) -> ClassifierMixin: """ Return a new wrapped Classifier from sklearn. Returns ------- wrapped_classifier: ClassifierMixin The sklearn Classifier. """ learner = self.learner._get_sklearn_classifier() if self.learner is not None else None return sk_AdaBoostClassifier( estimator=learner, n_estimators=self.maximum_number_of_learners, learning_rate=self._learning_rate, )
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/classification/_ada_boost.py
0.97296
0.535098
_ada_boost.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING from sklearn.neighbors import KNeighborsClassifier as sk_KNeighborsClassifier from safeds.exceptions import ClosedBound, DatasetMissesDataError, OutOfBoundsError from safeds.ml.classical._util_sklearn import fit, predict from ._classifier import Classifier if TYPE_CHECKING: from sklearn.base import ClassifierMixin from safeds.data.tabular.containers import Table, TaggedTable class KNearestNeighbors(Classifier): """ K-nearest-neighbors classification. Parameters ---------- number_of_neighbors : int The number of neighbors to use for interpolation. Has to be greater than 0 (validated in the constructor) and less than or equal to the sample size (validated when calling `fit`). Raises ------ OutOfBoundsError If `number_of_neighbors` is less than 1. """ def __init__(self, number_of_neighbors: int) -> None: # Validation if number_of_neighbors < 1: raise OutOfBoundsError(number_of_neighbors, name="number_of_neighbors", lower_bound=ClosedBound(1)) # Hyperparameters self._number_of_neighbors = number_of_neighbors # Internal state self._wrapped_classifier: sk_KNeighborsClassifier | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None @property def number_of_neighbors(self) -> int: """ Get the number of neighbors used for interpolation. Returns ------- result: int The number of neighbors. """ return self._number_of_neighbors def fit(self, training_set: TaggedTable) -> KNearestNeighbors: """ Create a copy of this classifier and fit it with the given training data. This classifier is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_classifier : KNearestNeighbors The fitted classifier. Raises ------ ValueError If `number_of_neighbors` is greater than the sample size. LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ if training_set.number_of_rows == 0: raise DatasetMissesDataError if self._number_of_neighbors > training_set.number_of_rows: raise ValueError( ( f"The parameter 'number_of_neighbors' ({self._number_of_neighbors}) has to be less than or equal to" f" the sample size ({training_set.number_of_rows})." ), ) wrapped_classifier = self._get_sklearn_classifier() fit(wrapped_classifier, training_set) result = KNearestNeighbors(self._number_of_neighbors) result._wrapped_classifier = wrapped_classifier result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_classifier, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the classifier is fitted. Returns ------- is_fitted : bool Whether the classifier is fitted. """ return self._wrapped_classifier is not None def _get_sklearn_classifier(self) -> ClassifierMixin: """ Return a new wrapped Classifier from sklearn. Returns ------- wrapped_classifier: ClassifierMixin The sklearn Classifier. """ return sk_KNeighborsClassifier(self._number_of_neighbors, n_jobs=-1)
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/classification/_k_nearest_neighbors.py
0.965835
0.583441
_k_nearest_neighbors.py
pypi
from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING from sklearn.metrics import accuracy_score as sk_accuracy_score from safeds.data.tabular.containers import Table, TaggedTable from safeds.exceptions import UntaggedTableError if TYPE_CHECKING: from typing import Any from sklearn.base import ClassifierMixin class Classifier(ABC): """Abstract base class for all classifiers.""" @abstractmethod def fit(self, training_set: TaggedTable) -> Classifier: """ Create a copy of this classifier and fit it with the given training data. This classifier is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_classifier : Classifier The fitted classifier. Raises ------ LearningError If the training data contains invalid values or if the training failed. """ @abstractmethod def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. """ @abstractmethod def is_fitted(self) -> bool: """ Check if the classifier is fitted. Returns ------- is_fitted : bool Whether the classifier is fitted. """ @abstractmethod def _get_sklearn_classifier(self) -> ClassifierMixin: """ Return a new wrapped Classifier from sklearn. Returns ------- wrapped_classifier: ClassifierMixin The sklearn Classifier. """ # noinspection PyProtectedMember def accuracy(self, validation_or_test_set: TaggedTable) -> float: """ Compute the accuracy of the classifier on the given data. Parameters ---------- validation_or_test_set : TaggedTable The validation or test set. Returns ------- accuracy : float The calculated accuracy score, i.e. the percentage of equal data. Raises ------ UntaggedTableError If the table is untagged. """ if not isinstance(validation_or_test_set, TaggedTable) and isinstance(validation_or_test_set, Table): raise UntaggedTableError expected_values = validation_or_test_set.target predicted_values = self.predict(validation_or_test_set.features).target return sk_accuracy_score(expected_values._data, predicted_values._data) def precision(self, validation_or_test_set: TaggedTable, positive_class: Any) -> float: """ Compute the classifier's precision on the given data. Parameters ---------- validation_or_test_set : TaggedTable The validation or test set. positive_class : Any The class to be considered positive. All other classes are considered negative. Returns ------- precision : float The calculated precision score, i.e. the ratio of correctly predicted positives to all predicted positives. Return 1 if no positive predictions are made. """ if not isinstance(validation_or_test_set, TaggedTable) and isinstance(validation_or_test_set, Table): raise UntaggedTableError expected_values = validation_or_test_set.target predicted_values = self.predict(validation_or_test_set.features).target n_true_positives = 0 n_false_positives = 0 for expected_value, predicted_value in zip(expected_values, predicted_values, strict=True): if predicted_value == positive_class: if expected_value == positive_class: n_true_positives += 1 else: n_false_positives += 1 if (n_true_positives + n_false_positives) == 0: return 1.0 return n_true_positives / (n_true_positives + n_false_positives) def recall(self, validation_or_test_set: TaggedTable, positive_class: Any) -> float: """ Compute the classifier's recall on the given data. Parameters ---------- validation_or_test_set : TaggedTable The validation or test set. positive_class : Any The class to be considered positive. All other classes are considered negative. Returns ------- recall : float The calculated recall score, i.e. the ratio of correctly predicted positives to all expected positives. Return 1 if there are no positive expectations. """ if not isinstance(validation_or_test_set, TaggedTable) and isinstance(validation_or_test_set, Table): raise UntaggedTableError expected_values = validation_or_test_set.target predicted_values = self.predict(validation_or_test_set.features).target n_true_positives = 0 n_false_negatives = 0 for expected_value, predicted_value in zip(expected_values, predicted_values, strict=True): if predicted_value == positive_class: if expected_value == positive_class: n_true_positives += 1 elif expected_value == positive_class: n_false_negatives += 1 if (n_true_positives + n_false_negatives) == 0: return 1.0 return n_true_positives / (n_true_positives + n_false_negatives) def f1_score(self, validation_or_test_set: TaggedTable, positive_class: Any) -> float: """ Compute the classifier's $F_1$-score on the given data. Parameters ---------- validation_or_test_set : TaggedTable The validation or test set. positive_class : Any The class to be considered positive. All other classes are considered negative. Returns ------- f1_score : float The calculated $F_1$-score, i.e. the harmonic mean between precision and recall. Return 1 if there are no positive expectations and predictions. """ if not isinstance(validation_or_test_set, TaggedTable) and isinstance(validation_or_test_set, Table): raise UntaggedTableError expected_values = validation_or_test_set.target predicted_values = self.predict(validation_or_test_set.features).target n_true_positives = 0 n_false_negatives = 0 n_false_positives = 0 for expected_value, predicted_value in zip(expected_values, predicted_values, strict=True): if predicted_value == positive_class: if expected_value == positive_class: n_true_positives += 1 else: n_false_positives += 1 elif expected_value == positive_class: n_false_negatives += 1 if (2 * n_true_positives + n_false_positives + n_false_negatives) == 0: return 1.0 return 2 * n_true_positives / (2 * n_true_positives + n_false_positives + n_false_negatives)
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/classification/_classifier.py
0.959837
0.593933
_classifier.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING from sklearn.ensemble import RandomForestClassifier as sk_RandomForestClassifier from safeds.exceptions import ClosedBound, OutOfBoundsError from safeds.ml.classical._util_sklearn import fit, predict from ._classifier import Classifier if TYPE_CHECKING: from sklearn.base import ClassifierMixin from safeds.data.tabular.containers import Table, TaggedTable class RandomForest(Classifier): """Random forest classification. Parameters ---------- number_of_trees : int The number of trees to be used in the random forest. Has to be greater than 0. Raises ------ OutOfBoundsError If `number_of_trees` is less than 1. """ def __init__(self, *, number_of_trees: int = 100) -> None: # Validation if number_of_trees < 1: raise OutOfBoundsError(number_of_trees, name="number_of_trees", lower_bound=ClosedBound(1)) # Hyperparameters self._number_of_trees = number_of_trees # Internal state self._wrapped_classifier: sk_RandomForestClassifier | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None @property def number_of_trees(self) -> int: """ Get the number of trees used in the random forest. Returns ------- result: int The number of trees. """ return self._number_of_trees def fit(self, training_set: TaggedTable) -> RandomForest: """ Create a copy of this classifier and fit it with the given training data. This classifier is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_classifier : RandomForest The fitted classifier. Raises ------ LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ wrapped_classifier = self._get_sklearn_classifier() fit(wrapped_classifier, training_set) result = RandomForest(number_of_trees=self._number_of_trees) result._wrapped_classifier = wrapped_classifier result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_classifier, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the classifier is fitted. Returns ------- is_fitted : bool Whether the classifier is fitted. """ return self._wrapped_classifier is not None def _get_sklearn_classifier(self) -> ClassifierMixin: """ Return a new wrapped Classifier from sklearn. Returns ------- wrapped_classifier: ClassifierMixin The sklearn Classifier. """ return sk_RandomForestClassifier(self._number_of_trees, n_jobs=-1)
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/classification/_random_forest.py
0.964681
0.491334
_random_forest.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING from sklearn.tree import DecisionTreeClassifier as sk_DecisionTreeClassifier from safeds.ml.classical._util_sklearn import fit, predict from ._classifier import Classifier if TYPE_CHECKING: from sklearn.base import ClassifierMixin from safeds.data.tabular.containers import Table, TaggedTable class DecisionTree(Classifier): """Decision tree classification.""" def __init__(self) -> None: # Internal state self._wrapped_classifier: sk_DecisionTreeClassifier | None = None self._feature_names: list[str] | None = None self._target_name: str | None = None def fit(self, training_set: TaggedTable) -> DecisionTree: """ Create a copy of this classifier and fit it with the given training data. This classifier is not modified. Parameters ---------- training_set : TaggedTable The training data containing the feature and target vectors. Returns ------- fitted_classifier : DecisionTree The fitted classifier. Raises ------ LearningError If the training data contains invalid values or if the training failed. UntaggedTableError If the table is untagged. NonNumericColumnError If the training data contains non-numerical values. MissingValuesColumnError If the training data contains missing values. DatasetMissesDataError If the training data contains no rows. """ wrapped_classifier = self._get_sklearn_classifier() fit(wrapped_classifier, training_set) result = DecisionTree() result._wrapped_classifier = wrapped_classifier result._feature_names = training_set.features.column_names result._target_name = training_set.target.name return result def predict(self, dataset: Table) -> TaggedTable: """ Predict a target vector using a dataset containing feature vectors. The model has to be trained first. Parameters ---------- dataset : Table The dataset containing the feature vectors. Returns ------- table : TaggedTable A dataset containing the given feature vectors and the predicted target vector. Raises ------ ModelNotFittedError If the model has not been fitted yet. DatasetContainsTargetError If the dataset contains the target column already. DatasetMissesFeaturesError If the dataset misses feature columns. PredictionError If predicting with the given dataset failed. NonNumericColumnError If the dataset contains non-numerical values. MissingValuesColumnError If the dataset contains missing values. DatasetMissesDataError If the dataset contains no rows. """ return predict(self._wrapped_classifier, dataset, self._feature_names, self._target_name) def is_fitted(self) -> bool: """ Check if the classifier is fitted. Returns ------- is_fitted : bool Whether the classifier is fitted. """ return self._wrapped_classifier is not None def _get_sklearn_classifier(self) -> ClassifierMixin: return sk_DecisionTreeClassifier()
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/ml/classical/classification/_decision_tree.py
0.964681
0.591812
_decision_tree.py
pypi
from __future__ import annotations from abc import ABC, abstractmethod from numpy import isinf, isnan class OutOfBoundsError(ValueError): """ A generic exception that can be used to signal that a (float) value is outside its expected range. Parameters ---------- actual: float The actual value that is outside its expected range. name: str | None The name of the offending variable. lower_bound: Bound | None The lower bound of the expected range. Use None if there is no lower Bound. upper_bound: Bound | None The upper bound of the expected range. Use None if there is no upper Bound. """ def __init__( self, actual: float, *, name: str | None = None, lower_bound: Bound | None = None, upper_bound: Bound | None = None, ): """ Initialize an OutOfBoundsError. Parameters ---------- actual: float The actual value that is outside its expected range. name: str | None The name of the offending variable. lower_bound: Bound | None The lower bound of the expected range. Use None if there is no lower Bound. upper_bound: Bound | None The upper bound of the expected range. Use None if there is no upper Bound. Raises ------ ValueError * If one of the given Bounds is +/-inf. (For infinite Bounds, pass None instead.) * If one of the given Bounds is nan. * If upper_bound < lower_bound. * If actual does not lie outside the given interval. * If actual is not a real number. """ # Validate bound parameters: if lower_bound is None and upper_bound is None: raise ValueError("Illegal interval: Attempting to raise OutOfBoundsError, but no bounds given.") if (lower_bound is not None and isinf(lower_bound.value)) or ( upper_bound is not None and isinf(upper_bound.value) ): raise ValueError("Illegal interval: Lower and upper bounds must be real numbers, or None if unbounded.") # Validate actual parameter: if isinf(actual) or isnan(actual): raise ValueError("Attempting to raise OutOfBoundsError with actual value not being a real number.") # Use local variables with stricter types to help static analysis: _lower_bound: Bound = lower_bound if lower_bound is not None else OpenBound(float("-inf")) _upper_bound: Bound = upper_bound if upper_bound is not None else OpenBound(float("inf")) # Check bounds: if _upper_bound.value < _lower_bound.value: raise ValueError( ( f"Illegal interval: Attempting to raise OutOfBoundsError, but given upper bound {_upper_bound} is " f"actually less than given lower bound {_lower_bound}." ), ) # Check that actual is indeed outside the interval: elif _lower_bound._check_lower_bound(actual) and _upper_bound._check_upper_bound(actual): raise ValueError( ( f"Illegal interval: Attempting to raise OutOfBoundsError, but value {actual} is not actually" f" outside given interval {_lower_bound._str_lower_bound()}, {_upper_bound._str_upper_bound()}." ), ) # Raise the actual exception: full_variable_name = actual if name is None else f"{name} (={actual})" super().__init__( f"{full_variable_name} is not inside {_lower_bound._str_lower_bound()}, {_upper_bound._str_upper_bound()}.", ) class Bound(ABC): """ Abstract base class for (lower or upper) Bounds on a float value. Parameters ---------- value: float The value of the Bound. """ def __init__(self, value: float): """ Initialize a Bound. Parameters ---------- value: float The value of the Bound. Raises ------ ValueError If value is nan or if value is +/-inf and the Bound type does not allow for infinite Bounds. """ if isnan(value): raise ValueError("Bound must be a real number, not nan.") self._value = value def __str__(self) -> str: """Get a string representation of the concrete value of the Bound.""" return str(self.value) @property def value(self) -> float: """Get the concrete value of the Bound.""" return self._value @abstractmethod def _str_lower_bound(self) -> str: """Get a string representation of the Bound as the lower Bound of an interval.""" @abstractmethod def _str_upper_bound(self) -> str: """Get a string representation of the Bound as the upper Bound of an interval.""" @abstractmethod def _check_lower_bound(self, actual: float) -> bool: """ Check that a value does not exceed the Bound on the lower side. Parameters ---------- actual: float The actual value that should be checked for not exceeding the Bound. """ @abstractmethod def _check_upper_bound(self, actual: float) -> bool: """ Check that a value does not exceed the Bound on the upper side. Parameters ---------- actual: float The actual value that should be checked for not exceeding the Bound. """ class ClosedBound(Bound): """ A closed Bound, i.e. the value on the border belongs to the range. Parameters ---------- value: float The value of the Bound. """ def __init__(self, value: float): """ Initialize a ClosedBound. Parameters ---------- value: float The value of the ClosedBound. Raises ------ ValueError If value is nan or if value is +/-inf. """ if value == float("-inf") or value == float("inf"): raise ValueError("ClosedBound must be a real number, not +/-inf.") super().__init__(value) def _str_lower_bound(self) -> str: """Get a string representation of the ClosedBound as the lower Bound of an interval.""" return f"[{self}" def _str_upper_bound(self) -> str: """Get a string representation of the ClosedBound as the upper Bound of an interval.""" return f"{self}]" def _check_lower_bound(self, actual: float) -> bool: """ Check that a value is not strictly lower than the ClosedBound. Parameters ---------- actual: float The actual value that should be checked for not exceeding the Bound. """ return actual >= self.value def _check_upper_bound(self, actual: float) -> bool: """ Check that a value is not strictly higher than the ClosedBound. Parameters ---------- actual: float The actual value that should be checked for not exceeding the Bound. """ return actual <= self.value class OpenBound(Bound): """ An open Bound, i.e. the value on the border does not belong to the range. Parameters ---------- value: float The value of the OpenBound. """ def __init__(self, value: float): """ Initialize an OpenBound. Parameters ---------- value: float The value of the OpenBound. Raises ------ ValueError If value is nan. """ super().__init__(value) def __str__(self) -> str: """Get a string representation of the concrete value of the OpenBound.""" if self.value == float("-inf"): return "-\u221e" elif self.value == float("inf"): return "\u221e" else: return super().__str__() def _str_lower_bound(self) -> str: """Get a string representation of the OpenBound as the lower Bound of an interval.""" return f"({self}" def _str_upper_bound(self) -> str: """Get a string representation of the OpenBound as the upper Bound of an interval.""" return f"{self})" def _check_lower_bound(self, actual: float) -> bool: """ Check that a value is not lower or equal to the OpenBound. Parameters ---------- actual: float The actual value that should be checked for not exceeding the Bound. """ return actual > self.value def _check_upper_bound(self, actual: float) -> bool: """ Check that a value is not higher or equal to the OpenBound. Parameters ---------- actual: float The actual value that should be checked for not exceeding the Bound. """ return actual < self.value
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/exceptions/_generic.py
0.970296
0.656025
_generic.py
pypi
class DatasetContainsTargetError(ValueError): """ Raised when a dataset contains the target column already. Parameters ---------- target_name: str The name of the target column. """ def __init__(self, target_name: str): super().__init__(f"Dataset already contains the target column '{target_name}'.") class DatasetMissesFeaturesError(ValueError): """ Raised when a dataset misses feature columns. Parameters ---------- missing_feature_names: list[str] The names of the missing feature columns. """ def __init__(self, missing_feature_names: list[str]): super().__init__(f"Dataset misses the feature columns '{missing_feature_names}'.") class DatasetMissesDataError(ValueError): """Raised when a dataset contains no rows.""" def __init__(self) -> None: super().__init__("Dataset contains no rows") class LearningError(Exception): """ Raised when an error occurred while training a model. Parameters ---------- reason: str The reason for the error. """ def __init__(self, reason: str): super().__init__(f"Error occurred while learning: {reason}") class ModelNotFittedError(Exception): """Raised when a model is used before fitting it.""" def __init__(self) -> None: super().__init__("The model has not been fitted yet.") class PredictionError(Exception): """ Raised when an error occurred while prediction a target vector using a model. Parameters ---------- reason: str The reason for the error. """ def __init__(self, reason: str): super().__init__(f"Error occurred while predicting: {reason}") class UntaggedTableError(Exception): """Raised when an untagged table is used instead of a TaggedTable in a regression or classification.""" def __init__(self) -> None: super().__init__( ( "This method needs a tagged table.\nA tagged table is a table that additionally knows which columns are" " features and which are the target to predict.\nUse Table.tag_column() to create a tagged table." ), )
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/exceptions/_ml.py
0.93453
0.728447
_ml.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from pathlib import Path class UnknownColumnNameError(KeyError): """ Exception raised for trying to access an invalid column name. Parameters ---------- column_names : list[str] The name of the column that was tried to be accessed. """ def __init__(self, column_names: list[str], similar_columns: list[str] | None = None): class _UnknownColumnNameErrorMessage( str, ): # This class is necessary for the newline character in a KeyError exception. See https://stackoverflow.com/a/70114007 def __repr__(self) -> str: return str(self) error_message = f"Could not find column(s) '{', '.join(column_names)}'." if similar_columns is not None and len(similar_columns) > 0: error_message += f"\nDid you mean '{similar_columns}'?" super().__init__(_UnknownColumnNameErrorMessage(error_message)) class NonNumericColumnError(Exception): """Exception raised for trying to do numerical operations on a non-numerical column.""" def __init__(self, column_info: str, help_msg: str | None = None) -> None: line_break = "\n" super().__init__( ( "Tried to do a numerical operation on one or multiple non-numerical columns:" f" \n{column_info}{line_break + help_msg if help_msg is not None else ''}" ), ) class MissingValuesColumnError(Exception): """Exception raised for trying to do operations on columns containing missing values.""" def __init__(self, column_info: str, help_msg: str | None = None) -> None: line_break = "\n" super().__init__( ( "Tried to do an operation on one or multiple columns containing missing values:" f" \n{column_info}{line_break + help_msg if help_msg is not None else ''}" ), ) class DuplicateColumnNameError(Exception): """ Exception raised for trying to modify a table resulting in a duplicate column name. Parameters ---------- column_name : str The name of the column that resulted in a duplicate. """ def __init__(self, column_name: str): super().__init__(f"Column '{column_name}' already exists.") class IndexOutOfBoundsError(IndexError): """ Exception raised for trying to access an element by an index that does not exist in the underlying data. Parameters ---------- index : int | slice The wrongly used index. """ def __init__(self, index: int | slice): if isinstance(index, int): super().__init__(f"There is no element at index '{index}'.") else: super().__init__(f"There is no element in the range [{index.start}, {index.stop}]") class ColumnSizeError(Exception): """ Exception raised for trying to use a column of unsupported size. Parameters ---------- expected_size : str The expected size of the column as an expression (e.g. 2, >0, !=0). actual_size : str The actual size of the column as an expression (e.g. 2, >0, !=0). """ def __init__(self, expected_size: str, actual_size: str): super().__init__(f"Expected a column of size {expected_size} but got column of size {actual_size}.") class ColumnLengthMismatchError(Exception): """Exception raised when the lengths of two or more columns do not match.""" def __init__(self, column_info: str): super().__init__(f"The length of at least one column differs: \n{column_info}") class TransformerNotFittedError(Exception): """Raised when a transformer is used before fitting it.""" def __init__(self) -> None: super().__init__("The transformer has not been fitted yet.") class ValueNotPresentWhenFittedError(Exception): """Exception raised when attempting to one-hot-encode a table containing values not present in the fitting phase.""" def __init__(self, values: list[tuple[str, str]]) -> None: values_info = [f"{value} in column {column}" for value, column in values] line_break = "\n" super().__init__( ( "Value(s) not present in the table the transformer was fitted on:" f" {line_break}{line_break.join(values_info)}" ), ) class WrongFileExtensionError(Exception): """Exception raised when the file has the wrong file extension.""" def __init__(self, file: str | Path, file_extension: str | list[str]) -> None: super().__init__( ( f"The file {file} has a wrong file extension. Please provide a file with the following extension(s):" f" {file_extension}" ), ) class IllegalSchemaModificationError(Exception): """Exception raised when modifying a schema in a way that is inconsistent with the subclass's requirements.""" def __init__(self, msg: str) -> None: super().__init__(f"Illegal schema modification: {msg}") class ColumnIsTargetError(IllegalSchemaModificationError): """Exception raised in overriden methods of the Table class when removing tagged Columns from a TaggedTable.""" def __init__(self, column_name: str) -> None: super().__init__(f'Column "{column_name}" is the target column and cannot be removed.')
/safe_ds-0.15.0.tar.gz/safe_ds-0.15.0/src/safeds/exceptions/_data.py
0.964229
0.3694
_data.py
pypi
from enum import Enum, unique class EthereumNetworkNotSupported(Exception): pass @unique class EthereumNetwork(Enum): """ Use https://chainlist.org/ as a reference """ UNKNOWN = -1 OLYMPIC = 0 MAINNET = 1 ROPSTEN = 3 RINKEBY = 4 GOERLI = 5 ETC_KOTTI = 6 TCH = 7 UBQ = 8 OPTIMISTIC = 10 META = 11 META_TESTNET = 12 DIODE_TESTNET = 13 FLR_FLARE = 14 DIODE = 15 FLR_COSTON = 16 TCH_THAIFI = 17 TST_TESTNET = 18 SGB_SONGBIRD = 19 BOBA_RINKEBY = 28 RSK = 30 RSK_TESTNET = 31 GOOD_TESTNET = 32 GOOD = 33 TBWG = 35 VAL = 38 TLOS = 40 TLOS_TESTNET = 41 KOVAN = 42 PANGOLIN_FREE_TESTNET = 43 CRAB_CRAB_NETWORK = 44 XDC = 50 TXDC_TESTNET = 51 CSC = 52 CSC_TESTNET = 53 BINANCE = 56 SYS = 57 ONTOLOGY = 58 EOS = 59 GO = 60 ELLA = 64 OKEXCHAIN_TESTNET = 65 OKEXCHAIN = 66 DBM_TESTNET = 67 SOTER = 68 MIX = 76 POA_SOKOL = 77 PC = 78 GENECHAIN = 80 METER = 82 METER_TESTNET = 83 GTTEST_TESTNET = 85 GT = 86 TOMO = 88 EOS_TESTNET = 95 BSC_CHAPEL = 97 POA_CORE = 99 XDAI = 100 WEB3GAMES_TESTNET = 102 VELAS_MAINNET = 106 TT = 108 XPR_TESTNET = 110 ETL = 111 FUSE_MAINNET = 122 FUSE_SPARK = 123 DWU = 124 FETH_FACTORY127 = 127 HECO = 128 MATIC = 137 DAX = 142 PHT_SIRIUS = 162 PHT = 163 RESIL_TESTNET = 172 AOX_XDAI = 200 ENERGY_WEB_CHAIN = 246 FANTOM = 250 HECO_TESTNET = 256 HPB = 269 BOBA = 288 KCC_TESTNET = 322 THETA = 361 THETA_TESTNET_SAPPHIRE = 363 THETA_TESTNET_AMBER = 364 THETA_TESTNET = 365 CRO = 385 RUPX = 499 TAO_CORE = 558 METIS_TESTNET = 588 MACA_TESTNET = 595 METIS_GOERLI_TESTNET = 599 KAR = 686 FETH_FACTORY127_TESTNET = 721 CHEAPETH_CHEAPNET = 777 ACA = 787 HAIC = 803 WAN = 888 YETI = 977 WAN_TESTNET = 999 KLAY_BAOBAB = 1001 NEW_TESTNET = 1007 EURUS_MAINNET = 1008 EVC_EVRICE = 1010 NEW = 1012 SAKURA = 1022 CLOVER_TESTNET = 1023 CLOVER = 1024 METIS = 1088 MATH = 1139 MATH_TESTNET = 1140 MOON_MOONBEAM = 1284 MOON_MOONRIVER = 1285 MOON_MOONROCK = 1286 MOON_MOONBASE = 1287 MOON_MOONSHADOW = 1288 GANACHE = 1337 CATECHAIN = 1618 RABBIT = 1807 EURUS_TESTNET = 1984 EGEM = 1987 PUBLICMINT_TESTNET = 2019 PUBLICMINT_MAINNET = 2020 EDG = 2021 EDG_BERESHEET = 2022 KORTHO = 2559 FANTOM_TESTNET = 4002 IOTEX_IO = 4689 IOTEX_IO_TESTNET = 4690 VENIDIUM_TESTNET = 4918 VENIDIUM = 4919 ESN = 5197 SYS_TESTNET = 5700 ONTOLOGY_TESTNET = 5851 RBD = 5869 SHYFT = 7341 MDGL_TESTNET = 8029 GENECHAIN_ADENINE = 8080 KLAY_CYPRESS = 8217 KORTHO_TEST = 8285 OLO = 8723 OLO_TESTNET = 8724 BLOXBERG = 8995 SMARTBCH = 10000 SMARTBCHTEST_TESTNET = 10001 GEN = 10101 SHYFT_TESTNET = 11437 REI_TESTNET = 12357 MTT = 16000 MTTTEST_DEVNET = 16001 GO_TESTNET = 31337 FSN = 32659 NRG = 39797 ARBITRUM = 42161 ARBITRUM_NOVA = 42170 CELO = 42220 ATH_ATHEREUM = 43110 AVALANCHE = 43114 CELO_ALFAJORES = 44787 REI_MAINNET = 47805 NRG_TESTNET = 49797 CELO_BAKLAVA = 62320 GODWOKEN_TESTNET = 71401 GODWOKEN = 71402 VOLTA = 73799 AKA = 200625 ARTIS_SIGMA1 = 246529 ARTIS_TAU1 = 246785 SPARTA_TESTNET = 333888 OLYMPUS = 333999 ARBITRUM_TESTNET = 421611 ETHO = 1313114 XERO = 1313500 MUSIC = 7762959 MUMBAI = 80001 PEP_TESTNET = 13371337 ILT = 18289463 QKI = 20181205 AUX = 28945486 JOYS = 35855456 AQUA = 61717561 TOYS_TESTNET = 99415706 OLT = 311752642 IPOS = 1122334455 AURORA = 1313161554 AURORA_TESTNET = 1313161555 AURORA_BETANET = 1313161556 PIRL = 3125659152 OLT_TESTNET = 4216137055 PALM_TESTNET = 11297108099 PALM = 11297108109 GATHER_DEVNET = 486217935 GATHER_TESTNET = 356256156 GATHER_MAINNET = 192837465 EVMOS_TESTNET = 9000 EVMOS_MAINNET = 9001 ASTAR = 592 SHIDEN = 336 CRONOS_MAINNET = 25 CRONOS_TESTNET = 338 QUARKCHAIN_MAINNET_ROOT = 100000 QUARKCHAIN_MAINNET_SHARD_0 = 100001 QUARKCHAIN_MAINNET_SHARD_1 = 100002 QUARKCHAIN_MAINNET_SHARD_2 = 100003 QUARKCHAIN_MAINNET_SHARD_3 = 100004 QUARKCHAIN_MAINNET_SHARD_4 = 100005 QUARKCHAIN_MAINNET_SHARD_5 = 100006 QUARKCHAIN_MAINNET_SHARD_6 = 100007 QUARKCHAIN_MAINNET_SHARD_7 = 100008 QUARKCHAIN_DEVNET_ROOT = 110000 QUARKCHAIN_DEVNET_SHARD_0 = 110001 QUARKCHAIN_DEVNET_SHARD_1 = 110002 QUARKCHAIN_DEVNET_SHARD_2 = 110003 QUARKCHAIN_DEVNET_SHARD_3 = 110004 QUARKCHAIN_DEVNET_SHARD_4 = 110005 QUARKCHAIN_DEVNET_SHARD_5 = 110006 QUARKCHAIN_DEVNET_SHARD_6 = 110007 QUARKCHAIN_DEVNET_SHARD_7 = 110008 CONFLUX_ESPACE = 1030 BROCHAIN_MAINNET = 108801 WAGMI = 11111 SEPOLIA = 11155111 IORA_CHAIN = 1197 SINGULARITY_ZERO_MAINNET = 12052 POPCATEUM_MAINNET = 1213 ENTERCHAIN_MAINNET = 1214 OM_CHAIN_MAINNET = 1246 OYCHAIN_MAINNET = 126 HALO_MAINNET = 1280 PHOENIX_MAINNET = 13381 SHERPAX_MAINNET = 1506 BTACHAIN = 1657 HARMONY_MAINNET_SHARD_0 = 1666600000 HARMONY_MAINNET_SHARD_1 = 1666600001 HARMONY_MAINNET_SHARD_2 = 1666600002 HARMONY_MAINNET_SHARD_3 = 1666600003 SEELE_MAINNET = 186 BMC_MAINNET = 188 NTITY_MAINNET = 197710212030 BTCIX_NETWORK = 19845 BITTORRENT_CHAIN_MAINNET = 199 ELASTOS_SMART_CHAIN = 20 RANGERS_PROTOCOL_MAINNET = 2025 DATAHOPPER = 2021121117 ECOBALL_MAINNET = 2100 OMCHAIN_MAINNET = 21816 ELA_DID_SIDECHAIN_MAINNET = 22 EVANESCO_MAINNET = 2213 KAVA_EVM = 2222 DITHEREUM_MAINNET = 24 NEON_EVM_DEVNET = 245022926 NEON_EVM_MAINNET = 245022934 SETHEUM = 258 EZCHAIN_C_CHAIN_MAINNET = 2612 SHIBACHAIN = 27 SOCIAL_SMART_CHAIN_MAINNET = 281121 GENESIS_L1 = 29 BITGERT_MAINNET = 32520 WEB3Q_MAINNET = 333 PULSECHAIN_MAINNET = 369 BITTEX_MAINNET = 3690 SX_NETWORK_MAINNET = 416 PHI_NETWORK = 4181 PEGGLECOIN = 42069 EMERALD_PARATIME_MAINNET = 42262 AUTOBAHN_NETWORK = 45000 DOUBLE_A_CHAIN_MAINNET = 512 UZMI_NETWORK_MAINNET = 5315 DFK_CHAIN = 53935 ZYX_MAINNET = 55 VELA1_CHAIN_MAINNET = 555 NAHMII_MAINNET = 5551 REI_CHAIN_MAINNET = 55555 MOLEREUM_NETWORK = 6022140761023 ECREDITS_MAINNET = 63000 PIXIE_CHAIN_MAINNET = 6626 HOO_SMART_CHAIN = 70 THINKIUM_MAINNET_CHAIN_0 = 70000 THINKIUM_MAINNET_CHAIN_1 = 70001 THINKIUM_MAINNET_CHAIN_2 = 70002 THINKIUM_MAINNET_CHAIN_103 = 70103 BLOCKCHAIN_STATION_MAINNET = 707 IDCHAIN_MAINNET = 74 RISE_OF_THE_WARBOTS_TESTNET = 7777 ZENITH_MAINNET = 79 TELEPORT = 8000 NOVA_NETWORK = 87 AMBROS_CHAIN_MAINNET = 880 VISION_MAINNET = 888888 GENESIS_COIN = 9100 ELUVIO_CONTENT_FABRIC = 955305 GARIZON_STAGE0 = 90 GARIZON_STAGE1 = 91 GARIZON_STAGE2 = 92 GARIZON_STAGE3 = 93 NEXT_SMART_CHAIN = 96 LUCKY_NETWORK = 998 UB_SMART_CHAIN = 99999 ETHEREUM_CLASSIC_MAINNET = 61 ETHERINC = 101 FREIGHT_TRUST_NETWORK = 211 PERMISSION = 222 SUR_BLOCKCHAIN_NETWORK = 262 KCC_MAINNET = 321 CALLISTO_MAINNET = 820 WORLD_TRADE_TECHNICAL_BLOCKCHAIN = 1202 ATHEIOS = 1620 TESLAFUNDS = 1856 WEBCHAIN = 24484 MINTME_COM_COIN = 24734 ETHERSOCIAL_NETWORK = 31102 CRYSTALEUM = 103090 ALAYA_MAINNET = 201018 PLATON_MAINNET = 210425 BITTORRENT_CHAIN_TESTNET = 1028 KAIBA_LIGHTNING_CHAIN_TESTNET = 104 WEB3GAMES_DEVNET = 105 NEBULA_TESTNET = 107 CRYPTOCOINPAY = 10823 QUADRANS_BLOCKCHAIN = 10946 QUADRANS_BLOCKCHAIN_TESTNET = 10947 EVANESCO_TESTNET = 1201 SINGULARITY_ZERO_TESTNET = 12051 OYCHAIN_TESTNET = 125 BOBA_NETWORK_BOBABEAM = 1294 BOBA_NETWORK_BOBABASE = 1297 BOBA_AVAX_L2 = 43288 ETND_CHAIN_MAINNETS = 131419 AITD_MAINNET = 1319 AITD_TESTNET = 1320 KINTSUGI = 1337702 KILN = 1337802 OPENPIECE_TESTNET = 141 SHERPAX_TESTNET = 1507 HARMONY_TESTNET_SHARD_0 = 1666700000 HARMONY_TESTNET_SHARD_1 = 1666700001 HARMONY_TESTNET_SHARD_2 = 1666700002 HARMONY_TESTNET_SHARD_3 = 1666700003 AIOZ_NETWORK = 168 LUDAN_MAINNET = 1688 IVAR_CHAIN_TESTNET = 16888 HOO_SMART_CHAIN_TESTNET = 170 AME_CHAIN_MAINNET = 180 CUBE_CHAIN_MAINNET = 1818 CUBE_CHAIN_TESTNET = 1819 BMC_TESTNET = 189 BON_NETWORK = 1898 CRYPTO_EMERGENCY = 193 HARADEV_TESTNET = 197710212031 MILKOMEDA_C1_MAINNET = 2001 MILKOMEDA_C1_TESTNET = 200101 MILKOMEDA_A1_MAINNET = 2002 MILKOMEDA_A1_TESTNET = 200202 CLOUDWALK_MAINNET = 2009 CLOUDWALK_TESTNET = 2008 ALAYA_DEV_TESTNET = 201030 SMARTMESH_MAINNET = 20180430 TAYCAN_TESTNET = 2023 ELA_ETH_SIDECHAIN_TESTNET = 21 ELA_DID_SIDECHAIN_TESTNET = 23 ECOBALL_TESTNET_ESPUMA = 2101 CENNZNET_AZALEA = 21337 FINDORA_MAINNET = 2152 FINDORA_TESTNET = 2153 SOTERONE_MAINNET_OLD = 218 TAYCAN = 22023 PLATON_DEV_TESTNET = 2203181 PLATON_DEV_TESTNET2 = 2206132 KAVA_EVM_TESTNET = 2221 VCHAIN_MAINNET = 2223 LACHAIN_MAINNET = 225 LACHAIN_TESTNET = 226 HAYMO_TESTNET = 234666 NEON_EVM_TESTNET = 245022940 TECHPAY_MAINNET = 2569 GENESIS_L1_TESTNET = 26 EZCHAIN_C_CHAIN_TESTNET = 2613 OASISCHAIN_MAINNET = 26863 OPTIMISM_ON_GNOSIS_CHAIN = 300 CENNZNET_RATA = 3000 CENNZNET_NIKAU = 3001 PIECE_TESTNET = 30067 ZCORE_TESTNET = 3331 WEB3Q_TESTNET = 3333 WEB3Q_GALILEO = 3334 DFK_CHAIN_TEST = 335 DITHEREUM_TESTNET = 34 PARIBU_NET_MAINNET = 3400 PARIBU_NET_TESTNET = 3500 JFIN_CHAIN = 3501 Q_MAINNET = 35441 Q_TESTNET = 35443 DXCHAIN_MAINNET = 36 CROSSBELL = 3737 DYNO_MAINNET = 3966 DYNO_TESTNET = 3967 YUANCHAIN_MAINNET = 3999 BOBA_NETWORK_BOBAOPERA_TESTNET = 4051 AIOZ_NETWORK_TESTNET = 4102 OPTIMISM_GOERLI_TESTNET = 420 EMERALD_PARATIME_TESTNET = 42261 AVALANCHE_FUJI_TESTNET = 43113 DEXALOT_TESTNET = 432201 WEELINK_TESTNET = 444900 DARWINIA_PANGORO_TESTNET = 45 DARWINIA_NETWORK = 46 OPENCHAIN_MAINNET = 474142 CMP_TESTNET = 512512 DOUBLE_A_CHAIN_TESTNET = 513 TLCHAIN_NETWORK_MAINNET = 5177 XT_SMART_CHAIN_MAINNET = 520 F_X_CORE_MAINNET_NETWORK = 530 CANDLE = 534 OPENPIECE_MAINNET = 54 NAHMII_TESTNET = 5553 REI_CHAIN_TESTNET = 55556 DIGEST_SWARM_CHAIN = 5777 KARURA_NETWORK_TESTNET = 596 ACALA_NETWORK_TESTNET = 597 MESHNYAN_TESTNET = 600 THINKIUM_TESTNET_CHAIN_0 = 60000 THINKIUM_TESTNET_CHAIN_1 = 60001 THINKIUM_TESTNET_CHAIN_103 = 60103 THINKIUM_TESTNET_CHAIN_2 = 60002 ETHEREUM_CLASSIC_TESTNET_MORDEN = 62 ETHEREUM_CLASSIC_TESTNET_MORDOR = 63 MULTIVAC_MAINNET = 62621 ECREDITS_TESTNET = 63001 SX_NETWORK_TESTNET = 647 PIXIE_CHAIN_TESTNET = 666 VISION_VPIONEER_TEST_CHAIN = 666666 OPTIMISM_KOVAN = 69 CONDRIEU = 69420 TOMB_CHAIN_MAINNET = 6969 STAR_SOCIAL_TESTNET = 700 ELLA_THE_HEART = 7027 BLOCKCHAIN_STATION_TESTNET = 708 CONFLUX_ESPACE_TESTNET = 71 POLYJUICE_TESTNET = 71393 DXCHAIN_TESTNET = 72 MIXIN_VIRTUAL_MACHINE = 73927 OPENCHAIN_TESTNET = 776 FIRENZE_TEST_NETWORK = 78110 HAZLOR_TESTNET = 7878 AEROCHAIN_TESTNET = 788 PORTAL_FANTASY_CHAIN_TEST = 808 ZENITH_TESTNET_VILNIUS = 81 CALLISTO_TESTNET = 821 GODWOKEN_TESTNET_V1 = 868455272153094 AMBROS_CHAIN_TESTNET = 8888 IVAR_CHAIN_MAINNET = 88888 MAMMOTH_MAINNET = 8898 TOMOCHAIN_TESTNET = 89 UBIQ_NETWORK_TESTNET = 9 GARIZON_TESTNET_STAGE0 = 900 GARIZON_TESTNET_STAGE1 = 901 GARIZON_TESTNET_STAGE2 = 902 GARIZON_TESTNET_STAGE3 = 903 BERYLBIT_MAINNET = 9012 PORTAL_FANTASY_CHAIN = 909 PULSECHAIN_TESTNET = 940 PULSECHAIN_TESTNET_V2B = 941 PULSECHAIN_TESTNET_V3 = 942 RANGERS_PROTOCOL_TESTNET_ROBIN = 9527 TOP_MAINNET_EVM = 980 TOP_MAINNET = 989 MYOWN_TESTNET = 9999 UB_SMART_CHAIN_TESTNET = 99998 AXON_TESTNET = 10012 @classmethod def _missing_(cls, value): return cls.UNKNOWN
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/ethereum_network.py
0.439627
0.320422
ethereum_network.py
pypi
import warnings from secrets import token_bytes from typing import Tuple, Union import eth_abi from eth._utils.address import generate_contract_address from eth_keys import keys from eth_typing import AnyAddress, ChecksumAddress, HexStr from eth_utils import to_normalized_address from hexbytes import HexBytes from sha3 import keccak_256 def fast_keccak(value: bytes) -> bytes: """ Calculates ethereum keccak256 using fast library `pysha3` :param value: :return: Keccak256 used by ethereum as `bytes` """ return keccak_256(value).digest() def fast_keccak_hex(value: bytes) -> HexStr: """ Same as `fast_keccak`, but it's a little more optimal calling `hexdigest()` than calling `digest()` and then `hex()` :param value: :return: Keccak256 used by ethereum as an hex string (not 0x prefixed) """ return HexStr(keccak_256(value).hexdigest()) def _build_checksum_address( norm_address: HexStr, address_hash: HexStr ) -> ChecksumAddress: """ https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md :param norm_address: address in lowercase (not 0x prefixed) :param address_hash: keccak256 of `norm_address` (not 0x prefixed) :return: """ return ChecksumAddress( "0x" + ( "".join( ( norm_address[i].upper() if int(address_hash[i], 16) > 7 else norm_address[i] ) for i in range(0, 40) ) ) ) def fast_to_checksum_address(value: Union[AnyAddress, str, bytes]) -> ChecksumAddress: """ Converts to checksum_address. Uses more optimal `pysha3` instead of `eth_utils` for keccak256 calculation :param value: :return: """ norm_address = to_normalized_address(value)[2:] address_hash = fast_keccak_hex(norm_address.encode()) return _build_checksum_address(norm_address, address_hash) def fast_bytes_to_checksum_address(value: bytes) -> ChecksumAddress: """ Converts to checksum_address. Uses more optimal `pysha3` instead of `eth_utils` for keccak256 calculation. As input is already in bytes, some checks and conversions can be skipped, providing a speedup of ~50% :param value: :return: """ if len(value) != 20: raise ValueError( "Cannot convert %s to a checksum address, 20 bytes were expected" ) norm_address = bytes(value).hex() address_hash = fast_keccak_hex(norm_address.encode()) return _build_checksum_address(norm_address, address_hash) def fast_is_checksum_address(value: Union[AnyAddress, str, bytes]) -> bool: """ Fast version to check if an address is a checksum_address :param value: :return: `True` if checksummed, `False` otherwise """ if not isinstance(value, str) or len(value) != 42 or not value.startswith("0x"): return False try: return fast_to_checksum_address(value) == value except ValueError: return False def get_eth_address_with_key() -> Tuple[str, bytes]: private_key = keys.PrivateKey(token_bytes(32)) address = private_key.public_key.to_checksum_address() return address, private_key.to_bytes() def get_eth_address_with_invalid_checksum() -> str: address, _ = get_eth_address_with_key() return "0x" + "".join( [c.lower() if c.isupper() else c.upper() for c in address[2:]] ) def decode_string_or_bytes32(data: bytes) -> str: try: return eth_abi.decode_abi(["string"], data)[0] except OverflowError: name = eth_abi.decode_abi(["bytes32"], data)[0] end_position = name.find(b"\x00") if end_position == -1: return name.decode() else: return name[:end_position].decode() def remove_swarm_metadata(code: bytes) -> bytes: """ Remove swarm metadata from Solidity bytecode :param code: :return: Code without metadata """ swarm = b"\xa1\x65bzzr0" position = code.rfind(swarm) if position == -1: raise ValueError("Swarm metadata not found in code %s" % code.hex()) return code[:position] def compare_byte_code(code_1: bytes, code_2: bytes) -> bool: """ Compare code, removing swarm metadata if necessary :param code_1: :param code_2: :return: True if same code, False otherwise """ if code_1 == code_2: return True else: codes = [] for code in (code_1, code_2): try: codes.append(remove_swarm_metadata(code)) except ValueError: codes.append(code) return codes[0] == codes[1] def mk_contract_address(address: Union[str, bytes], nonce: int) -> ChecksumAddress: """ Generate expected contract address when using EVM CREATE :param address: :param nonce: :return: """ return fast_to_checksum_address(generate_contract_address(HexBytes(address), nonce)) def mk_contract_address_2( from_: Union[str, bytes], salt: Union[str, bytes], init_code: Union[str, bytes] ) -> ChecksumAddress: """ Generate expected contract address when using EVM CREATE2. :param from_: The address which is creating this new address (need to be 20 bytes) :param salt: A salt (32 bytes) :param init_code: A init code of the contract being created :return: Address of the new contract """ from_ = HexBytes(from_) salt = HexBytes(salt) init_code = HexBytes(init_code) assert len(from_) == 20, f"Address {from_.hex()} is not valid. Must be 20 bytes" assert len(salt) == 32, f"Salt {salt.hex()} is not valid. Must be 32 bytes" assert len(init_code) > 0, f"Init code {init_code.hex()} is not valid" init_code_hash = fast_keccak(init_code) contract_address = fast_keccak(HexBytes("ff") + from_ + salt + init_code_hash) return fast_bytes_to_checksum_address(contract_address[12:]) def generate_address_2( from_: Union[str, bytes], salt: Union[str, bytes], init_code: Union[str, bytes] ) -> ChecksumAddress: """ .. deprecated:: use mk_contract_address_2 :param from_: :param salt: :param init_code: :return: """ warnings.warn( "`generate_address_2` is deprecated, use `mk_contract_address_2`", DeprecationWarning, ) return mk_contract_address_2(from_, salt, init_code)
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/utils.py
0.900547
0.58255
utils.py
pypi
import logging from dataclasses import dataclass from typing import Any, List, Optional, Sequence, Tuple from eth_abi.exceptions import DecodingError from eth_account.signers.local import LocalAccount from eth_typing import BlockIdentifier, BlockNumber, ChecksumAddress from hexbytes import HexBytes from web3 import Web3 from web3._utils.abi import map_abi_data from web3._utils.normalizers import BASE_RETURN_NORMALIZERS from web3.contract import ContractFunction from web3.exceptions import ContractLogicError from . import EthereumClient, EthereumNetwork, EthereumNetworkNotSupported from .ethereum_client import EthereumTxSent from .exceptions import BatchCallFunctionFailed from .oracles.abis.makerdao import multicall_v2_abi, multicall_v2_bytecode logger = logging.getLogger(__name__) @dataclass class MulticallResult: success: bool return_data: Optional[bytes] @dataclass class MulticallDecodedResult: success: bool return_data_decoded: Optional[Any] class Multicall: ADDRESSES = { EthereumNetwork.MAINNET: "0x5BA1e12693Dc8F9c48aAD8770482f4739bEeD696", EthereumNetwork.ARBITRUM: "0x021CeAC7e681dBCE9b5039d2535ED97590eB395c", EthereumNetwork.AVALANCHE: "0xAbeC56f92a89eEe33F5194Ca4151DD59785c2C74", EthereumNetwork.BINANCE: "0xed386Fe855C1EFf2f843B910923Dd8846E45C5A4", EthereumNetwork.FANTOM: "0xD98e3dBE5950Ca8Ce5a4b59630a5652110403E5c", EthereumNetwork.GOERLI: "0x5BA1e12693Dc8F9c48aAD8770482f4739bEeD696", EthereumNetwork.KOVAN: "0x5BA1e12693Dc8F9c48aAD8770482f4739bEeD696", EthereumNetwork.MATIC: "0xed386Fe855C1EFf2f843B910923Dd8846E45C5A4", EthereumNetwork.MUMBAI: "0xed386Fe855C1EFf2f843B910923Dd8846E45C5A4", EthereumNetwork.OPTIMISTIC: "0x2DC0E2aa608532Da689e89e237dF582B783E552C", EthereumNetwork.RINKEBY: "0x5BA1e12693Dc8F9c48aAD8770482f4739bEeD696", EthereumNetwork.ROPSTEN: "0x5BA1e12693Dc8F9c48aAD8770482f4739bEeD696", EthereumNetwork.XDAI: "0x08612d3C4A5Dfe2FaaFaFe6a4ff712C2dC675bF7", EthereumNetwork.KCC_MAINNET: "0x7C1C85C39d3D6b6ecB811dfe949B9C23f6E818B0", EthereumNetwork.KCC_TESTNET: "0x665683D9bd41C09cF38c3956c926D9924F1ADa97", } def __init__( self, ethereum_client: EthereumClient, multicall_contract_address: Optional[ChecksumAddress] = None, ): self.ethereum_client = ethereum_client self.w3 = ethereum_client.w3 ethereum_network = ethereum_client.get_network() address = multicall_contract_address or self.ADDRESSES.get(ethereum_network) if not address: raise EthereumNetworkNotSupported( "Multicall contract not available for %s", ethereum_network.name ) self.contract = self.get_contract(self.w3, address) def get_contract(self, w3: Web3, address: Optional[ChecksumAddress] = None): return w3.eth.contract( address, abi=multicall_v2_abi, bytecode=multicall_v2_bytecode ) @classmethod def deploy_contract( cls, ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy contract :param ethereum_client: :param deployer_account: Ethereum Account :return: deployed contract address """ contract = cls.get_contract(cls, ethereum_client.w3) tx = contract.constructor().build_transaction( {"from": deployer_account.address} ) tx_hash = ethereum_client.send_unsigned_transaction( tx, private_key=deployer_account.key ) tx_receipt = ethereum_client.get_transaction_receipt(tx_hash, timeout=120) assert tx_receipt and tx_receipt["status"] contract_address = tx_receipt["contractAddress"] logger.info( "Deployed Multicall V2 Contract %s by %s", contract_address, deployer_account.address, ) # Add address to addresses dictionary cls.ADDRESSES[ethereum_client.get_network()] = contract_address return EthereumTxSent(tx_hash, tx, contract_address) @staticmethod def _build_payload( contract_functions: Sequence[ContractFunction], ) -> Tuple[List[Tuple[ChecksumAddress, bytes]], List[List[Any]]]: targets_with_data = [] output_types = [] for contract_function in contract_functions: targets_with_data.append( ( contract_function.address, HexBytes(contract_function._encode_transaction_data()), ) ) output_types.append( [output["type"] for output in contract_function.abi["outputs"]] ) return targets_with_data, output_types def _build_payload_same_function( self, contract_function: ContractFunction, contract_addresses: Sequence[ChecksumAddress], ) -> Tuple[List[Tuple[ChecksumAddress, bytes]], List[List[Any]]]: targets_with_data = [] output_types = [] tx_data = HexBytes(contract_function._encode_transaction_data()) for contract_address in contract_addresses: targets_with_data.append((contract_address, tx_data)) output_types.append( [output["type"] for output in contract_function.abi["outputs"]] ) return targets_with_data, output_types def _decode_data(self, output_type: Sequence[str], data: bytes) -> Optional[Any]: """ :param output_type: :param data: :return: :raises: DecodingError """ if data: try: decoded_values = self.w3.codec.decode_abi(output_type, data) normalized_data = map_abi_data( BASE_RETURN_NORMALIZERS, output_type, decoded_values ) if len(normalized_data) == 1: return normalized_data[0] else: return normalized_data except DecodingError: logger.warning( "Cannot decode %s using output-type %s", data, output_type ) return data def _aggregate( self, targets_with_data: Sequence[Tuple[ChecksumAddress, bytes]], block_identifier: Optional[BlockIdentifier] = "latest", ) -> Tuple[BlockNumber, List[Optional[Any]]]: """ :param targets_with_data: List of target `addresses` and `data` to be called in each Contract :param block_identifier: :return: :raises: BatchCallFunctionFailed """ aggregate_parameter = [ {"target": target, "callData": data} for target, data in targets_with_data ] try: return self.contract.functions.aggregate(aggregate_parameter).call( block_identifier=block_identifier ) except (ContractLogicError, OverflowError): raise BatchCallFunctionFailed def aggregate( self, contract_functions: Sequence[ContractFunction], block_identifier: Optional[BlockIdentifier] = "latest", ) -> Tuple[BlockNumber, List[Optional[Any]]]: """ Calls ``aggregate`` on MakerDAO's Multicall contract. If a function called raises an error execution is stopped :param contract_functions: :param block_identifier: :return: A tuple with the ``blockNumber`` and a list with the decoded return values :raises: BatchCallFunctionFailed """ targets_with_data, output_types = self._build_payload(contract_functions) block_number, results = self._aggregate( targets_with_data, block_identifier=block_identifier ) decoded_results = [ self._decode_data(output_type, data) for output_type, data in zip(output_types, results) ] return block_number, decoded_results def _try_aggregate( self, targets_with_data: Sequence[Tuple[ChecksumAddress, bytes]], require_success: bool = False, block_identifier: Optional[BlockIdentifier] = "latest", ) -> List[MulticallResult]: """ Calls ``try_aggregate`` on MakerDAO's Multicall contract. :param targets_with_data: :param require_success: If ``True``, an exception in any of the functions will stop the execution. Also, an invalid decoded value will stop the execution :param block_identifier: :return: A list with the decoded return values """ aggregate_parameter = [ {"target": target, "callData": data} for target, data in targets_with_data ] try: result = self.contract.functions.tryAggregate( require_success, aggregate_parameter ).call(block_identifier=block_identifier) if require_success and b"" in (data for _, data in result): # `b''` values are decoding errors/missing contracts/missing functions raise BatchCallFunctionFailed return [ MulticallResult(success, data if data else None) for success, data in result ] except (ContractLogicError, OverflowError, ValueError): raise BatchCallFunctionFailed def try_aggregate( self, contract_functions: Sequence[ContractFunction], require_success: bool = False, block_identifier: Optional[BlockIdentifier] = "latest", ) -> List[MulticallDecodedResult]: """ Calls ``try_aggregate`` on MakerDAO's Multicall contract. :param contract_functions: :param require_success: If ``True``, an exception in any of the functions will stop the execution :param block_identifier: :return: A list with the decoded return values """ targets_with_data, output_types = self._build_payload(contract_functions) results = self._try_aggregate( targets_with_data, require_success=require_success, block_identifier=block_identifier, ) return [ MulticallDecodedResult( multicall_result.success, self._decode_data(output_type, multicall_result.return_data) if multicall_result.success else multicall_result.return_data, ) for output_type, multicall_result in zip(output_types, results) ] def try_aggregate_same_function( self, contract_function: ContractFunction, contract_addresses: Sequence[ChecksumAddress], require_success: bool = False, block_identifier: Optional[BlockIdentifier] = "latest", ) -> List[MulticallDecodedResult]: """ Calls ``try_aggregate`` on MakerDAO's Multicall contract. Reuse same function with multiple contract addresses. It's more optimal due to instantiating ``ContractFunction`` objects is very demanding :param contract_function: :param contract_addresses: :param require_success: If ``True``, an exception in any of the functions will stop the execution :param block_identifier: :return: A list with the decoded return values """ targets_with_data, output_types = self._build_payload_same_function( contract_function, contract_addresses ) results = self._try_aggregate( targets_with_data, require_success=require_success, block_identifier=block_identifier, ) return [ MulticallDecodedResult( multicall_result.success, self._decode_data(output_type, multicall_result.return_data) if multicall_result.success else multicall_result.return_data, ) for output_type, multicall_result in zip(output_types, results) ]
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/multicall.py
0.898009
0.209348
multicall.py
pypi
import json import time from typing import Any, Dict, Optional from urllib.parse import urljoin import requests from .. import EthereumNetwork from .contract_metadata import ContractMetadata class EtherscanClientException(Exception): pass class EtherscanClientConfigurationProblem(Exception): pass class EtherscanRateLimitError(EtherscanClientException): pass class EtherscanClient: NETWORK_WITH_URL = { EthereumNetwork.MAINNET: "https://etherscan.io", EthereumNetwork.RINKEBY: "https://rinkeby.etherscan.io", EthereumNetwork.ROPSTEN: "https://ropsten.etherscan.io", EthereumNetwork.GOERLI: "https://goerli.etherscan.io", EthereumNetwork.KOVAN: "https://kovan.etherscan.io", EthereumNetwork.BINANCE: "https://bscscan.com", EthereumNetwork.MATIC: "https://polygonscan.com", EthereumNetwork.OPTIMISTIC: "https://optimistic.etherscan.io", EthereumNetwork.ARBITRUM: "https://arbiscan.io", EthereumNetwork.AVALANCHE: "https://snowtrace.io", EthereumNetwork.MOON_MOONBEAM: "https://moonscan.io", EthereumNetwork.MOON_MOONRIVER: "https://moonriver.moonscan.io", EthereumNetwork.MOON_MOONBASE: "https://moonbase.moonscan.io", EthereumNetwork.CRONOS_MAINNET: "https://cronoscan.com", EthereumNetwork.CRONOS_TESTNET: "https://testnet.cronoscan.com", } NETWORK_WITH_API_URL = { EthereumNetwork.MAINNET: "https://api.etherscan.io", EthereumNetwork.RINKEBY: "https://api-rinkeby.etherscan.io", EthereumNetwork.ROPSTEN: "https://api-ropsten.etherscan.io", EthereumNetwork.GOERLI: "https://api-goerli.etherscan.io/", EthereumNetwork.KOVAN: "https://api-kovan.etherscan.io/", EthereumNetwork.BINANCE: "https://api.bscscan.com", EthereumNetwork.MATIC: "https://api.polygonscan.com", EthereumNetwork.OPTIMISTIC: "https://api-optimistic.etherscan.io", EthereumNetwork.ARBITRUM: "https://api.arbiscan.io", EthereumNetwork.AVALANCHE: "https://api.snowtrace.io", EthereumNetwork.MOON_MOONBEAM: "https://api-moonbeam.moonscan.io", EthereumNetwork.MOON_MOONRIVER: "https://api-moonriver.moonscan.io", EthereumNetwork.MOON_MOONBASE: "https://api-moonbase.moonscan.io", EthereumNetwork.CRONOS_MAINNET: "https://api.cronoscan.com", EthereumNetwork.CRONOS_TESTNET: "https://api-testnet.cronoscan.com", } HTTP_HEADERS = { "User-Agent": "curl/7.77.0", } def __init__(self, network: EthereumNetwork, api_key: Optional[str] = None): self.network = network self.api_key = api_key self.base_url = self.NETWORK_WITH_URL.get(network) self.base_api_url = self.NETWORK_WITH_API_URL.get(network) if self.base_api_url is None: raise EtherscanClientConfigurationProblem( f"Network {network.name} - {network.value} not supported" ) self.http_session = requests.Session() self.http_session.headers = self.HTTP_HEADERS def build_url(self, path: str): url = urljoin(self.base_api_url, path) if self.api_key: url += f"&apikey={self.api_key}" return url def _do_request(self, url: str) -> Optional[Dict[str, Any]]: response = self.http_session.get(url) if response.ok: response_json = response.json() result = response_json["result"] if "Max rate limit reached" in result: # Max rate limit reached, please use API Key for higher rate limit raise EtherscanRateLimitError if response_json["status"] == "1": return result def _retry_request(self, url: str, retry: bool = True) -> Optional[Dict[str, Any]]: for _ in range(3): try: return self._do_request(url) except EtherscanRateLimitError as exc: if not retry: raise exc else: time.sleep(5) def get_contract_metadata( self, contract_address: str, retry: bool = True ) -> Optional[ContractMetadata]: contract_source_code = self.get_contract_source_code( contract_address, retry=retry ) if contract_source_code: contract_name = contract_source_code["ContractName"] contract_abi = contract_source_code["ABI"] if contract_abi: return ContractMetadata(contract_name, contract_abi, False) def get_contract_source_code(self, contract_address: str, retry: bool = True): """ Get source code for a contract. Source code query also returns: - ContractName: "", - CompilerVersion: "", - OptimizationUsed: "", - Runs: "", - ConstructorArguments: "" - EVMVersion: "Default", - Library: "", - LicenseType: "", - Proxy: "0", - Implementation: "", - SwarmSource: "" :param contract_address: :param retry: if ``True``, try again if there's Rate Limit Error :return: """ url = self.build_url( f"api?module=contract&action=getsourcecode&address={contract_address}" ) result = self._retry_request(url, retry=retry) # Returns a list if result: result = result[0] abi_str = result["ABI"] result["ABI"] = json.loads(abi_str) if abi_str.startswith("[") else None return result def get_contract_abi(self, contract_address: str, retry: bool = True): url = self.build_url( f"api?module=contract&action=getabi&address={contract_address}" ) result = self._retry_request(url, retry=retry) if result: return json.loads(result)
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/clients/etherscan_client.py
0.742141
0.295059
etherscan_client.py
pypi
from typing import Any, Dict, List, Optional from urllib.parse import urljoin import requests from .. import EthereumNetwork from ..utils import fast_is_checksum_address from .contract_metadata import ContractMetadata class Sourcify: """ Get contract metadata from Sourcify. Matches can be full or partial: - Full: Both the source files as well as the meta data files were an exact match between the deployed bytecode and the published files. - Partial: Source code compiles to the same bytecode and thus the contract behaves in the same way, but the source code can be different: Variables can have misleading names, comments can be different and especially the NatSpec comments could have been modified. """ def __init__( self, network: EthereumNetwork = EthereumNetwork.MAINNET, base_url: str = "https://repo.sourcify.dev/", ): self.network = network self.base_url = base_url self.http_session = requests.session() def _get_abi_from_metadata(self, metadata: Dict[str, Any]) -> List[Dict[str, Any]]: return metadata["output"]["abi"] def _get_name_from_metadata(self, metadata: Dict[str, Any]) -> Optional[str]: values = list(metadata["settings"].get("compilationTarget", {}).values()) if values: return values[0] def _do_request(self, url: str) -> Optional[Dict[str, Any]]: response = self.http_session.get(url, timeout=10) if not response.ok: return None return response.json() def get_contract_metadata( self, contract_address: str ) -> Optional[ContractMetadata]: assert fast_is_checksum_address( contract_address ), "Expecting a checksummed address" for match_type in ("full_match", "partial_match"): url = urljoin( self.base_url, f"/contracts/{match_type}/{self.network.value}/{contract_address}/metadata.json", ) metadata = self._do_request(url) if metadata: abi = self._get_abi_from_metadata(metadata) name = self._get_name_from_metadata(metadata) return ContractMetadata(name, abi, match_type == "partial_match") return None
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/clients/sourcify.py
0.899345
0.365966
sourcify.py
pypi
import json from typing import Any, Dict, Optional from urllib.parse import urljoin import requests from eth_typing import ChecksumAddress from .. import EthereumNetwork from .contract_metadata import ContractMetadata class BlockscoutClientException(Exception): pass class BlockScoutConfigurationProblem(BlockscoutClientException): pass class BlockscoutClient: NETWORK_WITH_URL = { EthereumNetwork.XDAI: "https://blockscout.com/poa/xdai/", EthereumNetwork.MATIC: "https://polygon-explorer-mainnet.chainstacklabs.com/", EthereumNetwork.MUMBAI: "https://polygon-explorer-mumbai.chainstacklabs.com/", EthereumNetwork.ENERGY_WEB_CHAIN: "https://explorer.energyweb.org/", EthereumNetwork.VOLTA: "https://volta-explorer.energyweb.org/", EthereumNetwork.OLYMPUS: "https://explorer.polis.tech", EthereumNetwork.BOBA_NETWORK_BOBABEAM: "https://blockexplorer.bobabeam.boba.network/", EthereumNetwork.BOBA_RINKEBY: "https://blockexplorer.rinkeby.boba.network/", EthereumNetwork.BOBA: "https://blockexplorer.boba.network/", EthereumNetwork.GATHER_DEVNET: "https://devnet-explorer.gather.network/", EthereumNetwork.GATHER_TESTNET: "https://testnet-explorer.gather.network/", EthereumNetwork.GATHER_MAINNET: "https://explorer.gather.network/", EthereumNetwork.METIS_TESTNET: "https://stardust-explorer.metis.io/", EthereumNetwork.METIS_GOERLI_TESTNET: "https://goerli.explorer.metisdevops.link/", EthereumNetwork.METIS: "https://andromeda-explorer.metis.io/", EthereumNetwork.FUSE_MAINNET: "https://explorer.fuse.io/", EthereumNetwork.VELAS_MAINNET: "https://evmexplorer.velas.com/", EthereumNetwork.REI_MAINNET: "https://scan.rei.network/", EthereumNetwork.REI_TESTNET: "https://scan-test.rei.network/", EthereumNetwork.METER: "https://scan.meter.io/", EthereumNetwork.METER_TESTNET: "https://scan-warringstakes.meter.io/", EthereumNetwork.GODWOKEN_TESTNET: "https://v1.betanet.gwscan.com/", EthereumNetwork.GODWOKEN: "https://v1.gwscan.com/", EthereumNetwork.VENIDIUM_TESTNET: "https://evm-testnet.venidiumexplorer.com/", EthereumNetwork.VENIDIUM: "https://evm.venidiumexplorer.com/", EthereumNetwork.KLAY_BAOBAB: "https://baobab.scope.klaytn.com/", EthereumNetwork.KLAY_CYPRESS: "https://scope.klaytn.com/", EthereumNetwork.ACA: "https://blockscout.acala.network/", EthereumNetwork.KARURA_NETWORK_TESTNET: "https://blockscout.karura.network/", EthereumNetwork.ACALA_NETWORK_TESTNET: "https://blockscout.mandala.acala.network/", EthereumNetwork.ASTAR: "https://blockscout.com/astar/", EthereumNetwork.EVMOS_MAINNET: "https://evm.evmos.org", EthereumNetwork.EVMOS_TESTNET: "https://evm.evmos.dev", EthereumNetwork.RABBIT: "https://rabbit.analogscan.com", EthereumNetwork.KCC_MAINNET: "https://scan.kcc.io/", EthereumNetwork.KCC_TESTNET: "https://scan-testnet.kcc.network/", EthereumNetwork.AXON_TESTNET: "https://www.axon-node.info/", } def __init__(self, network: EthereumNetwork): self.network = network self.base_url = self.NETWORK_WITH_URL.get(network) if self.base_url is None: raise BlockScoutConfigurationProblem( f"Network {network.name} - {network.value} not supported" ) self.grahpql_url = self.base_url + "/graphiql" self.http_session = requests.Session() def build_url(self, path: str): return urljoin(self.base_url, path) def _do_request(self, url: str, query: str) -> Optional[Dict[str, Any]]: response = self.http_session.post(url, json={"query": query}, timeout=10) if not response.ok: return None return response.json() def get_contract_metadata( self, address: ChecksumAddress ) -> Optional[ContractMetadata]: query = '{address(hash: "%s") { hash, smartContract {name, abi} }}' % address result = self._do_request(self.grahpql_url, query) if ( result and "error" not in result and result.get("data", {}).get("address", {}) and result["data"]["address"]["smartContract"] ): smart_contract = result["data"]["address"]["smartContract"] return ContractMetadata( smart_contract["name"], json.loads(smart_contract["abi"]), False )
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/clients/blockscout_client.py
0.768386
0.364042
blockscout_client.py
pypi
import binascii from typing import Optional, Union from django.core import exceptions from django.db import models from django.utils.translation import gettext_lazy as _ from eth_typing import ChecksumAddress from eth_utils import to_normalized_address from hexbytes import HexBytes from ..utils import fast_bytes_to_checksum_address, fast_to_checksum_address from .forms import EthereumAddressFieldForm, HexFieldForm, Keccak256FieldForm from .validators import validate_checksumed_address try: from django.db import DefaultConnectionProxy connection = DefaultConnectionProxy() except ImportError: from django.db import connections connection = connections["default"] class EthereumAddressField(models.CharField): default_validators = [validate_checksumed_address] description = "DEPRECATED. Use `EthereumAddressV2Field`. Ethereum address (EIP55)" default_error_messages = { "invalid": _('"%(value)s" value must be an EIP55 checksummed address.'), } def __init__(self, *args, **kwargs): kwargs["max_length"] = 42 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs def from_db_value(self, value, expression, connection): return self.to_python(value) def to_python(self, value): value = super().to_python(value) if value: try: return fast_to_checksum_address(value) except ValueError: raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) else: return value def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) class EthereumAddressV2Field(models.Field): default_validators = [validate_checksumed_address] description = "Ethereum address (EIP55)" default_error_messages = { "invalid": _('"%(value)s" value must be an EIP55 checksummed address.'), } def get_internal_type(self): return "BinaryField" def from_db_value( self, value: memoryview, expression, connection ) -> Optional[ChecksumAddress]: if value: return fast_bytes_to_checksum_address(value) def get_prep_value(self, value: ChecksumAddress) -> Optional[bytes]: if value: try: return HexBytes(to_normalized_address(value)) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def to_python(self, value) -> Optional[ChecksumAddress]: if value is not None: try: return fast_to_checksum_address(value) except ValueError: raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def formfield(self, **kwargs): defaults = { "form_class": EthereumAddressFieldForm, "max_length": 2 + 40, } defaults.update(kwargs) return super().formfield(**defaults) class Uint256Field(models.DecimalField): """ Field to store ethereum uint256 values. Uses Decimal db type without decimals to store in the database, but retrieve as `int` instead of `Decimal` (https://docs.python.org/3/library/decimal.html) """ description = _("Ethereum uint256 number") def __init__(self, *args, **kwargs): kwargs["max_digits"] = 79 # 2 ** 256 is 78 digits kwargs["decimal_places"] = 0 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_digits"] del kwargs["decimal_places"] return name, path, args, kwargs def from_db_value(self, value, expression, connection): if value is None: return value return int(value) class HexField(models.CharField): """ Field to store hex values (without 0x). Returns hex with 0x prefix. On Database side a CharField is used. """ description = "Stores a hex value into a CharField. DEPRECATED, use a BinaryField" def from_db_value(self, value, expression, connection): return self.to_python(value) def to_python(self, value): return value if value is None else HexBytes(value).hex() def get_prep_value(self, value): if value is None: return value elif isinstance(value, HexBytes): return value.hex()[ 2: ] # HexBytes.hex() retrieves hexadecimal with '0x', remove it elif isinstance(value, bytes): return value.hex() # bytes.hex() retrieves hexadecimal without '0x' else: # str return HexBytes(value).hex()[2:] def formfield(self, **kwargs): # We need max_lenght + 2 on forms because of `0x` defaults = {"max_length": self.max_length + 2} # TODO: Handle multiple backends with different feature flags. if self.null and not connection.features.interprets_empty_strings_as_nulls: defaults["empty_value"] = None defaults.update(kwargs) return super().formfield(**defaults) def clean(self, value, model_instance): value = self.to_python(value) self.validate(value, model_instance) # Validation didn't work because of `0x` self.run_validators(value[2:]) return value class HexV2Field(models.BinaryField): def formfield(self, **kwargs): defaults = { "form_class": HexFieldForm, } defaults.update(kwargs) return super().formfield(**defaults) class Sha3HashField(HexField): description = "DEPRECATED. Use `Keccak256Field`" def __init__(self, *args, **kwargs): kwargs["max_length"] = 64 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs class Keccak256Field(models.BinaryField): description = "Keccak256 hash stored as binary" default_error_messages = { "invalid": _('"%(value)s" hash must be a 32 bytes hexadecimal.'), "length": _('"%(value)s" hash must have exactly 32 bytes.'), } def _to_bytes(self, value) -> Optional[bytes]: if value is None: return else: try: result = HexBytes(value) if len(result) != 32: raise exceptions.ValidationError( self.error_messages["length"], code="length", params={"value": value}, ) return result except (ValueError, binascii.Error): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def from_db_value( self, value: memoryview, expression, connection ) -> Optional[bytes]: if value: return HexBytes(value.tobytes()).hex() def get_prep_value(self, value: Union[bytes, str]) -> Optional[bytes]: if value: return self._to_bytes(value) def to_python(self, value) -> Optional[str]: if value is not None: try: return self._to_bytes(value) except (ValueError, binascii.Error): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def formfield(self, **kwargs): defaults = { "form_class": Keccak256FieldForm, "max_length": 2 + 64, } defaults.update(kwargs) return super().formfield(**defaults)
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/django/models.py
0.826362
0.198239
models.py
pypi
import binascii from typing import Any, Optional from django import forms from django.core import exceptions from django.core.exceptions import ValidationError from django.utils.translation import gettext as _ from hexbytes import HexBytes from gnosis.eth.utils import fast_is_checksum_address class EthereumAddressFieldForm(forms.CharField): default_error_messages = { "invalid": _("Enter a valid checksummed Ethereum Address."), } def prepare_value(self, value): return value def to_python(self, value): value = super().to_python(value) if value in self.empty_values: return None elif not fast_is_checksum_address(value): raise ValidationError(self.error_messages["invalid"], code="invalid") return value class HexFieldForm(forms.CharField): default_error_messages = { "invalid": _("Enter a valid hexadecimal."), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.empty_value = None def prepare_value(self, value: memoryview) -> str: if value: return "0x" + bytes(value).hex() else: return "" def to_python(self, value: Optional[Any]) -> Optional[HexBytes]: if value in self.empty_values: return self.empty_value try: if isinstance(value, str): value = value.strip() return HexBytes(value) except (binascii.Error, TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) class Keccak256FieldForm(HexFieldForm): default_error_messages = { "invalid": _('"%(value)s" is not a valid keccak256 hash.'), "length": _('"%(value)s" keccak256 hash should be 32 bytes.'), } def prepare_value(self, value: str) -> str: # Keccak field already returns a hex str return value def to_python(self, value: Optional[Any]) -> HexBytes: value: Optional[HexBytes] = super().to_python(value) if value and len(value) != 32: raise ValidationError( self.error_messages["length"], code="length", params={"value": value.hex()}, ) return value
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/django/forms.py
0.856107
0.237443
forms.py
pypi
import functools import logging from typing import Optional from eth_abi.exceptions import DecodingError from eth_typing import ChecksumAddress from web3.contract import Contract from web3.exceptions import BadFunctionCallOutput from gnosis.util import cached_property from .. import EthereumClient from ..constants import NULL_ADDRESS from ..contracts import get_erc20_contract from .abis.uniswap_v3 import ( uniswap_v3_factory_abi, uniswap_v3_pool_abi, uniswap_v3_router_abi, ) from .exceptions import CannotGetPriceFromOracle from .oracles import PriceOracle from .utils import get_decimals logger = logging.getLogger(__name__) class UniswapV3Oracle(PriceOracle): # https://docs.uniswap.org/protocol/reference/deployments UNISWAP_V3_ROUTER = "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45" # Cache to optimize calculation: https://docs.uniswap.org/sdk/guides/fetching-prices#understanding-sqrtprice PRICE_CONVERSION_CONSTANT = 2**192 def __init__( self, ethereum_client: EthereumClient, uniswap_v3_router_address: Optional[ChecksumAddress] = None, ): """ :param ethereum_client: """ self.ethereum_client = ethereum_client self.w3 = ethereum_client.w3 self.router_address = uniswap_v3_router_address or self.UNISWAP_V3_ROUTER self.factory = self.get_factory() @classmethod def is_available( cls, ethereum_client: EthereumClient, uniswap_v3_router_address: Optional[ChecksumAddress] = None, ) -> bool: """ :param ethereum_client: :param uniswap_v3_router_address: :return: `True` if Uniswap V3 is available for the EthereumClient provided, `False` otherwise """ return ethereum_client.is_contract( uniswap_v3_router_address or cls.UNISWAP_V3_ROUTER ) def get_factory(self) -> Contract: """ Factory contract creates the pools for token pairs :return: Uniswap V3 Factory Contract """ try: factory_address = self.router.functions.factory().call() except BadFunctionCallOutput: raise ValueError( f"Uniswap V3 Router Contract {self.router_address} does not exist" ) return self.w3.eth.contract(factory_address, abi=uniswap_v3_factory_abi) @cached_property def router(self) -> Contract: """ Router knows about the `Uniswap Factory` and `Wrapped Eth` addresses for the network :return: Uniswap V3 Router Contract """ return self.w3.eth.contract(self.router_address, abi=uniswap_v3_router_abi) @cached_property def weth_address(self) -> ChecksumAddress: """ :return: Wrapped ether checksummed address """ return self.router.functions.WETH9().call() @functools.lru_cache(maxsize=512) def get_pool_address( self, token_address: str, token_address_2: str, fee: Optional[int] = 3000 ) -> Optional[ChecksumAddress]: """ Get pool address for tokens with a given fee (by default, 0.3) :param token_address: :param token_address_2: :param fee: Uniswap V3 uses 0.3 as the default fee :return: Pool address """ pool_address = self.factory.functions.getPool( token_address, token_address_2, fee ).call() if pool_address == NULL_ADDRESS: return None return pool_address def get_price( self, token_address: str, token_address_2: Optional[str] = None ) -> float: """ :param token_address: :param token_address_2: :return: price for `token_address` related to `token_address_2`. If `token_address_2` is not provided, `Wrapped Eth` address will be used """ token_address_2 = token_address_2 or self.weth_address if token_address == token_address_2: return 1.0 reversed = token_address.lower() > token_address_2.lower() # Make it cache friendly as order does not matter args = ( (token_address_2, token_address) if reversed else (token_address, token_address_2) ) pool_address = self.get_pool_address(*args) if not pool_address: raise CannotGetPriceFromOracle( f"Uniswap V3 pool does not exist for {token_address} and {token_address_2}" ) # Decimals needs to be adjusted token_decimals = get_decimals(token_address, self.ethereum_client) token_2_decimals = get_decimals(token_address_2, self.ethereum_client) pool_contract = self.w3.eth.contract(pool_address, abi=uniswap_v3_pool_abi) try: ( token_balance, token_2_balance, (sqrt_price_x96, _, _, _, _, _, _), ) = self.ethereum_client.batch_call( [ get_erc20_contract( self.ethereum_client.w3, token_address ).functions.balanceOf(pool_address), get_erc20_contract( self.ethereum_client.w3, token_address_2 ).functions.balanceOf(pool_address), pool_contract.functions.slot0(), ] ) if (token_balance / 10**token_decimals) < 2 or ( token_2_balance / 10**token_2_decimals ) < 2: error_message = ( f"Not enough liquidity on uniswap v3 for pair token_1={token_address} " f"token_2={token_address_2}, at least 2 units of each token are required" ) logger.warning(error_message) raise CannotGetPriceFromOracle(error_message) except ( ValueError, BadFunctionCallOutput, DecodingError, ) as e: error_message = ( f"Cannot get uniswap v3 price for pair token_1={token_address} " f"token_2={token_address_2}" ) logger.warning(error_message) raise CannotGetPriceFromOracle(error_message) from e # https://docs.uniswap.org/sdk/guides/fetching-prices if not reversed: # Multiplying by itself is way faster than exponential price = (sqrt_price_x96 * sqrt_price_x96) / self.PRICE_CONVERSION_CONSTANT else: price = self.PRICE_CONVERSION_CONSTANT / (sqrt_price_x96 * sqrt_price_x96) return price * 10 ** (token_decimals - token_2_decimals)
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/oracles/uniswap_v3.py
0.860516
0.188175
uniswap_v3.py
pypi
import logging from typing import Optional from eth_abi.exceptions import DecodingError from web3.exceptions import BadFunctionCallOutput from gnosis.util import cached_property from .. import EthereumClient, EthereumNetwork from ..contracts import get_kyber_network_proxy_contract from .exceptions import CannotGetPriceFromOracle, InvalidPriceFromOracle from .oracles import PriceOracle from .utils import get_decimals logger = logging.getLogger(__name__) class KyberOracle(PriceOracle): """ KyberSwap Legacy Oracle https://docs.kyberswap.com/Legacy/addresses/addresses-mainnet """ # This is the `tokenAddress` they use for ETH ¯\_(ツ)_/¯ ETH_TOKEN_ADDRESS = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" ADDRESSES = { EthereumNetwork.MAINNET: "0x9AAb3f75489902f3a48495025729a0AF77d4b11e", EthereumNetwork.RINKEBY: "0x0d5371e5EE23dec7DF251A8957279629aa79E9C5", EthereumNetwork.ROPSTEN: "0xd719c34261e099Fdb33030ac8909d5788D3039C4", EthereumNetwork.KOVAN: "0xc153eeAD19e0DBbDb3462Dcc2B703cC6D738A37c", } def __init__( self, ethereum_client: EthereumClient, kyber_network_proxy_address: Optional[str] = None, ): """ :param ethereum_client: :param kyber_network_proxy_address: https://developer.kyber.network/docs/MainnetEnvGuide/#contract-addresses """ self.ethereum_client = ethereum_client self.w3 = ethereum_client.w3 self._kyber_network_proxy_address = kyber_network_proxy_address @classmethod def is_available( cls, ethereum_client: EthereumClient, ) -> bool: """ :param ethereum_client: :return: `True` if Oracle is available for the EthereumClient provided, `False` otherwise """ return ethereum_client.get_network() in cls.ADDRESSES @cached_property def kyber_network_proxy_address(self): if self._kyber_network_proxy_address: return self._kyber_network_proxy_address return self.ADDRESSES.get( self.ethereum_client.get_network(), self.ADDRESSES.get(EthereumNetwork.MAINNET), ) # By default return Mainnet address @cached_property def kyber_network_proxy_contract(self): return get_kyber_network_proxy_contract( self.w3, self.kyber_network_proxy_address ) def get_price( self, token_address_1: str, token_address_2: str = ETH_TOKEN_ADDRESS ) -> float: if token_address_1 == token_address_2: return 1.0 try: # Get decimals for token, estimation will be more accurate decimals = get_decimals(token_address_1, self.ethereum_client) token_unit = int(10**decimals) ( expected_rate, _, ) = self.kyber_network_proxy_contract.functions.getExpectedRate( token_address_1, token_address_2, int(token_unit) ).call() price = expected_rate / 1e18 if price <= 0.0: # Try again the opposite ( expected_rate, _, ) = self.kyber_network_proxy_contract.functions.getExpectedRate( token_address_2, token_address_1, int(token_unit) ).call() price = (token_unit / expected_rate) if expected_rate else 0 if price <= 0.0: error_message = ( f"price={price} <= 0 from kyber-network-proxy={self.kyber_network_proxy_address} " f"for token-1={token_address_1} to token-2={token_address_2}" ) logger.warning(error_message) raise InvalidPriceFromOracle(error_message) return price except (ValueError, BadFunctionCallOutput, DecodingError) as e: error_message = ( f"Cannot get price from kyber-network-proxy={self.kyber_network_proxy_address} " f"for token-1={token_address_1} to token-2={token_address_2}" ) logger.warning(error_message) raise CannotGetPriceFromOracle(error_message) from e
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/oracles/kyber.py
0.880271
0.155015
kyber.py
pypi
mooniswap_abi = [ { "inputs": [ {"internalType": "contract IERC20", "name": "_token0", "type": "address"}, {"internalType": "contract IERC20", "name": "_token1", "type": "address"}, {"internalType": "string", "name": "name", "type": "string"}, {"internalType": "string", "name": "symbol", "type": "string"}, { "internalType": "contract IMooniswapFactoryGovernance", "name": "_mooniswapFactoryGovernance", "type": "address", }, ], "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": True, "internalType": "address", "name": "spender", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "user", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "decayPeriod", "type": "uint256", }, { "indexed": False, "internalType": "bool", "name": "isDefault", "type": "bool", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, ], "name": "DecayPeriodVoteUpdate", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "receiver", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "share", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "token0Amount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "token1Amount", "type": "uint256", }, ], "name": "Deposited", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "string", "name": "reason", "type": "string", } ], "name": "Error", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "user", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "fee", "type": "uint256", }, { "indexed": False, "internalType": "bool", "name": "isDefault", "type": "bool", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, ], "name": "FeeVoteUpdate", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "previousOwner", "type": "address", }, { "indexed": True, "internalType": "address", "name": "newOwner", "type": "address", }, ], "name": "OwnershipTransferred", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "user", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "slippageFee", "type": "uint256", }, { "indexed": False, "internalType": "bool", "name": "isDefault", "type": "bool", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, ], "name": "SlippageFeeVoteUpdate", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "receiver", "type": "address", }, { "indexed": True, "internalType": "address", "name": "srcToken", "type": "address", }, { "indexed": False, "internalType": "address", "name": "dstToken", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "result", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "srcAdditionBalance", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "dstRemovalBalance", "type": "uint256", }, { "indexed": False, "internalType": "address", "name": "referral", "type": "address", }, ], "name": "Swapped", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint256", "name": "srcBalance", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "dstBalance", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "fee", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "slippageFee", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "referralShare", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "governanceShare", "type": "uint256", }, ], "name": "Sync", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "to", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "receiver", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "share", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "token0Amount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "token1Amount", "type": "uint256", }, ], "name": "Withdrawn", "type": "event", }, { "inputs": [ {"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}, ], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "decayPeriod", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "uint256", "name": "vote", "type": "uint256"}], "name": "decayPeriodVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "decayPeriodVotes", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "decimals", "outputs": [{"internalType": "uint8", "name": "", "type": "uint8"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "subtractedValue", "type": "uint256"}, ], "name": "decreaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint256[2]", "name": "maxAmounts", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "minAmounts", "type": "uint256[2]"}, ], "name": "deposit", "outputs": [ {"internalType": "uint256", "name": "fairSupply", "type": "uint256"}, { "internalType": "uint256[2]", "name": "receivedAmounts", "type": "uint256[2]", }, ], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "uint256[2]", "name": "maxAmounts", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "minAmounts", "type": "uint256[2]"}, {"internalType": "address", "name": "target", "type": "address"}, ], "name": "depositFor", "outputs": [ {"internalType": "uint256", "name": "fairSupply", "type": "uint256"}, { "internalType": "uint256[2]", "name": "receivedAmounts", "type": "uint256[2]", }, ], "stateMutability": "payable", "type": "function", }, { "inputs": [], "name": "discardDecayPeriodVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "discardFeeVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "discardSlippageFeeVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "fee", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "uint256", "name": "vote", "type": "uint256"}], "name": "feeVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "feeVotes", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "token", "type": "address"} ], "name": "getBalanceForAddition", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "token", "type": "address"} ], "name": "getBalanceForRemoval", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "src", "type": "address"}, {"internalType": "contract IERC20", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "getReturn", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "getTokens", "outputs": [ {"internalType": "contract IERC20[]", "name": "tokens", "type": "address[]"} ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "addedValue", "type": "uint256"}, ], "name": "increaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "mooniswapFactoryGovernance", "outputs": [ { "internalType": "contract IMooniswapFactoryGovernance", "name": "", "type": "address", } ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "name", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "owner", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "rescueFunds", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "contract IMooniswapFactoryGovernance", "name": "newMooniswapFactoryGovernance", "type": "address", } ], "name": "setMooniswapFactoryGovernance", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "slippageFee", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "uint256", "name": "vote", "type": "uint256"}], "name": "slippageFeeVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "slippageFeeVotes", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "src", "type": "address"}, {"internalType": "contract IERC20", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256", "name": "minReturn", "type": "uint256"}, {"internalType": "address", "name": "referral", "type": "address"}, ], "name": "swap", "outputs": [{"internalType": "uint256", "name": "result", "type": "uint256"}], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "src", "type": "address"}, {"internalType": "contract IERC20", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256", "name": "minReturn", "type": "uint256"}, {"internalType": "address", "name": "referral", "type": "address"}, {"internalType": "address payable", "name": "receiver", "type": "address"}, ], "name": "swapFor", "outputs": [{"internalType": "uint256", "name": "result", "type": "uint256"}], "stateMutability": "payable", "type": "function", }, { "inputs": [], "name": "symbol", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "token0", "outputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "token1", "outputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "uint256", "name": "i", "type": "uint256"}], "name": "tokens", "outputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "sender", "type": "address"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "newOwner", "type": "address"}], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "name": "virtualBalancesForAddition", "outputs": [ {"internalType": "uint216", "name": "balance", "type": "uint216"}, {"internalType": "uint40", "name": "time", "type": "uint40"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "name": "virtualBalancesForRemoval", "outputs": [ {"internalType": "uint216", "name": "balance", "type": "uint216"}, {"internalType": "uint40", "name": "time", "type": "uint40"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "virtualDecayPeriod", "outputs": [ {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint48", "name": "", "type": "uint48"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "virtualFee", "outputs": [ {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint48", "name": "", "type": "uint48"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "virtualSlippageFee", "outputs": [ {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint48", "name": "", "type": "uint48"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "name": "volumes", "outputs": [ {"internalType": "uint128", "name": "confirmed", "type": "uint128"}, {"internalType": "uint128", "name": "result", "type": "uint128"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256[]", "name": "minReturns", "type": "uint256[]"}, ], "name": "withdraw", "outputs": [ { "internalType": "uint256[2]", "name": "withdrawnAmounts", "type": "uint256[2]", } ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256[]", "name": "minReturns", "type": "uint256[]"}, {"internalType": "address payable", "name": "target", "type": "address"}, ], "name": "withdrawFor", "outputs": [ { "internalType": "uint256[2]", "name": "withdrawnAmounts", "type": "uint256[2]", } ], "stateMutability": "nonpayable", "type": "function", }, ]
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/oracles/abis/mooniswap_abis.py
0.535098
0.515315
mooniswap_abis.py
pypi
uniswap_v3_factory_abi = [ {"inputs": [], "stateMutability": "nonpayable", "type": "constructor"}, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "uint24", "name": "fee", "type": "uint24", }, { "indexed": True, "internalType": "int24", "name": "tickSpacing", "type": "int24", }, ], "name": "FeeAmountEnabled", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "oldOwner", "type": "address", }, { "indexed": True, "internalType": "address", "name": "newOwner", "type": "address", }, ], "name": "OwnerChanged", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "token0", "type": "address", }, { "indexed": True, "internalType": "address", "name": "token1", "type": "address", }, { "indexed": True, "internalType": "uint24", "name": "fee", "type": "uint24", }, { "indexed": False, "internalType": "int24", "name": "tickSpacing", "type": "int24", }, { "indexed": False, "internalType": "address", "name": "pool", "type": "address", }, ], "name": "PoolCreated", "type": "event", }, { "inputs": [ {"internalType": "address", "name": "tokenA", "type": "address"}, {"internalType": "address", "name": "tokenB", "type": "address"}, {"internalType": "uint24", "name": "fee", "type": "uint24"}, ], "name": "createPool", "outputs": [{"internalType": "address", "name": "pool", "type": "address"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint24", "name": "fee", "type": "uint24"}, {"internalType": "int24", "name": "tickSpacing", "type": "int24"}, ], "name": "enableFeeAmount", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "uint24", "name": "", "type": "uint24"}], "name": "feeAmountTickSpacing", "outputs": [{"internalType": "int24", "name": "", "type": "int24"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "", "type": "address"}, {"internalType": "address", "name": "", "type": "address"}, {"internalType": "uint24", "name": "", "type": "uint24"}, ], "name": "getPool", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "owner", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "parameters", "outputs": [ {"internalType": "address", "name": "factory", "type": "address"}, {"internalType": "address", "name": "token0", "type": "address"}, {"internalType": "address", "name": "token1", "type": "address"}, {"internalType": "uint24", "name": "fee", "type": "uint24"}, {"internalType": "int24", "name": "tickSpacing", "type": "int24"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "address", "name": "_owner", "type": "address"}], "name": "setOwner", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ] uniswap_v3_router_abi = [ { "inputs": [ {"internalType": "address", "name": "_factoryV2", "type": "address"}, {"internalType": "address", "name": "factoryV3", "type": "address"}, {"internalType": "address", "name": "_positionManager", "type": "address"}, {"internalType": "address", "name": "_WETH9", "type": "address"}, ], "stateMutability": "nonpayable", "type": "constructor", }, { "inputs": [], "name": "WETH9", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "approveMax", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "approveMaxMinusOne", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "approveZeroThenMax", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "approveZeroThenMaxMinusOne", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [{"internalType": "bytes", "name": "data", "type": "bytes"}], "name": "callPositionManager", "outputs": [{"internalType": "bytes", "name": "result", "type": "bytes"}], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "bytes[]", "name": "paths", "type": "bytes[]"}, {"internalType": "uint128[]", "name": "amounts", "type": "uint128[]"}, { "internalType": "uint24", "name": "maximumTickDivergence", "type": "uint24", }, {"internalType": "uint32", "name": "secondsAgo", "type": "uint32"}, ], "name": "checkOracleSlippage", "outputs": [], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "bytes", "name": "path", "type": "bytes"}, { "internalType": "uint24", "name": "maximumTickDivergence", "type": "uint24", }, {"internalType": "uint32", "name": "secondsAgo", "type": "uint32"}, ], "name": "checkOracleSlippage", "outputs": [], "stateMutability": "view", "type": "function", }, { "inputs": [ { "components": [ {"internalType": "bytes", "name": "path", "type": "bytes"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amountIn", "type": "uint256"}, { "internalType": "uint256", "name": "amountOutMinimum", "type": "uint256", }, ], "internalType": "struct IV3SwapRouter.ExactInputParams", "name": "params", "type": "tuple", } ], "name": "exactInput", "outputs": [ {"internalType": "uint256", "name": "amountOut", "type": "uint256"} ], "stateMutability": "payable", "type": "function", }, { "inputs": [ { "components": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "address", "name": "tokenOut", "type": "address"}, {"internalType": "uint24", "name": "fee", "type": "uint24"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amountIn", "type": "uint256"}, { "internalType": "uint256", "name": "amountOutMinimum", "type": "uint256", }, { "internalType": "uint160", "name": "sqrtPriceLimitX96", "type": "uint160", }, ], "internalType": "struct IV3SwapRouter.ExactInputSingleParams", "name": "params", "type": "tuple", } ], "name": "exactInputSingle", "outputs": [ {"internalType": "uint256", "name": "amountOut", "type": "uint256"} ], "stateMutability": "payable", "type": "function", }, { "inputs": [ { "components": [ {"internalType": "bytes", "name": "path", "type": "bytes"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amountOut", "type": "uint256"}, { "internalType": "uint256", "name": "amountInMaximum", "type": "uint256", }, ], "internalType": "struct IV3SwapRouter.ExactOutputParams", "name": "params", "type": "tuple", } ], "name": "exactOutput", "outputs": [{"internalType": "uint256", "name": "amountIn", "type": "uint256"}], "stateMutability": "payable", "type": "function", }, { "inputs": [ { "components": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "address", "name": "tokenOut", "type": "address"}, {"internalType": "uint24", "name": "fee", "type": "uint24"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amountOut", "type": "uint256"}, { "internalType": "uint256", "name": "amountInMaximum", "type": "uint256", }, { "internalType": "uint160", "name": "sqrtPriceLimitX96", "type": "uint160", }, ], "internalType": "struct IV3SwapRouter.ExactOutputSingleParams", "name": "params", "type": "tuple", } ], "name": "exactOutputSingle", "outputs": [{"internalType": "uint256", "name": "amountIn", "type": "uint256"}], "stateMutability": "payable", "type": "function", }, { "inputs": [], "name": "factory", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "factoryV2", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "getApprovalType", "outputs": [ { "internalType": "enum IApproveAndCall.ApprovalType", "name": "", "type": "uint8", } ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "components": [ {"internalType": "address", "name": "token0", "type": "address"}, {"internalType": "address", "name": "token1", "type": "address"}, {"internalType": "uint256", "name": "tokenId", "type": "uint256"}, { "internalType": "uint256", "name": "amount0Min", "type": "uint256", }, { "internalType": "uint256", "name": "amount1Min", "type": "uint256", }, ], "internalType": "struct IApproveAndCall.IncreaseLiquidityParams", "name": "params", "type": "tuple", } ], "name": "increaseLiquidity", "outputs": [{"internalType": "bytes", "name": "result", "type": "bytes"}], "stateMutability": "payable", "type": "function", }, { "inputs": [ { "components": [ {"internalType": "address", "name": "token0", "type": "address"}, {"internalType": "address", "name": "token1", "type": "address"}, {"internalType": "uint24", "name": "fee", "type": "uint24"}, {"internalType": "int24", "name": "tickLower", "type": "int24"}, {"internalType": "int24", "name": "tickUpper", "type": "int24"}, { "internalType": "uint256", "name": "amount0Min", "type": "uint256", }, { "internalType": "uint256", "name": "amount1Min", "type": "uint256", }, {"internalType": "address", "name": "recipient", "type": "address"}, ], "internalType": "struct IApproveAndCall.MintParams", "name": "params", "type": "tuple", } ], "name": "mint", "outputs": [{"internalType": "bytes", "name": "result", "type": "bytes"}], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "bytes32", "name": "previousBlockhash", "type": "bytes32"}, {"internalType": "bytes[]", "name": "data", "type": "bytes[]"}, ], "name": "multicall", "outputs": [{"internalType": "bytes[]", "name": "", "type": "bytes[]"}], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "deadline", "type": "uint256"}, {"internalType": "bytes[]", "name": "data", "type": "bytes[]"}, ], "name": "multicall", "outputs": [{"internalType": "bytes[]", "name": "", "type": "bytes[]"}], "stateMutability": "payable", "type": "function", }, { "inputs": [{"internalType": "bytes[]", "name": "data", "type": "bytes[]"}], "name": "multicall", "outputs": [{"internalType": "bytes[]", "name": "results", "type": "bytes[]"}], "stateMutability": "payable", "type": "function", }, { "inputs": [], "name": "positionManager", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}, ], "name": "pull", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [], "name": "refundETH", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}, {"internalType": "uint256", "name": "deadline", "type": "uint256"}, {"internalType": "uint8", "name": "v", "type": "uint8"}, {"internalType": "bytes32", "name": "r", "type": "bytes32"}, {"internalType": "bytes32", "name": "s", "type": "bytes32"}, ], "name": "selfPermit", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "nonce", "type": "uint256"}, {"internalType": "uint256", "name": "expiry", "type": "uint256"}, {"internalType": "uint8", "name": "v", "type": "uint8"}, {"internalType": "bytes32", "name": "r", "type": "bytes32"}, {"internalType": "bytes32", "name": "s", "type": "bytes32"}, ], "name": "selfPermitAllowed", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "nonce", "type": "uint256"}, {"internalType": "uint256", "name": "expiry", "type": "uint256"}, {"internalType": "uint8", "name": "v", "type": "uint8"}, {"internalType": "bytes32", "name": "r", "type": "bytes32"}, {"internalType": "bytes32", "name": "s", "type": "bytes32"}, ], "name": "selfPermitAllowedIfNecessary", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}, {"internalType": "uint256", "name": "deadline", "type": "uint256"}, {"internalType": "uint8", "name": "v", "type": "uint8"}, {"internalType": "bytes32", "name": "r", "type": "bytes32"}, {"internalType": "bytes32", "name": "s", "type": "bytes32"}, ], "name": "selfPermitIfNecessary", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amountIn", "type": "uint256"}, {"internalType": "uint256", "name": "amountOutMin", "type": "uint256"}, {"internalType": "address[]", "name": "path", "type": "address[]"}, {"internalType": "address", "name": "to", "type": "address"}, ], "name": "swapExactTokensForTokens", "outputs": [ {"internalType": "uint256", "name": "amountOut", "type": "uint256"} ], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amountOut", "type": "uint256"}, {"internalType": "uint256", "name": "amountInMax", "type": "uint256"}, {"internalType": "address[]", "name": "path", "type": "address[]"}, {"internalType": "address", "name": "to", "type": "address"}, ], "name": "swapTokensForExactTokens", "outputs": [{"internalType": "uint256", "name": "amountIn", "type": "uint256"}], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "amountMinimum", "type": "uint256"}, {"internalType": "address", "name": "recipient", "type": "address"}, ], "name": "sweepToken", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "amountMinimum", "type": "uint256"}, ], "name": "sweepToken", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "amountMinimum", "type": "uint256"}, {"internalType": "uint256", "name": "feeBips", "type": "uint256"}, {"internalType": "address", "name": "feeRecipient", "type": "address"}, ], "name": "sweepTokenWithFee", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "amountMinimum", "type": "uint256"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "feeBips", "type": "uint256"}, {"internalType": "address", "name": "feeRecipient", "type": "address"}, ], "name": "sweepTokenWithFee", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "int256", "name": "amount0Delta", "type": "int256"}, {"internalType": "int256", "name": "amount1Delta", "type": "int256"}, {"internalType": "bytes", "name": "_data", "type": "bytes"}, ], "name": "uniswapV3SwapCallback", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amountMinimum", "type": "uint256"}, {"internalType": "address", "name": "recipient", "type": "address"}, ], "name": "unwrapWETH9", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amountMinimum", "type": "uint256"} ], "name": "unwrapWETH9", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amountMinimum", "type": "uint256"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "feeBips", "type": "uint256"}, {"internalType": "address", "name": "feeRecipient", "type": "address"}, ], "name": "unwrapWETH9WithFee", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amountMinimum", "type": "uint256"}, {"internalType": "uint256", "name": "feeBips", "type": "uint256"}, {"internalType": "address", "name": "feeRecipient", "type": "address"}, ], "name": "unwrapWETH9WithFee", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [{"internalType": "uint256", "name": "value", "type": "uint256"}], "name": "wrapETH", "outputs": [], "stateMutability": "payable", "type": "function", }, {"stateMutability": "payable", "type": "receive"}, ] uniswap_v3_pool_abi = [ {"inputs": [], "stateMutability": "nonpayable", "type": "constructor"}, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": True, "internalType": "int24", "name": "tickLower", "type": "int24", }, { "indexed": True, "internalType": "int24", "name": "tickUpper", "type": "int24", }, { "indexed": False, "internalType": "uint128", "name": "amount", "type": "uint128", }, { "indexed": False, "internalType": "uint256", "name": "amount0", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "amount1", "type": "uint256", }, ], "name": "Burn", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": False, "internalType": "address", "name": "recipient", "type": "address", }, { "indexed": True, "internalType": "int24", "name": "tickLower", "type": "int24", }, { "indexed": True, "internalType": "int24", "name": "tickUpper", "type": "int24", }, { "indexed": False, "internalType": "uint128", "name": "amount0", "type": "uint128", }, { "indexed": False, "internalType": "uint128", "name": "amount1", "type": "uint128", }, ], "name": "Collect", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "recipient", "type": "address", }, { "indexed": False, "internalType": "uint128", "name": "amount0", "type": "uint128", }, { "indexed": False, "internalType": "uint128", "name": "amount1", "type": "uint128", }, ], "name": "CollectProtocol", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "recipient", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amount0", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "amount1", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "paid0", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "paid1", "type": "uint256", }, ], "name": "Flash", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint16", "name": "observationCardinalityNextOld", "type": "uint16", }, { "indexed": False, "internalType": "uint16", "name": "observationCardinalityNextNew", "type": "uint16", }, ], "name": "IncreaseObservationCardinalityNext", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint160", "name": "sqrtPriceX96", "type": "uint160", }, { "indexed": False, "internalType": "int24", "name": "tick", "type": "int24", }, ], "name": "Initialize", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": True, "internalType": "int24", "name": "tickLower", "type": "int24", }, { "indexed": True, "internalType": "int24", "name": "tickUpper", "type": "int24", }, { "indexed": False, "internalType": "uint128", "name": "amount", "type": "uint128", }, { "indexed": False, "internalType": "uint256", "name": "amount0", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "amount1", "type": "uint256", }, ], "name": "Mint", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint8", "name": "feeProtocol0Old", "type": "uint8", }, { "indexed": False, "internalType": "uint8", "name": "feeProtocol1Old", "type": "uint8", }, { "indexed": False, "internalType": "uint8", "name": "feeProtocol0New", "type": "uint8", }, { "indexed": False, "internalType": "uint8", "name": "feeProtocol1New", "type": "uint8", }, ], "name": "SetFeeProtocol", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "recipient", "type": "address", }, { "indexed": False, "internalType": "int256", "name": "amount0", "type": "int256", }, { "indexed": False, "internalType": "int256", "name": "amount1", "type": "int256", }, { "indexed": False, "internalType": "uint160", "name": "sqrtPriceX96", "type": "uint160", }, { "indexed": False, "internalType": "uint128", "name": "liquidity", "type": "uint128", }, { "indexed": False, "internalType": "int24", "name": "tick", "type": "int24", }, ], "name": "Swap", "type": "event", }, { "inputs": [ {"internalType": "int24", "name": "tickLower", "type": "int24"}, {"internalType": "int24", "name": "tickUpper", "type": "int24"}, {"internalType": "uint128", "name": "amount", "type": "uint128"}, ], "name": "burn", "outputs": [ {"internalType": "uint256", "name": "amount0", "type": "uint256"}, {"internalType": "uint256", "name": "amount1", "type": "uint256"}, ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "int24", "name": "tickLower", "type": "int24"}, {"internalType": "int24", "name": "tickUpper", "type": "int24"}, {"internalType": "uint128", "name": "amount0Requested", "type": "uint128"}, {"internalType": "uint128", "name": "amount1Requested", "type": "uint128"}, ], "name": "collect", "outputs": [ {"internalType": "uint128", "name": "amount0", "type": "uint128"}, {"internalType": "uint128", "name": "amount1", "type": "uint128"}, ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint128", "name": "amount0Requested", "type": "uint128"}, {"internalType": "uint128", "name": "amount1Requested", "type": "uint128"}, ], "name": "collectProtocol", "outputs": [ {"internalType": "uint128", "name": "amount0", "type": "uint128"}, {"internalType": "uint128", "name": "amount1", "type": "uint128"}, ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "factory", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "fee", "outputs": [{"internalType": "uint24", "name": "", "type": "uint24"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "feeGrowthGlobal0X128", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "feeGrowthGlobal1X128", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount0", "type": "uint256"}, {"internalType": "uint256", "name": "amount1", "type": "uint256"}, {"internalType": "bytes", "name": "data", "type": "bytes"}, ], "name": "flash", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "uint16", "name": "observationCardinalityNext", "type": "uint16", } ], "name": "increaseObservationCardinalityNext", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint160", "name": "sqrtPriceX96", "type": "uint160"} ], "name": "initialize", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "liquidity", "outputs": [{"internalType": "uint128", "name": "", "type": "uint128"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "maxLiquidityPerTick", "outputs": [{"internalType": "uint128", "name": "", "type": "uint128"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "int24", "name": "tickLower", "type": "int24"}, {"internalType": "int24", "name": "tickUpper", "type": "int24"}, {"internalType": "uint128", "name": "amount", "type": "uint128"}, {"internalType": "bytes", "name": "data", "type": "bytes"}, ], "name": "mint", "outputs": [ {"internalType": "uint256", "name": "amount0", "type": "uint256"}, {"internalType": "uint256", "name": "amount1", "type": "uint256"}, ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "name": "observations", "outputs": [ {"internalType": "uint32", "name": "blockTimestamp", "type": "uint32"}, {"internalType": "int56", "name": "tickCumulative", "type": "int56"}, { "internalType": "uint160", "name": "secondsPerLiquidityCumulativeX128", "type": "uint160", }, {"internalType": "bool", "name": "initialized", "type": "bool"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "uint32[]", "name": "secondsAgos", "type": "uint32[]"} ], "name": "observe", "outputs": [ {"internalType": "int56[]", "name": "tickCumulatives", "type": "int56[]"}, { "internalType": "uint160[]", "name": "secondsPerLiquidityCumulativeX128s", "type": "uint160[]", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "bytes32", "name": "", "type": "bytes32"}], "name": "positions", "outputs": [ {"internalType": "uint128", "name": "liquidity", "type": "uint128"}, { "internalType": "uint256", "name": "feeGrowthInside0LastX128", "type": "uint256", }, { "internalType": "uint256", "name": "feeGrowthInside1LastX128", "type": "uint256", }, {"internalType": "uint128", "name": "tokensOwed0", "type": "uint128"}, {"internalType": "uint128", "name": "tokensOwed1", "type": "uint128"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "protocolFees", "outputs": [ {"internalType": "uint128", "name": "token0", "type": "uint128"}, {"internalType": "uint128", "name": "token1", "type": "uint128"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "uint8", "name": "feeProtocol0", "type": "uint8"}, {"internalType": "uint8", "name": "feeProtocol1", "type": "uint8"}, ], "name": "setFeeProtocol", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "slot0", "outputs": [ {"internalType": "uint160", "name": "sqrtPriceX96", "type": "uint160"}, {"internalType": "int24", "name": "tick", "type": "int24"}, {"internalType": "uint16", "name": "observationIndex", "type": "uint16"}, { "internalType": "uint16", "name": "observationCardinality", "type": "uint16", }, { "internalType": "uint16", "name": "observationCardinalityNext", "type": "uint16", }, {"internalType": "uint8", "name": "feeProtocol", "type": "uint8"}, {"internalType": "bool", "name": "unlocked", "type": "bool"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "int24", "name": "tickLower", "type": "int24"}, {"internalType": "int24", "name": "tickUpper", "type": "int24"}, ], "name": "snapshotCumulativesInside", "outputs": [ {"internalType": "int56", "name": "tickCumulativeInside", "type": "int56"}, { "internalType": "uint160", "name": "secondsPerLiquidityInsideX128", "type": "uint160", }, {"internalType": "uint32", "name": "secondsInside", "type": "uint32"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "bool", "name": "zeroForOne", "type": "bool"}, {"internalType": "int256", "name": "amountSpecified", "type": "int256"}, {"internalType": "uint160", "name": "sqrtPriceLimitX96", "type": "uint160"}, {"internalType": "bytes", "name": "data", "type": "bytes"}, ], "name": "swap", "outputs": [ {"internalType": "int256", "name": "amount0", "type": "int256"}, {"internalType": "int256", "name": "amount1", "type": "int256"}, ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "int16", "name": "", "type": "int16"}], "name": "tickBitmap", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "tickSpacing", "outputs": [{"internalType": "int24", "name": "", "type": "int24"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "int24", "name": "", "type": "int24"}], "name": "ticks", "outputs": [ {"internalType": "uint128", "name": "liquidityGross", "type": "uint128"}, {"internalType": "int128", "name": "liquidityNet", "type": "int128"}, { "internalType": "uint256", "name": "feeGrowthOutside0X128", "type": "uint256", }, { "internalType": "uint256", "name": "feeGrowthOutside1X128", "type": "uint256", }, {"internalType": "int56", "name": "tickCumulativeOutside", "type": "int56"}, { "internalType": "uint160", "name": "secondsPerLiquidityOutsideX128", "type": "uint160", }, {"internalType": "uint32", "name": "secondsOutside", "type": "uint32"}, {"internalType": "bool", "name": "initialized", "type": "bool"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "token0", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "token1", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, ]
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/oracles/abis/uniswap_v3.py
0.515864
0.476275
uniswap_v3.py
pypi
AAVE_ATOKEN_ABI = [ { "inputs": [ { "internalType": "contract ILendingPool", "name": "pool", "type": "address", }, { "internalType": "address", "name": "underlyingAssetAddress", "type": "address", }, { "internalType": "address", "name": "reserveTreasuryAddress", "type": "address", }, {"internalType": "string", "name": "tokenName", "type": "string"}, {"internalType": "string", "name": "tokenSymbol", "type": "string"}, { "internalType": "address", "name": "incentivesController", "type": "address", }, ], "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": True, "internalType": "address", "name": "spender", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "to", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "index", "type": "uint256", }, ], "name": "BalanceTransfer", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "target", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "index", "type": "uint256", }, ], "name": "Burn", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "underlyingAsset", "type": "address", }, { "indexed": True, "internalType": "address", "name": "pool", "type": "address", }, { "indexed": False, "internalType": "address", "name": "treasury", "type": "address", }, { "indexed": False, "internalType": "address", "name": "incentivesController", "type": "address", }, { "indexed": False, "internalType": "uint8", "name": "aTokenDecimals", "type": "uint8", }, { "indexed": False, "internalType": "string", "name": "aTokenName", "type": "string", }, { "indexed": False, "internalType": "string", "name": "aTokenSymbol", "type": "string", }, { "indexed": False, "internalType": "bytes", "name": "params", "type": "bytes", }, ], "name": "Initialized", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "index", "type": "uint256", }, ], "name": "Mint", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "to", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "inputs": [], "name": "ATOKEN_REVISION", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "DOMAIN_SEPARATOR", "outputs": [{"internalType": "bytes32", "name": "", "type": "bytes32"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "EIP712_REVISION", "outputs": [{"internalType": "bytes", "name": "", "type": "bytes"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "PERMIT_TYPEHASH", "outputs": [{"internalType": "bytes32", "name": "", "type": "bytes32"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "POOL", "outputs": [ {"internalType": "contract ILendingPool", "name": "", "type": "address"} ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "RESERVE_TREASURY_ADDRESS", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "UINT_MAX_VALUE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "UNDERLYING_ASSET_ADDRESS", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "address", "name": "", "type": "address"}], "name": "_nonces", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}, ], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "user", "type": "address"}, { "internalType": "address", "name": "receiverOfUnderlying", "type": "address", }, {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256", "name": "index", "type": "uint256"}, ], "name": "burn", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "decimals", "outputs": [{"internalType": "uint8", "name": "", "type": "uint8"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "subtractedValue", "type": "uint256"}, ], "name": "decreaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "getIncentivesController", "outputs": [ { "internalType": "contract IAaveIncentivesController", "name": "", "type": "address", } ], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "getScaledUserBalanceAndSupply", "outputs": [ {"internalType": "uint256", "name": "", "type": "uint256"}, {"internalType": "uint256", "name": "", "type": "uint256"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "addedValue", "type": "uint256"}, ], "name": "increaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "uint8", "name": "underlyingAssetDecimals", "type": "uint8", }, {"internalType": "string", "name": "tokenName", "type": "string"}, {"internalType": "string", "name": "tokenSymbol", "type": "string"}, ], "name": "initialize", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "user", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256", "name": "index", "type": "uint256"}, ], "name": "mint", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256", "name": "index", "type": "uint256"}, ], "name": "mintToTreasury", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "name", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}, {"internalType": "uint256", "name": "deadline", "type": "uint256"}, {"internalType": "uint8", "name": "v", "type": "uint8"}, {"internalType": "bytes32", "name": "r", "type": "bytes32"}, {"internalType": "bytes32", "name": "s", "type": "bytes32"}, ], "name": "permit", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "scaledBalanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "scaledTotalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "symbol", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "sender", "type": "address"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "from", "type": "address"}, {"internalType": "address", "name": "to", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}, ], "name": "transferOnLiquidation", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "target", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transferUnderlyingTo", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "nonpayable", "type": "function", }, ]
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/oracles/abis/aave_abis.py
0.566019
0.415847
aave_abis.py
pypi
curve_address_provider_abi = [ { "name": "NewAddressIdentifier", "inputs": [ {"type": "uint256", "name": "id", "indexed": True}, {"type": "address", "name": "addr", "indexed": False}, {"type": "string", "name": "description", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "AddressModified", "inputs": [ {"type": "uint256", "name": "id", "indexed": True}, {"type": "address", "name": "new_address", "indexed": False}, {"type": "uint256", "name": "version", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "CommitNewAdmin", "inputs": [ {"type": "uint256", "name": "deadline", "indexed": True}, {"type": "address", "name": "admin", "indexed": True}, ], "anonymous": False, "type": "event", }, { "name": "NewAdmin", "inputs": [{"type": "address", "name": "admin", "indexed": True}], "anonymous": False, "type": "event", }, { "outputs": [], "inputs": [{"type": "address", "name": "_admin"}], "stateMutability": "nonpayable", "type": "constructor", }, { "name": "get_registry", "outputs": [{"type": "address", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 1061, }, { "name": "max_id", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 1258, }, { "name": "get_address", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "uint256", "name": "_id"}], "stateMutability": "view", "type": "function", "gas": 1308, }, { "name": "add_new_id", "outputs": [{"type": "uint256", "name": ""}], "inputs": [ {"type": "address", "name": "_address"}, {"type": "string", "name": "_description"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 291275, }, { "name": "set_address", "outputs": [{"type": "bool", "name": ""}], "inputs": [ {"type": "uint256", "name": "_id"}, {"type": "address", "name": "_address"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 182430, }, { "name": "unset_address", "outputs": [{"type": "bool", "name": ""}], "inputs": [{"type": "uint256", "name": "_id"}], "stateMutability": "nonpayable", "type": "function", "gas": 101348, }, { "name": "commit_transfer_ownership", "outputs": [{"type": "bool", "name": ""}], "inputs": [{"type": "address", "name": "_new_admin"}], "stateMutability": "nonpayable", "type": "function", "gas": 74048, }, { "name": "apply_transfer_ownership", "outputs": [{"type": "bool", "name": ""}], "inputs": [], "stateMutability": "nonpayable", "type": "function", "gas": 60125, }, { "name": "revert_transfer_ownership", "outputs": [{"type": "bool", "name": ""}], "inputs": [], "stateMutability": "nonpayable", "type": "function", "gas": 21400, }, { "name": "admin", "outputs": [{"type": "address", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 1331, }, { "name": "transfer_ownership_deadline", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 1361, }, { "name": "future_admin", "outputs": [{"type": "address", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 1391, }, { "name": "get_id_info", "outputs": [ {"type": "address", "name": "addr"}, {"type": "bool", "name": "is_active"}, {"type": "uint256", "name": "version"}, {"type": "uint256", "name": "last_modified"}, {"type": "string", "name": "description"}, ], "inputs": [{"type": "uint256", "name": "arg0"}], "stateMutability": "view", "type": "function", "gas": 12168, }, ] curve_registry_abi = [ { "name": "PoolAdded", "inputs": [ {"type": "address", "name": "pool", "indexed": True}, {"type": "bytes", "name": "rate_method_id", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "PoolRemoved", "inputs": [{"type": "address", "name": "pool", "indexed": True}], "anonymous": False, "type": "event", }, { "outputs": [], "inputs": [ {"type": "address", "name": "_address_provider"}, {"type": "address", "name": "_gauge_controller"}, ], "stateMutability": "nonpayable", "type": "constructor", }, { "name": "find_pool_for_coins", "outputs": [{"type": "address", "name": ""}], "inputs": [ {"type": "address", "name": "_from"}, {"type": "address", "name": "_to"}, ], "stateMutability": "view", "type": "function", }, { "name": "find_pool_for_coins", "outputs": [{"type": "address", "name": ""}], "inputs": [ {"type": "address", "name": "_from"}, {"type": "address", "name": "_to"}, {"type": "uint256", "name": "i"}, ], "stateMutability": "view", "type": "function", }, { "name": "get_n_coins", "outputs": [{"type": "uint256[2]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 1704, }, { "name": "get_coins", "outputs": [{"type": "address[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 12285, }, { "name": "get_underlying_coins", "outputs": [{"type": "address[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 12347, }, { "name": "get_decimals", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 8199, }, { "name": "get_underlying_decimals", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 8261, }, { "name": "get_rates", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 34780, }, { "name": "get_gauges", "outputs": [ {"type": "address[10]", "name": ""}, {"type": "int128[10]", "name": ""}, ], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 20310, }, { "name": "get_balances", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 16818, }, { "name": "get_underlying_balances", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 158953, }, { "name": "get_virtual_price_from_lp_token", "outputs": [{"type": "uint256", "name": ""}], "inputs": [{"type": "address", "name": "_token"}], "stateMutability": "view", "type": "function", "gas": 2080, }, { "name": "get_A", "outputs": [{"type": "uint256", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 1198, }, { "name": "get_parameters", "outputs": [ {"type": "uint256", "name": "A"}, {"type": "uint256", "name": "future_A"}, {"type": "uint256", "name": "fee"}, {"type": "uint256", "name": "admin_fee"}, {"type": "uint256", "name": "future_fee"}, {"type": "uint256", "name": "future_admin_fee"}, {"type": "address", "name": "future_owner"}, {"type": "uint256", "name": "initial_A"}, {"type": "uint256", "name": "initial_A_time"}, {"type": "uint256", "name": "future_A_time"}, ], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 6458, }, { "name": "get_fees", "outputs": [{"type": "uint256[2]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 1603, }, { "name": "get_admin_balances", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 36719, }, { "name": "get_coin_indices", "outputs": [ {"type": "int128", "name": ""}, {"type": "int128", "name": ""}, {"type": "bool", "name": ""}, ], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "address", "name": "_from"}, {"type": "address", "name": "_to"}, ], "stateMutability": "view", "type": "function", "gas": 27456, }, { "name": "estimate_gas_used", "outputs": [{"type": "uint256", "name": ""}], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "address", "name": "_from"}, {"type": "address", "name": "_to"}, ], "stateMutability": "view", "type": "function", "gas": 32329, }, { "name": "add_pool", "outputs": [], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "uint256", "name": "_n_coins"}, {"type": "address", "name": "_lp_token"}, {"type": "bytes32", "name": "_rate_method_id"}, {"type": "uint256", "name": "_decimals"}, {"type": "uint256", "name": "_underlying_decimals"}, {"type": "bool", "name": "_has_initial_A"}, {"type": "bool", "name": "_is_v1"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 10196577, }, { "name": "add_pool_without_underlying", "outputs": [], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "uint256", "name": "_n_coins"}, {"type": "address", "name": "_lp_token"}, {"type": "bytes32", "name": "_rate_method_id"}, {"type": "uint256", "name": "_decimals"}, {"type": "uint256", "name": "_use_rates"}, {"type": "bool", "name": "_has_initial_A"}, {"type": "bool", "name": "_is_v1"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 5590664, }, { "name": "add_metapool", "outputs": [], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "uint256", "name": "_n_coins"}, {"type": "address", "name": "_lp_token"}, {"type": "uint256", "name": "_decimals"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 10226976, }, { "name": "remove_pool", "outputs": [], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "nonpayable", "type": "function", "gas": 779646579509, }, { "name": "set_pool_gas_estimates", "outputs": [], "inputs": [ {"type": "address[5]", "name": "_addr"}, {"type": "uint256[2][5]", "name": "_amount"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 355578, }, { "name": "set_coin_gas_estimates", "outputs": [], "inputs": [ {"type": "address[10]", "name": "_addr"}, {"type": "uint256[10]", "name": "_amount"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 357165, }, { "name": "set_gas_estimate_contract", "outputs": [], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "address", "name": "_estimator"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 37747, }, { "name": "set_liquidity_gauges", "outputs": [], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "address[10]", "name": "_liquidity_gauges"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 365793, }, { "name": "address_provider", "outputs": [{"type": "address", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 2111, }, { "name": "gauge_controller", "outputs": [{"type": "address", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 2141, }, { "name": "pool_list", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "uint256", "name": "arg0"}], "stateMutability": "view", "type": "function", "gas": 2280, }, { "name": "pool_count", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 2201, }, { "name": "get_pool_from_lp_token", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "address", "name": "arg0"}], "stateMutability": "view", "type": "function", "gas": 2446, }, { "name": "get_lp_token", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "address", "name": "arg0"}], "stateMutability": "view", "type": "function", "gas": 2476, }, ] curve_pool_abi = [ { "name": "TokenExchange", "inputs": [ {"type": "address", "name": "buyer", "indexed": True}, {"type": "int128", "name": "sold_id", "indexed": False}, {"type": "uint256", "name": "tokens_sold", "indexed": False}, {"type": "int128", "name": "bought_id", "indexed": False}, {"type": "uint256", "name": "tokens_bought", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "TokenExchangeUnderlying", "inputs": [ {"type": "address", "name": "buyer", "indexed": True}, {"type": "int128", "name": "sold_id", "indexed": False}, {"type": "uint256", "name": "tokens_sold", "indexed": False}, {"type": "int128", "name": "bought_id", "indexed": False}, {"type": "uint256", "name": "tokens_bought", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "AddLiquidity", "inputs": [ {"type": "address", "name": "provider", "indexed": True}, {"type": "uint256[4]", "name": "token_amounts", "indexed": False}, {"type": "uint256[4]", "name": "fees", "indexed": False}, {"type": "uint256", "name": "invariant", "indexed": False}, {"type": "uint256", "name": "token_supply", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "RemoveLiquidity", "inputs": [ {"type": "address", "name": "provider", "indexed": True}, {"type": "uint256[4]", "name": "token_amounts", "indexed": False}, {"type": "uint256[4]", "name": "fees", "indexed": False}, {"type": "uint256", "name": "token_supply", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "RemoveLiquidityImbalance", "inputs": [ {"type": "address", "name": "provider", "indexed": True}, {"type": "uint256[4]", "name": "token_amounts", "indexed": False}, {"type": "uint256[4]", "name": "fees", "indexed": False}, {"type": "uint256", "name": "invariant", "indexed": False}, {"type": "uint256", "name": "token_supply", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "CommitNewAdmin", "inputs": [ {"type": "uint256", "name": "deadline", "indexed": True, "unit": "sec"}, {"type": "address", "name": "admin", "indexed": True}, ], "anonymous": False, "type": "event", }, { "name": "NewAdmin", "inputs": [{"type": "address", "name": "admin", "indexed": True}], "anonymous": False, "type": "event", }, { "name": "CommitNewParameters", "inputs": [ {"type": "uint256", "name": "deadline", "indexed": True, "unit": "sec"}, {"type": "uint256", "name": "A", "indexed": False}, {"type": "uint256", "name": "fee", "indexed": False}, {"type": "uint256", "name": "admin_fee", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "NewParameters", "inputs": [ {"type": "uint256", "name": "A", "indexed": False}, {"type": "uint256", "name": "fee", "indexed": False}, {"type": "uint256", "name": "admin_fee", "indexed": False}, ], "anonymous": False, "type": "event", }, { "outputs": [], "inputs": [ {"type": "address[4]", "name": "_coins"}, {"type": "address[4]", "name": "_underlying_coins"}, {"type": "address", "name": "_pool_token"}, {"type": "uint256", "name": "_A"}, {"type": "uint256", "name": "_fee"}, ], "constant": False, "payable": False, "type": "constructor", }, { "name": "get_virtual_price", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 1570535, }, { "name": "calc_token_amount", "outputs": [{"type": "uint256", "name": ""}], "inputs": [ {"type": "uint256[4]", "name": "amounts"}, {"type": "bool", "name": "deposit"}, ], "constant": True, "payable": False, "type": "function", "gas": 6103471, }, { "name": "add_liquidity", "outputs": [], "inputs": [ {"type": "uint256[4]", "name": "amounts"}, {"type": "uint256", "name": "min_mint_amount"}, ], "constant": False, "payable": False, "type": "function", "gas": 9331701, }, { "name": "get_dy", "outputs": [{"type": "uint256", "name": ""}], "inputs": [ {"type": "int128", "name": "i"}, {"type": "int128", "name": "j"}, {"type": "uint256", "name": "dx"}, ], "constant": True, "payable": False, "type": "function", "gas": 3489637, }, { "name": "get_dy_underlying", "outputs": [{"type": "uint256", "name": ""}], "inputs": [ {"type": "int128", "name": "i"}, {"type": "int128", "name": "j"}, {"type": "uint256", "name": "dx"}, ], "constant": True, "payable": False, "type": "function", "gas": 3489467, }, { "name": "exchange", "outputs": [], "inputs": [ {"type": "int128", "name": "i"}, {"type": "int128", "name": "j"}, {"type": "uint256", "name": "dx"}, {"type": "uint256", "name": "min_dy"}, ], "constant": False, "payable": False, "type": "function", "gas": 7034253, }, { "name": "exchange_underlying", "outputs": [], "inputs": [ {"type": "int128", "name": "i"}, {"type": "int128", "name": "j"}, {"type": "uint256", "name": "dx"}, {"type": "uint256", "name": "min_dy"}, ], "constant": False, "payable": False, "type": "function", "gas": 7050488, }, { "name": "remove_liquidity", "outputs": [], "inputs": [ {"type": "uint256", "name": "_amount"}, {"type": "uint256[4]", "name": "min_amounts"}, ], "constant": False, "payable": False, "type": "function", "gas": 241191, }, { "name": "remove_liquidity_imbalance", "outputs": [], "inputs": [ {"type": "uint256[4]", "name": "amounts"}, {"type": "uint256", "name": "max_burn_amount"}, ], "constant": False, "payable": False, "type": "function", "gas": 9330864, }, { "name": "commit_new_parameters", "outputs": [], "inputs": [ {"type": "uint256", "name": "amplification"}, {"type": "uint256", "name": "new_fee"}, {"type": "uint256", "name": "new_admin_fee"}, ], "constant": False, "payable": False, "type": "function", "gas": 146045, }, { "name": "apply_new_parameters", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 133452, }, { "name": "revert_new_parameters", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 21775, }, { "name": "commit_transfer_ownership", "outputs": [], "inputs": [{"type": "address", "name": "_owner"}], "constant": False, "payable": False, "type": "function", "gas": 74452, }, { "name": "apply_transfer_ownership", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 60508, }, { "name": "revert_transfer_ownership", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 21865, }, { "name": "withdraw_admin_fees", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 23448, }, { "name": "kill_me", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 37818, }, { "name": "unkill_me", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 21955, }, { "name": "coins", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "int128", "name": "arg0"}], "constant": True, "payable": False, "type": "function", "gas": 2130, }, { "name": "underlying_coins", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "int128", "name": "arg0"}], "constant": True, "payable": False, "type": "function", "gas": 2160, }, { "name": "balances", "outputs": [{"type": "uint256", "name": ""}], "inputs": [{"type": "int128", "name": "arg0"}], "constant": True, "payable": False, "type": "function", "gas": 2190, }, { "name": "A", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2021, }, { "name": "fee", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2051, }, { "name": "admin_fee", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2081, }, { "name": "owner", "outputs": [{"type": "address", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2111, }, { "name": "admin_actions_deadline", "outputs": [{"type": "uint256", "unit": "sec", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2141, }, { "name": "transfer_ownership_deadline", "outputs": [{"type": "uint256", "unit": "sec", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2171, }, { "name": "future_A", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2201, }, { "name": "future_fee", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2231, }, { "name": "future_admin_fee", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2261, }, { "name": "future_owner", "outputs": [{"type": "address", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2291, }, ]
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/oracles/abis/curve_abis.py
0.663124
0.531149
curve_abis.py
pypi
cream_ctoken_abi = [ { "inputs": [ {"internalType": "address", "name": "underlying_", "type": "address"}, { "internalType": "contract ComptrollerInterface", "name": "comptroller_", "type": "address", }, { "internalType": "contract InterestRateModel", "name": "interestRateModel_", "type": "address", }, { "internalType": "uint256", "name": "initialExchangeRateMantissa_", "type": "uint256", }, {"internalType": "string", "name": "name_", "type": "string"}, {"internalType": "string", "name": "symbol_", "type": "string"}, {"internalType": "uint8", "name": "decimals_", "type": "uint8"}, {"internalType": "address payable", "name": "admin_", "type": "address"}, {"internalType": "address", "name": "implementation_", "type": "address"}, { "internalType": "bytes", "name": "becomeImplementationData", "type": "bytes", }, ], "payable": False, "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint256", "name": "cashPrior", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "interestAccumulated", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "borrowIndex", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "totalBorrows", "type": "uint256", }, ], "name": "AccrueInterest", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": True, "internalType": "address", "name": "spender", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "borrower", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "borrowAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "accountBorrows", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "totalBorrows", "type": "uint256", }, ], "name": "Borrow", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint256", "name": "error", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "info", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "detail", "type": "uint256", }, ], "name": "Failure", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "liquidator", "type": "address", }, { "indexed": False, "internalType": "address", "name": "borrower", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "repayAmount", "type": "uint256", }, { "indexed": False, "internalType": "address", "name": "cTokenCollateral", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "seizeTokens", "type": "uint256", }, ], "name": "LiquidateBorrow", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "minter", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "mintAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "mintTokens", "type": "uint256", }, ], "name": "Mint", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "oldAdmin", "type": "address", }, { "indexed": False, "internalType": "address", "name": "newAdmin", "type": "address", }, ], "name": "NewAdmin", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "contract ComptrollerInterface", "name": "oldComptroller", "type": "address", }, { "indexed": False, "internalType": "contract ComptrollerInterface", "name": "newComptroller", "type": "address", }, ], "name": "NewComptroller", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "oldImplementation", "type": "address", }, { "indexed": False, "internalType": "address", "name": "newImplementation", "type": "address", }, ], "name": "NewImplementation", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "contract InterestRateModel", "name": "oldInterestRateModel", "type": "address", }, { "indexed": False, "internalType": "contract InterestRateModel", "name": "newInterestRateModel", "type": "address", }, ], "name": "NewMarketInterestRateModel", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "oldPendingAdmin", "type": "address", }, { "indexed": False, "internalType": "address", "name": "newPendingAdmin", "type": "address", }, ], "name": "NewPendingAdmin", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint256", "name": "oldReserveFactorMantissa", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "newReserveFactorMantissa", "type": "uint256", }, ], "name": "NewReserveFactor", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "redeemer", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "redeemAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "redeemTokens", "type": "uint256", }, ], "name": "Redeem", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "payer", "type": "address", }, { "indexed": False, "internalType": "address", "name": "borrower", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "repayAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "accountBorrows", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "totalBorrows", "type": "uint256", }, ], "name": "RepayBorrow", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "benefactor", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "addAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "newTotalReserves", "type": "uint256", }, ], "name": "ReservesAdded", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "admin", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "reduceAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "newTotalReserves", "type": "uint256", }, ], "name": "ReservesReduced", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "to", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, {"payable": True, "stateMutability": "payable", "type": "fallback"}, { "constant": False, "inputs": [], "name": "_acceptAdmin", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "uint256", "name": "addAmount", "type": "uint256"}], "name": "_addReserves", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "reduceAmount", "type": "uint256"} ], "name": "_reduceReserves", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ { "internalType": "contract ComptrollerInterface", "name": "newComptroller", "type": "address", } ], "name": "_setComptroller", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "implementation_", "type": "address"}, {"internalType": "bool", "name": "allowResign", "type": "bool"}, { "internalType": "bytes", "name": "becomeImplementationData", "type": "bytes", }, ], "name": "_setImplementation", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ { "internalType": "contract InterestRateModel", "name": "newInterestRateModel", "type": "address", } ], "name": "_setInterestRateModel", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ { "internalType": "address payable", "name": "newPendingAdmin", "type": "address", } ], "name": "_setPendingAdmin", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ { "internalType": "uint256", "name": "newReserveFactorMantissa", "type": "uint256", } ], "name": "_setReserveFactor", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "accrualBlockNumber", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [], "name": "accrueInterest", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "admin", "outputs": [{"internalType": "address payable", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}, ], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "owner", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [{"internalType": "address", "name": "owner", "type": "address"}], "name": "balanceOfUnderlying", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "borrowAmount", "type": "uint256"} ], "name": "borrow", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "borrowBalanceCurrent", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "borrowBalanceStored", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "borrowIndex", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "borrowRatePerBlock", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "comptroller", "outputs": [ { "internalType": "contract ComptrollerInterface", "name": "", "type": "address", } ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "decimals", "outputs": [{"internalType": "uint8", "name": "", "type": "uint8"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [{"internalType": "bytes", "name": "data", "type": "bytes"}], "name": "delegateToImplementation", "outputs": [{"internalType": "bytes", "name": "", "type": "bytes"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "bytes", "name": "data", "type": "bytes"}], "name": "delegateToViewImplementation", "outputs": [{"internalType": "bytes", "name": "", "type": "bytes"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [], "name": "exchangeRateCurrent", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "exchangeRateStored", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "getAccountSnapshot", "outputs": [ {"internalType": "uint256", "name": "", "type": "uint256"}, {"internalType": "uint256", "name": "", "type": "uint256"}, {"internalType": "uint256", "name": "", "type": "uint256"}, {"internalType": "uint256", "name": "", "type": "uint256"}, ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getCash", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "implementation", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "interestRateModel", "outputs": [ { "internalType": "contract InterestRateModel", "name": "", "type": "address", } ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "isCToken", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "borrower", "type": "address"}, {"internalType": "uint256", "name": "repayAmount", "type": "uint256"}, { "internalType": "contract CTokenInterface", "name": "cTokenCollateral", "type": "address", }, ], "name": "liquidateBorrow", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "mintAmount", "type": "uint256"} ], "name": "mint", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "name", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "pendingAdmin", "outputs": [{"internalType": "address payable", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "redeemTokens", "type": "uint256"} ], "name": "redeem", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "redeemAmount", "type": "uint256"} ], "name": "redeemUnderlying", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "repayAmount", "type": "uint256"} ], "name": "repayBorrow", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "reserveFactorMantissa", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "liquidator", "type": "address"}, {"internalType": "address", "name": "borrower", "type": "address"}, {"internalType": "uint256", "name": "seizeTokens", "type": "uint256"}, ], "name": "seize", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "supplyRatePerBlock", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "symbol", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "totalBorrows", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [], "name": "totalBorrowsCurrent", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "totalReserves", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "src", "type": "address"}, {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "underlying", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, ]
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/oracles/abis/cream_abis.py
0.577495
0.492249
cream_abis.py
pypi
multicall_v2_abi = [ { "inputs": [ { "components": [ {"internalType": "address", "name": "target", "type": "address"}, {"internalType": "bytes", "name": "callData", "type": "bytes"}, ], "internalType": "struct Multicall2.Call[]", "name": "calls", "type": "tuple[]", } ], "name": "aggregate", "outputs": [ {"internalType": "uint256", "name": "blockNumber", "type": "uint256"}, {"internalType": "bytes[]", "name": "returnData", "type": "bytes[]"}, ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "components": [ {"internalType": "address", "name": "target", "type": "address"}, {"internalType": "bytes", "name": "callData", "type": "bytes"}, ], "internalType": "struct Multicall2.Call[]", "name": "calls", "type": "tuple[]", } ], "name": "blockAndAggregate", "outputs": [ {"internalType": "uint256", "name": "blockNumber", "type": "uint256"}, {"internalType": "bytes32", "name": "blockHash", "type": "bytes32"}, { "components": [ {"internalType": "bool", "name": "success", "type": "bool"}, {"internalType": "bytes", "name": "returnData", "type": "bytes"}, ], "internalType": "struct Multicall2.Result[]", "name": "returnData", "type": "tuple[]", }, ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "blockNumber", "type": "uint256"} ], "name": "getBlockHash", "outputs": [ {"internalType": "bytes32", "name": "blockHash", "type": "bytes32"} ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "getBlockNumber", "outputs": [ {"internalType": "uint256", "name": "blockNumber", "type": "uint256"} ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "getCurrentBlockCoinbase", "outputs": [{"internalType": "address", "name": "coinbase", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "getCurrentBlockDifficulty", "outputs": [ {"internalType": "uint256", "name": "difficulty", "type": "uint256"} ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "getCurrentBlockGasLimit", "outputs": [{"internalType": "uint256", "name": "gaslimit", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "getCurrentBlockTimestamp", "outputs": [ {"internalType": "uint256", "name": "timestamp", "type": "uint256"} ], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "address", "name": "addr", "type": "address"}], "name": "getEthBalance", "outputs": [{"internalType": "uint256", "name": "balance", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "getLastBlockHash", "outputs": [ {"internalType": "bytes32", "name": "blockHash", "type": "bytes32"} ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "bool", "name": "requireSuccess", "type": "bool"}, { "components": [ {"internalType": "address", "name": "target", "type": "address"}, {"internalType": "bytes", "name": "callData", "type": "bytes"}, ], "internalType": "struct Multicall2.Call[]", "name": "calls", "type": "tuple[]", }, ], "name": "tryAggregate", "outputs": [ { "components": [ {"internalType": "bool", "name": "success", "type": "bool"}, {"internalType": "bytes", "name": "returnData", "type": "bytes"}, ], "internalType": "struct Multicall2.Result[]", "name": "returnData", "type": "tuple[]", } ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "bool", "name": "requireSuccess", "type": "bool"}, { "components": [ {"internalType": "address", "name": "target", "type": "address"}, {"internalType": "bytes", "name": "callData", "type": "bytes"}, ], "internalType": "struct Multicall2.Call[]", "name": "calls", "type": "tuple[]", }, ], "name": "tryBlockAndAggregate", "outputs": [ {"internalType": "uint256", "name": "blockNumber", "type": "uint256"}, {"internalType": "bytes32", "name": "blockHash", "type": "bytes32"}, { "components": [ {"internalType": "bool", "name": "success", "type": "bool"}, {"internalType": "bytes", "name": "returnData", "type": "bytes"}, ], "internalType": "struct Multicall2.Result[]", "name": "returnData", "type": "tuple[]", }, ], "stateMutability": "nonpayable", "type": "function", }, ] multicall_v2_bytecode = b'`\x80`@R4\x80\x15a\x00\x10W`\x00\x80\xfd[Pa\t\xd3\x80a\x00 `\x009`\x00\xf3\xfe`\x80`@R4\x80\x15a\x00\x10W`\x00\x80\xfd[P`\x046\x10a\x00\xb4W`\x005`\xe0\x1c\x80crB]\x9d\x11a\x00qW\x80crB]\x9d\x14a\x01:W\x80c\x86\xd5\x16\xe8\x14a\x01@W\x80c\xa8\xb0WN\x14a\x01FW\x80c\xbc\xe3\x8b\xd7\x14a\x01TW\x80c\xc3\x07\x7f\xa9\x14a\x01tW\x80c\xee\x82\xac^\x14a\x01\x87Wa\x00\xb4V[\x80c\x0f(\xc9}\x14a\x00\xb9W\x80c%-\xbaB\x14a\x00\xceW\x80c\'\xe8mn\x14a\x00\xefW\x80c9\x95B\xe9\x14a\x00\xf7W\x80cB\xcb\xb1\\\x14a\x01\x19W\x80cM#\x01\xcc\x14a\x01\x1fW[`\x00\x80\xfd[B[`@Q\x90\x81R` \x01[`@Q\x80\x91\x03\x90\xf3[a\x00\xe1a\x00\xdc6`\x04a\x06\xe2V[a\x01\x99V[`@Qa\x00\xc5\x92\x91\x90a\x08NV[a\x00\xbba\x03YV[a\x01\na\x01\x056`\x04a\x07\x1dV[a\x03lV[`@Qa\x00\xc5\x93\x92\x91\x90a\x08\xb6V[Ca\x00\xbbV[a\x00\xbba\x01-6`\x04a\x06\xc1V[`\x01`\x01`\xa0\x1b\x03\x161\x90V[Da\x00\xbbV[Ea\x00\xbbV[`@QA\x81R` \x01a\x00\xc5V[a\x01ga\x01b6`\x04a\x07\x1dV[a\x03\x84V[`@Qa\x00\xc5\x91\x90a\x08;V[a\x01\na\x01\x826`\x04a\x06\xe2V[a\x05vV[a\x00\xbba\x01\x956`\x04a\x07oV[@\x90V[\x80QC\x90``\x90g\xff\xff\xff\xff\xff\xff\xff\xff\x81\x11\x15a\x01\xc6WcNH{q`\xe0\x1b`\x00R`A`\x04R`$`\x00\xfd[`@Q\x90\x80\x82R\x80` \x02` \x01\x82\x01`@R\x80\x15a\x01\xf9W\x81` \x01[``\x81R` \x01\x90`\x01\x90\x03\x90\x81a\x01\xe4W\x90P[P\x90P`\x00[\x83Q\x81\x10\x15a\x03SW`\x00\x80\x85\x83\x81Q\x81\x10a\x02+WcNH{q`\xe0\x1b`\x00R`2`\x04R`$`\x00\xfd[` \x02` \x01\x01Q`\x00\x01Q`\x01`\x01`\xa0\x1b\x03\x16\x86\x84\x81Q\x81\x10a\x02`WcNH{q`\xe0\x1b`\x00R`2`\x04R`$`\x00\xfd[` \x02` \x01\x01Q` \x01Q`@Qa\x02y\x91\x90a\x08\x1fV[`\x00`@Q\x80\x83\x03\x81`\x00\x86Z\xf1\x91PP=\x80`\x00\x81\x14a\x02\xb6W`@Q\x91P`\x1f\x19`?=\x01\x16\x82\x01`@R=\x82R=`\x00` \x84\x01>a\x02\xbbV[``\x91P[P\x91P\x91P\x81a\x03\x12W`@QbF\x1b\xcd`\xe5\x1b\x81R` `\x04\x82\x01\x81\x90R`$\x82\x01R\x7fMulticall aggregate: call failed`D\x82\x01R`d\x01[`@Q\x80\x91\x03\x90\xfd[\x80\x84\x84\x81Q\x81\x10a\x033WcNH{q`\xe0\x1b`\x00R`2`\x04R`$`\x00\xfd[` \x02` \x01\x01\x81\x90RPPP\x80\x80a\x03K\x90a\tVV[\x91PPa\x01\xffV[P\x91P\x91V[`\x00a\x03f`\x01Ca\t\x0fV[@\x90P\x90V[C\x80@``a\x03{\x85\x85a\x03\x84V[\x90P\x92P\x92P\x92V[``\x81Qg\xff\xff\xff\xff\xff\xff\xff\xff\x81\x11\x15a\x03\xaeWcNH{q`\xe0\x1b`\x00R`A`\x04R`$`\x00\xfd[`@Q\x90\x80\x82R\x80` \x02` \x01\x82\x01`@R\x80\x15a\x03\xf4W\x81` \x01[`@\x80Q\x80\x82\x01\x90\x91R`\x00\x81R``` \x82\x01R\x81R` \x01\x90`\x01\x90\x03\x90\x81a\x03\xccW\x90P[P\x90P`\x00[\x82Q\x81\x10\x15a\x05oW`\x00\x80\x84\x83\x81Q\x81\x10a\x04&WcNH{q`\xe0\x1b`\x00R`2`\x04R`$`\x00\xfd[` \x02` \x01\x01Q`\x00\x01Q`\x01`\x01`\xa0\x1b\x03\x16\x85\x84\x81Q\x81\x10a\x04[WcNH{q`\xe0\x1b`\x00R`2`\x04R`$`\x00\xfd[` \x02` \x01\x01Q` \x01Q`@Qa\x04t\x91\x90a\x08\x1fV[`\x00`@Q\x80\x83\x03\x81`\x00\x86Z\xf1\x91PP=\x80`\x00\x81\x14a\x04\xb1W`@Q\x91P`\x1f\x19`?=\x01\x16\x82\x01`@R=\x82R=`\x00` \x84\x01>a\x04\xb6V[``\x91P[P\x91P\x91P\x85\x15a\x05\x18W\x81a\x05\x18W`@QbF\x1b\xcd`\xe5\x1b\x81R` `\x04\x82\x01R`!`$\x82\x01R\x7fMulticall2 aggregate: call faile`D\x82\x01R`\x19`\xfa\x1b`d\x82\x01R`\x84\x01a\x03\tV[`@Q\x80`@\x01`@R\x80\x83\x15\x15\x81R` \x01\x82\x81RP\x84\x84\x81Q\x81\x10a\x05OWcNH{q`\xe0\x1b`\x00R`2`\x04R`$`\x00\xfd[` \x02` \x01\x01\x81\x90RPPP\x80\x80a\x05g\x90a\tVV[\x91PPa\x03\xfaV[P\x92\x91PPV[`\x00\x80``a\x05\x86`\x01\x85a\x03lV[\x91\x96\x90\x95P\x90\x93P\x91PPV[\x805`\x01`\x01`\xa0\x1b\x03\x81\x16\x81\x14a\x05\xaaW`\x00\x80\xfd[\x91\x90PV[`\x00\x82`\x1f\x83\x01\x12a\x05\xbfW\x80\x81\xfd[\x815` g\xff\xff\xff\xff\xff\xff\xff\xff\x80\x83\x11\x15a\x05\xdcWa\x05\xdca\t\x87V[a\x05\xe9\x82\x83\x85\x02\x01a\x08\xdeV[\x83\x81R\x82\x81\x01\x90\x86\x84\x01\x86[\x86\x81\x10\x15a\x06\xb3W\x815\x89\x01`@`\x1f\x19\x81\x81\x84\x8f\x03\x01\x12\x15a\x06\x16W\x8a\x8b\xfd[a\x06\x1f\x82a\x08\xdeV[a\x06*\x8a\x85\x01a\x05\x93V[\x81R\x82\x84\x015\x89\x81\x11\x15a\x06<W\x8c\x8d\xfd[\x80\x85\x01\x94PP\x8d`?\x85\x01\x12a\x06PW\x8b\x8c\xfd[\x89\x84\x015\x89\x81\x11\x15a\x06dWa\x06da\t\x87V[a\x06t\x8b\x84`\x1f\x84\x01\x16\x01a\x08\xdeV[\x92P\x80\x83R\x8e\x84\x82\x87\x01\x01\x11\x15a\x06\x89W\x8c\x8d\xfd[\x80\x84\x86\x01\x8c\x85\x017\x82\x01\x8a\x01\x8c\x90R\x80\x8a\x01\x91\x90\x91R\x86RPP\x92\x85\x01\x92\x90\x85\x01\x90`\x01\x01a\x05\xf5V[P\x90\x98\x97PPPPPPPPV[`\x00` \x82\x84\x03\x12\x15a\x06\xd2W\x80\x81\xfd[a\x06\xdb\x82a\x05\x93V[\x93\x92PPPV[`\x00` \x82\x84\x03\x12\x15a\x06\xf3W\x80\x81\xfd[\x815g\xff\xff\xff\xff\xff\xff\xff\xff\x81\x11\x15a\x07\tW\x81\x82\xfd[a\x07\x15\x84\x82\x85\x01a\x05\xafV[\x94\x93PPPPV[`\x00\x80`@\x83\x85\x03\x12\x15a\x07/W\x80\x81\xfd[\x825\x80\x15\x15\x81\x14a\x07>W\x81\x82\xfd[\x91P` \x83\x015g\xff\xff\xff\xff\xff\xff\xff\xff\x81\x11\x15a\x07YW\x81\x82\xfd[a\x07e\x85\x82\x86\x01a\x05\xafV[\x91PP\x92P\x92\x90PV[`\x00` \x82\x84\x03\x12\x15a\x07\x80W\x80\x81\xfd[P5\x91\x90PV[`\x00\x82\x82Q\x80\x85R` \x80\x86\x01\x95P\x80\x81\x83\x02\x84\x01\x01\x81\x86\x01\x85[\x84\x81\x10\x15a\x07\xe6W\x85\x83\x03`\x1f\x19\x01\x89R\x81Q\x80Q\x15\x15\x84R\x84\x01Q`@\x85\x85\x01\x81\x90Ra\x07\xd2\x81\x86\x01\x83a\x07\xf3V[\x9a\x86\x01\x9a\x94PPP\x90\x83\x01\x90`\x01\x01a\x07\xa2V[P\x90\x97\x96PPPPPPPV[`\x00\x81Q\x80\x84Ra\x08\x0b\x81` \x86\x01` \x86\x01a\t&V[`\x1f\x01`\x1f\x19\x16\x92\x90\x92\x01` \x01\x92\x91PPV[`\x00\x82Qa\x081\x81\x84` \x87\x01a\t&V[\x91\x90\x91\x01\x92\x91PPV[`\x00` \x82Ra\x06\xdb` \x83\x01\x84a\x07\x87V[`\x00`@\x82\x01\x84\x83R` `@\x81\x85\x01R\x81\x85Q\x80\x84R``\x86\x01\x91P``\x83\x82\x02\x87\x01\x01\x93P\x82\x87\x01\x85[\x82\x81\x10\x15a\x08\xa8W`_\x19\x88\x87\x03\x01\x84Ra\x08\x96\x86\x83Qa\x07\xf3V[\x95P\x92\x84\x01\x92\x90\x84\x01\x90`\x01\x01a\x08zV[P\x93\x98\x97PPPPPPPPV[`\x00\x84\x82R\x83` \x83\x01R```@\x83\x01Ra\x08\xd5``\x83\x01\x84a\x07\x87V[\x95\x94PPPPPV[`@Q`\x1f\x82\x01`\x1f\x19\x16\x81\x01g\xff\xff\xff\xff\xff\xff\xff\xff\x81\x11\x82\x82\x10\x17\x15a\t\x07Wa\t\x07a\t\x87V[`@R\x91\x90PV[`\x00\x82\x82\x10\x15a\t!Wa\t!a\tqV[P\x03\x90V[`\x00[\x83\x81\x10\x15a\tAW\x81\x81\x01Q\x83\x82\x01R` \x01a\t)V[\x83\x81\x11\x15a\tPW`\x00\x84\x84\x01R[PPPPV[`\x00`\x00\x19\x82\x14\x15a\tjWa\tja\tqV[P`\x01\x01\x90V[cNH{q`\xe0\x1b`\x00R`\x11`\x04R`$`\x00\xfd[cNH{q`\xe0\x1b`\x00R`A`\x04R`$`\x00\xfd\xfe\xa2dipfsX"\x12 g\x87\xfa\xa4\xe9\x95"\xd9\x928\xbf\xcc\xae}\xb6c@m_\xb7m2\xf8S\x95\xe2\x07m73\xa7\xcddsolcC\x00\x08\x02\x003'
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/oracles/abis/makerdao.py
0.492188
0.568595
makerdao.py
pypi
balancer_pool_abi = [ { "inputs": [], "payable": False, "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "src", "type": "address", }, { "indexed": True, "internalType": "address", "name": "dst", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amt", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": True, "inputs": [ { "indexed": True, "internalType": "bytes4", "name": "sig", "type": "bytes4", }, { "indexed": True, "internalType": "address", "name": "caller", "type": "address", }, { "indexed": False, "internalType": "bytes", "name": "data", "type": "bytes", }, ], "name": "LOG_CALL", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "caller", "type": "address", }, { "indexed": True, "internalType": "address", "name": "tokenOut", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "tokenAmountOut", "type": "uint256", }, ], "name": "LOG_EXIT", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "caller", "type": "address", }, { "indexed": True, "internalType": "address", "name": "tokenIn", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "tokenAmountIn", "type": "uint256", }, ], "name": "LOG_JOIN", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "caller", "type": "address", }, { "indexed": True, "internalType": "address", "name": "tokenIn", "type": "address", }, { "indexed": True, "internalType": "address", "name": "tokenOut", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "tokenAmountIn", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "tokenAmountOut", "type": "uint256", }, ], "name": "LOG_SWAP", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "src", "type": "address", }, { "indexed": True, "internalType": "address", "name": "dst", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amt", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "constant": True, "inputs": [], "name": "BONE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "BPOW_PRECISION", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "EXIT_FEE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "INIT_POOL_SUPPLY", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_BOUND_TOKENS", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_BPOW_BASE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_FEE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_IN_RATIO", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_OUT_RATIO", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_TOTAL_WEIGHT", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_WEIGHT", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MIN_BALANCE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MIN_BOUND_TOKENS", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MIN_BPOW_BASE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MIN_FEE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MIN_WEIGHT", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "address", "name": "src", "type": "address"}, {"internalType": "address", "name": "dst", "type": "address"}, ], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amt", "type": "uint256"}, ], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "whom", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "balance", "type": "uint256"}, {"internalType": "uint256", "name": "denorm", "type": "uint256"}, ], "name": "bind", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenBalanceOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcInGivenOut", "outputs": [ {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenBalanceOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcOutGivenIn", "outputs": [ {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightOut", "type": "uint256"}, {"internalType": "uint256", "name": "poolSupply", "type": "uint256"}, {"internalType": "uint256", "name": "totalWeight", "type": "uint256"}, {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcPoolInGivenSingleOut", "outputs": [ {"internalType": "uint256", "name": "poolAmountIn", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightIn", "type": "uint256"}, {"internalType": "uint256", "name": "poolSupply", "type": "uint256"}, {"internalType": "uint256", "name": "totalWeight", "type": "uint256"}, {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcPoolOutGivenSingleIn", "outputs": [ {"internalType": "uint256", "name": "poolAmountOut", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightIn", "type": "uint256"}, {"internalType": "uint256", "name": "poolSupply", "type": "uint256"}, {"internalType": "uint256", "name": "totalWeight", "type": "uint256"}, {"internalType": "uint256", "name": "poolAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcSingleInGivenPoolOut", "outputs": [ {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightOut", "type": "uint256"}, {"internalType": "uint256", "name": "poolSupply", "type": "uint256"}, {"internalType": "uint256", "name": "totalWeight", "type": "uint256"}, {"internalType": "uint256", "name": "poolAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcSingleOutGivenPoolIn", "outputs": [ {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenBalanceOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightOut", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcSpotPrice", "outputs": [ {"internalType": "uint256", "name": "spotPrice", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [], "name": "decimals", "outputs": [{"internalType": "uint8", "name": "", "type": "uint8"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amt", "type": "uint256"}, ], "name": "decreaseApproval", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "poolAmountIn", "type": "uint256"}, {"internalType": "uint256[]", "name": "minAmountsOut", "type": "uint256[]"}, ], "name": "exitPool", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenOut", "type": "address"}, {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "maxPoolAmountIn", "type": "uint256"}, ], "name": "exitswapExternAmountOut", "outputs": [ {"internalType": "uint256", "name": "poolAmountIn", "type": "uint256"} ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenOut", "type": "address"}, {"internalType": "uint256", "name": "poolAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "minAmountOut", "type": "uint256"}, ], "name": "exitswapPoolAmountIn", "outputs": [ {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"} ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [], "name": "finalize", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "getBalance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getColor", "outputs": [{"internalType": "bytes32", "name": "", "type": "bytes32"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getController", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getCurrentTokens", "outputs": [ {"internalType": "address[]", "name": "tokens", "type": "address[]"} ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "getDenormalizedWeight", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getFinalTokens", "outputs": [ {"internalType": "address[]", "name": "tokens", "type": "address[]"} ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "getNormalizedWeight", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getNumTokens", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "address", "name": "tokenOut", "type": "address"}, ], "name": "getSpotPrice", "outputs": [ {"internalType": "uint256", "name": "spotPrice", "type": "uint256"} ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "address", "name": "tokenOut", "type": "address"}, ], "name": "getSpotPriceSansFee", "outputs": [ {"internalType": "uint256", "name": "spotPrice", "type": "uint256"} ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getSwapFee", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getTotalDenormalizedWeight", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "gulp", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amt", "type": "uint256"}, ], "name": "increaseApproval", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "t", "type": "address"}], "name": "isBound", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "isFinalized", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "isPublicSwap", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "poolAmountOut", "type": "uint256"}, {"internalType": "uint256[]", "name": "maxAmountsIn", "type": "uint256[]"}, ], "name": "joinPool", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "minPoolAmountOut", "type": "uint256"}, ], "name": "joinswapExternAmountIn", "outputs": [ {"internalType": "uint256", "name": "poolAmountOut", "type": "uint256"} ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "uint256", "name": "poolAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "maxAmountIn", "type": "uint256"}, ], "name": "joinswapPoolAmountOut", "outputs": [ {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"} ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "name", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "balance", "type": "uint256"}, {"internalType": "uint256", "name": "denorm", "type": "uint256"}, ], "name": "rebind", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "address", "name": "manager", "type": "address"}], "name": "setController", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "bool", "name": "public_", "type": "bool"}], "name": "setPublicSwap", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "uint256", "name": "swapFee", "type": "uint256"}], "name": "setSwapFee", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"}, {"internalType": "address", "name": "tokenOut", "type": "address"}, {"internalType": "uint256", "name": "minAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "maxPrice", "type": "uint256"}, ], "name": "swapExactAmountIn", "outputs": [ {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "spotPriceAfter", "type": "uint256"}, ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "uint256", "name": "maxAmountIn", "type": "uint256"}, {"internalType": "address", "name": "tokenOut", "type": "address"}, {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "maxPrice", "type": "uint256"}, ], "name": "swapExactAmountOut", "outputs": [ {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "spotPriceAfter", "type": "uint256"}, ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "symbol", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amt", "type": "uint256"}, ], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "src", "type": "address"}, {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amt", "type": "uint256"}, ], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "unbind", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, ]
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/oracles/abis/balancer_abis.py
0.493897
0.450299
balancer_abis.py
pypi
YVAULT_ABI = [ { "inputs": [ {"internalType": "address", "name": "_token", "type": "address"}, {"internalType": "address", "name": "_controller", "type": "address"}, ], "payable": False, "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": True, "internalType": "address", "name": "spender", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "to", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "constant": True, "inputs": [ {"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}, ], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "available", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "balance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "controller", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "decimals", "outputs": [{"internalType": "uint8", "name": "", "type": "uint8"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "subtractedValue", "type": "uint256"}, ], "name": "decreaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "uint256", "name": "_amount", "type": "uint256"}], "name": "deposit", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [], "name": "depositAll", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [], "name": "earn", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "getPricePerFullShare", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "governance", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "addedValue", "type": "uint256"}, ], "name": "increaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "max", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "min", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "name", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "_controller", "type": "address"} ], "name": "setController", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "_governance", "type": "address"} ], "name": "setGovernance", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "uint256", "name": "_min", "type": "uint256"}], "name": "setMin", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "string", "name": "_name", "type": "string"}], "name": "setName", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "string", "name": "_symbol", "type": "string"}], "name": "setSymbol", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "symbol", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "token", "outputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "sender", "type": "address"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "uint256", "name": "_shares", "type": "uint256"}], "name": "withdraw", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [], "name": "withdrawAll", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, ] YTOKEN_ABI = [ { "name": "Transfer", "inputs": [ {"name": "sender", "type": "address", "indexed": True}, {"name": "receiver", "type": "address", "indexed": True}, {"name": "value", "type": "uint256", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "Approval", "inputs": [ {"name": "owner", "type": "address", "indexed": True}, {"name": "spender", "type": "address", "indexed": True}, {"name": "value", "type": "uint256", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "StrategyAdded", "inputs": [ {"name": "strategy", "type": "address", "indexed": True}, {"name": "debtRatio", "type": "uint256", "indexed": False}, {"name": "minDebtPerHarvest", "type": "uint256", "indexed": False}, {"name": "maxDebtPerHarvest", "type": "uint256", "indexed": False}, {"name": "performanceFee", "type": "uint256", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "StrategyReported", "inputs": [ {"name": "strategy", "type": "address", "indexed": True}, {"name": "gain", "type": "uint256", "indexed": False}, {"name": "loss", "type": "uint256", "indexed": False}, {"name": "debtPaid", "type": "uint256", "indexed": False}, {"name": "totalGain", "type": "uint256", "indexed": False}, {"name": "totalLoss", "type": "uint256", "indexed": False}, {"name": "totalDebt", "type": "uint256", "indexed": False}, {"name": "debtAdded", "type": "uint256", "indexed": False}, {"name": "debtRatio", "type": "uint256", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "UpdateGovernance", "inputs": [{"name": "governance", "type": "address", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "UpdateManagement", "inputs": [{"name": "management", "type": "address", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "UpdateGuestList", "inputs": [{"name": "guestList", "type": "address", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "UpdateRewards", "inputs": [{"name": "rewards", "type": "address", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "UpdateDepositLimit", "inputs": [{"name": "depositLimit", "type": "uint256", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "UpdatePerformanceFee", "inputs": [{"name": "performanceFee", "type": "uint256", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "UpdateManagementFee", "inputs": [{"name": "managementFee", "type": "uint256", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "UpdateGuardian", "inputs": [{"name": "guardian", "type": "address", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "EmergencyShutdown", "inputs": [{"name": "active", "type": "bool", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "UpdateWithdrawalQueue", "inputs": [{"name": "queue", "type": "address[20]", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "StrategyUpdateDebtRatio", "inputs": [ {"name": "strategy", "type": "address", "indexed": True}, {"name": "debtRatio", "type": "uint256", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "StrategyUpdateMinDebtPerHarvest", "inputs": [ {"name": "strategy", "type": "address", "indexed": True}, {"name": "minDebtPerHarvest", "type": "uint256", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "StrategyUpdateMaxDebtPerHarvest", "inputs": [ {"name": "strategy", "type": "address", "indexed": True}, {"name": "maxDebtPerHarvest", "type": "uint256", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "StrategyUpdatePerformanceFee", "inputs": [ {"name": "strategy", "type": "address", "indexed": True}, {"name": "performanceFee", "type": "uint256", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "StrategyMigrated", "inputs": [ {"name": "oldVersion", "type": "address", "indexed": True}, {"name": "newVersion", "type": "address", "indexed": True}, ], "anonymous": False, "type": "event", }, { "name": "StrategyRevoked", "inputs": [{"name": "strategy", "type": "address", "indexed": True}], "anonymous": False, "type": "event", }, { "name": "StrategyRemovedFromQueue", "inputs": [{"name": "strategy", "type": "address", "indexed": True}], "anonymous": False, "type": "event", }, { "name": "StrategyAddedToQueue", "inputs": [{"name": "strategy", "type": "address", "indexed": True}], "anonymous": False, "type": "event", }, { "stateMutability": "nonpayable", "type": "function", "name": "initialize", "inputs": [ {"name": "token", "type": "address"}, {"name": "governance", "type": "address"}, {"name": "rewards", "type": "address"}, {"name": "nameOverride", "type": "string"}, {"name": "symbolOverride", "type": "string"}, ], "outputs": [], }, { "stateMutability": "nonpayable", "type": "function", "name": "initialize", "inputs": [ {"name": "token", "type": "address"}, {"name": "governance", "type": "address"}, {"name": "rewards", "type": "address"}, {"name": "nameOverride", "type": "string"}, {"name": "symbolOverride", "type": "string"}, {"name": "guardian", "type": "address"}, ], "outputs": [], }, { "stateMutability": "pure", "type": "function", "name": "apiVersion", "inputs": [], "outputs": [{"name": "", "type": "string"}], "gas": 4546, }, { "stateMutability": "nonpayable", "type": "function", "name": "setName", "inputs": [{"name": "name", "type": "string"}], "outputs": [], "gas": 107044, }, { "stateMutability": "nonpayable", "type": "function", "name": "setSymbol", "inputs": [{"name": "symbol", "type": "string"}], "outputs": [], "gas": 71894, }, { "stateMutability": "nonpayable", "type": "function", "name": "setGovernance", "inputs": [{"name": "governance", "type": "address"}], "outputs": [], "gas": 36365, }, { "stateMutability": "nonpayable", "type": "function", "name": "acceptGovernance", "inputs": [], "outputs": [], "gas": 37637, }, { "stateMutability": "nonpayable", "type": "function", "name": "setManagement", "inputs": [{"name": "management", "type": "address"}], "outputs": [], "gas": 37775, }, { "stateMutability": "nonpayable", "type": "function", "name": "setGuestList", "inputs": [{"name": "guestList", "type": "address"}], "outputs": [], "gas": 37805, }, { "stateMutability": "nonpayable", "type": "function", "name": "setRewards", "inputs": [{"name": "rewards", "type": "address"}], "outputs": [], "gas": 37835, }, { "stateMutability": "nonpayable", "type": "function", "name": "setLockedProfitDegration", "inputs": [{"name": "degration", "type": "uint256"}], "outputs": [], "gas": 36519, }, { "stateMutability": "nonpayable", "type": "function", "name": "setDepositLimit", "inputs": [{"name": "limit", "type": "uint256"}], "outputs": [], "gas": 37795, }, { "stateMutability": "nonpayable", "type": "function", "name": "setPerformanceFee", "inputs": [{"name": "fee", "type": "uint256"}], "outputs": [], "gas": 37929, }, { "stateMutability": "nonpayable", "type": "function", "name": "setManagementFee", "inputs": [{"name": "fee", "type": "uint256"}], "outputs": [], "gas": 37959, }, { "stateMutability": "nonpayable", "type": "function", "name": "setGuardian", "inputs": [{"name": "guardian", "type": "address"}], "outputs": [], "gas": 39203, }, { "stateMutability": "nonpayable", "type": "function", "name": "setEmergencyShutdown", "inputs": [{"name": "active", "type": "bool"}], "outputs": [], "gas": 39274, }, { "stateMutability": "nonpayable", "type": "function", "name": "setWithdrawalQueue", "inputs": [{"name": "queue", "type": "address[20]"}], "outputs": [], "gas": 763950, }, { "stateMutability": "nonpayable", "type": "function", "name": "transfer", "inputs": [ {"name": "receiver", "type": "address"}, {"name": "amount", "type": "uint256"}, ], "outputs": [{"name": "", "type": "bool"}], "gas": 76768, }, { "stateMutability": "nonpayable", "type": "function", "name": "transferFrom", "inputs": [ {"name": "sender", "type": "address"}, {"name": "receiver", "type": "address"}, {"name": "amount", "type": "uint256"}, ], "outputs": [{"name": "", "type": "bool"}], "gas": 116531, }, { "stateMutability": "nonpayable", "type": "function", "name": "approve", "inputs": [ {"name": "spender", "type": "address"}, {"name": "amount", "type": "uint256"}, ], "outputs": [{"name": "", "type": "bool"}], "gas": 38271, }, { "stateMutability": "nonpayable", "type": "function", "name": "increaseAllowance", "inputs": [ {"name": "spender", "type": "address"}, {"name": "amount", "type": "uint256"}, ], "outputs": [{"name": "", "type": "bool"}], "gas": 40312, }, { "stateMutability": "nonpayable", "type": "function", "name": "decreaseAllowance", "inputs": [ {"name": "spender", "type": "address"}, {"name": "amount", "type": "uint256"}, ], "outputs": [{"name": "", "type": "bool"}], "gas": 40336, }, { "stateMutability": "nonpayable", "type": "function", "name": "permit", "inputs": [ {"name": "owner", "type": "address"}, {"name": "spender", "type": "address"}, {"name": "amount", "type": "uint256"}, {"name": "expiry", "type": "uint256"}, {"name": "signature", "type": "bytes"}, ], "outputs": [{"name": "", "type": "bool"}], "gas": 81264, }, { "stateMutability": "view", "type": "function", "name": "totalAssets", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 4098, }, { "stateMutability": "nonpayable", "type": "function", "name": "deposit", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "nonpayable", "type": "function", "name": "deposit", "inputs": [{"name": "_amount", "type": "uint256"}], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "nonpayable", "type": "function", "name": "deposit", "inputs": [ {"name": "_amount", "type": "uint256"}, {"name": "recipient", "type": "address"}, ], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "view", "type": "function", "name": "maxAvailableShares", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 383839, }, { "stateMutability": "nonpayable", "type": "function", "name": "withdraw", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "nonpayable", "type": "function", "name": "withdraw", "inputs": [{"name": "maxShares", "type": "uint256"}], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "nonpayable", "type": "function", "name": "withdraw", "inputs": [ {"name": "maxShares", "type": "uint256"}, {"name": "recipient", "type": "address"}, ], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "nonpayable", "type": "function", "name": "withdraw", "inputs": [ {"name": "maxShares", "type": "uint256"}, {"name": "recipient", "type": "address"}, {"name": "maxLoss", "type": "uint256"}, ], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "view", "type": "function", "name": "pricePerShare", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 18195, }, { "stateMutability": "nonpayable", "type": "function", "name": "addStrategy", "inputs": [ {"name": "strategy", "type": "address"}, {"name": "debtRatio", "type": "uint256"}, {"name": "minDebtPerHarvest", "type": "uint256"}, {"name": "maxDebtPerHarvest", "type": "uint256"}, {"name": "performanceFee", "type": "uint256"}, ], "outputs": [], "gas": 1485796, }, { "stateMutability": "nonpayable", "type": "function", "name": "updateStrategyDebtRatio", "inputs": [ {"name": "strategy", "type": "address"}, {"name": "debtRatio", "type": "uint256"}, ], "outputs": [], "gas": 115193, }, { "stateMutability": "nonpayable", "type": "function", "name": "updateStrategyMinDebtPerHarvest", "inputs": [ {"name": "strategy", "type": "address"}, {"name": "minDebtPerHarvest", "type": "uint256"}, ], "outputs": [], "gas": 42441, }, { "stateMutability": "nonpayable", "type": "function", "name": "updateStrategyMaxDebtPerHarvest", "inputs": [ {"name": "strategy", "type": "address"}, {"name": "maxDebtPerHarvest", "type": "uint256"}, ], "outputs": [], "gas": 42471, }, { "stateMutability": "nonpayable", "type": "function", "name": "updateStrategyPerformanceFee", "inputs": [ {"name": "strategy", "type": "address"}, {"name": "performanceFee", "type": "uint256"}, ], "outputs": [], "gas": 41251, }, { "stateMutability": "nonpayable", "type": "function", "name": "migrateStrategy", "inputs": [ {"name": "oldVersion", "type": "address"}, {"name": "newVersion", "type": "address"}, ], "outputs": [], "gas": 1141468, }, { "stateMutability": "nonpayable", "type": "function", "name": "revokeStrategy", "inputs": [], "outputs": [], }, { "stateMutability": "nonpayable", "type": "function", "name": "revokeStrategy", "inputs": [{"name": "strategy", "type": "address"}], "outputs": [], }, { "stateMutability": "nonpayable", "type": "function", "name": "addStrategyToQueue", "inputs": [{"name": "strategy", "type": "address"}], "outputs": [], "gas": 1199804, }, { "stateMutability": "nonpayable", "type": "function", "name": "removeStrategyFromQueue", "inputs": [{"name": "strategy", "type": "address"}], "outputs": [], "gas": 23088703, }, { "stateMutability": "view", "type": "function", "name": "debtOutstanding", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "view", "type": "function", "name": "debtOutstanding", "inputs": [{"name": "strategy", "type": "address"}], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "view", "type": "function", "name": "creditAvailable", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "view", "type": "function", "name": "creditAvailable", "inputs": [{"name": "strategy", "type": "address"}], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "view", "type": "function", "name": "availableDepositLimit", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 9551, }, { "stateMutability": "view", "type": "function", "name": "expectedReturn", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "view", "type": "function", "name": "expectedReturn", "inputs": [{"name": "strategy", "type": "address"}], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "nonpayable", "type": "function", "name": "report", "inputs": [ {"name": "gain", "type": "uint256"}, {"name": "loss", "type": "uint256"}, {"name": "_debtPayment", "type": "uint256"}, ], "outputs": [{"name": "", "type": "uint256"}], "gas": 1015170, }, { "stateMutability": "nonpayable", "type": "function", "name": "sweep", "inputs": [{"name": "token", "type": "address"}], "outputs": [], }, { "stateMutability": "nonpayable", "type": "function", "name": "sweep", "inputs": [ {"name": "token", "type": "address"}, {"name": "amount", "type": "uint256"}, ], "outputs": [], }, { "stateMutability": "view", "type": "function", "name": "name", "inputs": [], "outputs": [{"name": "", "type": "string"}], "gas": 8750, }, { "stateMutability": "view", "type": "function", "name": "symbol", "inputs": [], "outputs": [{"name": "", "type": "string"}], "gas": 7803, }, { "stateMutability": "view", "type": "function", "name": "decimals", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2408, }, { "stateMutability": "view", "type": "function", "name": "precisionFactor", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2438, }, { "stateMutability": "view", "type": "function", "name": "balanceOf", "inputs": [{"name": "arg0", "type": "address"}], "outputs": [{"name": "", "type": "uint256"}], "gas": 2683, }, { "stateMutability": "view", "type": "function", "name": "allowance", "inputs": [ {"name": "arg0", "type": "address"}, {"name": "arg1", "type": "address"}, ], "outputs": [{"name": "", "type": "uint256"}], "gas": 2928, }, { "stateMutability": "view", "type": "function", "name": "totalSupply", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2528, }, { "stateMutability": "view", "type": "function", "name": "token", "inputs": [], "outputs": [{"name": "", "type": "address"}], "gas": 2558, }, { "stateMutability": "view", "type": "function", "name": "governance", "inputs": [], "outputs": [{"name": "", "type": "address"}], "gas": 2588, }, { "stateMutability": "view", "type": "function", "name": "management", "inputs": [], "outputs": [{"name": "", "type": "address"}], "gas": 2618, }, { "stateMutability": "view", "type": "function", "name": "guardian", "inputs": [], "outputs": [{"name": "", "type": "address"}], "gas": 2648, }, { "stateMutability": "view", "type": "function", "name": "guestList", "inputs": [], "outputs": [{"name": "", "type": "address"}], "gas": 2678, }, { "stateMutability": "view", "type": "function", "name": "strategies", "inputs": [{"name": "arg0", "type": "address"}], "outputs": [ {"name": "performanceFee", "type": "uint256"}, {"name": "activation", "type": "uint256"}, {"name": "debtRatio", "type": "uint256"}, {"name": "minDebtPerHarvest", "type": "uint256"}, {"name": "maxDebtPerHarvest", "type": "uint256"}, {"name": "lastReport", "type": "uint256"}, {"name": "totalDebt", "type": "uint256"}, {"name": "totalGain", "type": "uint256"}, {"name": "totalLoss", "type": "uint256"}, ], "gas": 11031, }, { "stateMutability": "view", "type": "function", "name": "withdrawalQueue", "inputs": [{"name": "arg0", "type": "uint256"}], "outputs": [{"name": "", "type": "address"}], "gas": 2847, }, { "stateMutability": "view", "type": "function", "name": "emergencyShutdown", "inputs": [], "outputs": [{"name": "", "type": "bool"}], "gas": 2768, }, { "stateMutability": "view", "type": "function", "name": "depositLimit", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2798, }, { "stateMutability": "view", "type": "function", "name": "debtRatio", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2828, }, { "stateMutability": "view", "type": "function", "name": "totalDebt", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2858, }, { "stateMutability": "view", "type": "function", "name": "lastReport", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2888, }, { "stateMutability": "view", "type": "function", "name": "activation", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2918, }, { "stateMutability": "view", "type": "function", "name": "lockedProfit", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2948, }, { "stateMutability": "view", "type": "function", "name": "lockedProfitDegration", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2978, }, { "stateMutability": "view", "type": "function", "name": "rewards", "inputs": [], "outputs": [{"name": "", "type": "address"}], "gas": 3008, }, { "stateMutability": "view", "type": "function", "name": "managementFee", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 3038, }, { "stateMutability": "view", "type": "function", "name": "performanceFee", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 3068, }, { "stateMutability": "view", "type": "function", "name": "nonces", "inputs": [{"name": "arg0", "type": "address"}], "outputs": [{"name": "", "type": "uint256"}], "gas": 3313, }, { "stateMutability": "view", "type": "function", "name": "DOMAIN_SEPARATOR", "inputs": [], "outputs": [{"name": "", "type": "bytes32"}], "gas": 3128, }, ]
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/oracles/abis/yearn_abis.py
0.521959
0.48182
yearn_abis.py
pypi
import json import os import sys from typing import Any, Dict, Optional from eth_typing import ChecksumAddress from hexbytes import HexBytes from web3 import Web3 from web3.contract import Contract from gnosis.util import cache def load_contract_interface(file_name): return _load_json_file(_abi_file_path(file_name)) def _abi_file_path(file): return os.path.abspath(os.path.join(os.path.dirname(__file__), file)) def _load_json_file(path): with open(path) as f: return json.load(f) current_module = sys.modules[__name__] contracts = { "safe_V1_3_0": "GnosisSafe_V1_3_0.json", "safe_V1_1_1": "GnosisSafe_V1_1_1.json", "safe_V1_0_0": "GnosisSafe_V1_0_0.json", "safe_V0_0_1": "GnosisSafe_V0_0_1.json", "compatibility_fallback_handler_V1_3_0": "CompatibilityFallbackHandler_V1_3_0.json", "erc20": "ERC20.json", "erc721": "ERC721.json", "erc1155": "ERC1155.json", "example_erc20": "ERC20TestToken.json", "delegate_constructor_proxy": "DelegateConstructorProxy.json", "multi_send": "MultiSend.json", "paying_proxy": "PayingProxy.json", "proxy_factory": "ProxyFactory_V1_3_0.json", "proxy_factory_V1_1_1": "ProxyFactory_V1_1_1.json", "proxy_factory_V1_0_0": "ProxyFactory_V1_0_0.json", "proxy": "Proxy_V1_1_1.json", "uniswap_exchange": "uniswap_exchange.json", "uniswap_factory": "uniswap_factory.json", "uniswap_v2_factory": "uniswap_v2_factory.json", "uniswap_v2_pair": "uniswap_v2_pair.json", "uniswap_v2_router": "uniswap_v2_router.json", # Router02 "kyber_network_proxy": "kyber_network_proxy.json", "cpk_factory": "CPKFactory.json", } def generate_contract_fn(contract: Dict[str, Any]): """ Dynamically generate functions to work with the contracts :param contract: :return: """ def fn(w3: Web3, address: Optional[ChecksumAddress] = None): return w3.eth.contract( address=address, abi=contract["abi"], bytecode=contract.get("bytecode") ) return fn # Anotate functions that will be generated later with `setattr` so typing does not complains def get_safe_contract(w3: Web3, address: Optional[str] = None) -> Contract: """ :param w3: :param address: :return: Latest available safe contract (v1.3.0) """ return get_safe_V1_3_0_contract(w3, address=address) def get_safe_V1_3_0_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_safe_V1_1_1_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_safe_V1_0_0_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_safe_V0_0_1_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_compatibility_fallback_handler_V1_3_0_contract( w3: Web3, address: Optional[str] = None ) -> Contract: pass def get_erc20_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_erc721_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_erc1155_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_example_erc20_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_delegate_constructor_proxy_contract( w3: Web3, address: Optional[str] = None ) -> Contract: pass def get_multi_send_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_paying_proxy_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_proxy_factory_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_proxy_factory_V1_1_1_contract( w3: Web3, address: Optional[str] = None ) -> Contract: pass def get_proxy_factory_V1_0_0_contract( w3: Web3, address: Optional[str] = None ) -> Contract: pass def get_proxy_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_uniswap_exchange_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_uniswap_factory_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_uniswap_v2_factory_contract( w3: Web3, address: Optional[str] = None ) -> Contract: pass def get_uniswap_v2_pair_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_uniswap_v2_router_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_kyber_network_proxy_contract( w3: Web3, address: Optional[str] = None ) -> Contract: pass def get_cpk_factory_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass @cache def get_proxy_1_3_0_deployed_bytecode() -> bytes: return HexBytes(load_contract_interface("Proxy_V1_3_0.json")["deployedBytecode"]) def get_proxy_1_1_1_mainnet_deployed_bytecode() -> bytes: """ Somehow it's different from the generated version compiling the contracts """ return HexBytes( "0x608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea265627a7a72315820d8a00dc4fe6bf675a9d7416fc2d00bb3433362aa8186b750f76c4027269667ff64736f6c634300050e0032" ) @cache def get_proxy_1_1_1_deployed_bytecode() -> bytes: return HexBytes(load_contract_interface("Proxy_V1_1_1.json")["deployedBytecode"]) @cache def get_proxy_1_0_0_deployed_bytecode() -> bytes: return HexBytes(load_contract_interface("Proxy_V1_0_0.json")["deployedBytecode"]) @cache def get_paying_proxy_deployed_bytecode() -> bytes: return HexBytes(load_contract_interface("PayingProxy.json")["deployedBytecode"]) for contract_name, json_contract_filename in contracts.items(): fn_name = "get_{}_contract".format(contract_name) contract_dict = load_contract_interface(json_contract_filename) if not contract_dict: raise ValueError(f"{contract_name} json cannot be empty") setattr(current_module, fn_name, generate_contract_fn(contract_dict))
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/eth/contracts/__init__.py
0.621885
0.210543
__init__.py
pypi
from enum import Enum from logging import getLogger from typing import List, Optional, Union from eth_account.signers.local import LocalAccount from eth_typing import ChecksumAddress from hexbytes import HexBytes from web3 import Web3 from gnosis.eth import EthereumClient, EthereumTxSent from gnosis.eth.contracts import get_multi_send_contract from gnosis.eth.typing import EthereumData from gnosis.eth.utils import fast_bytes_to_checksum_address, fast_is_checksum_address logger = getLogger(__name__) class MultiSendOperation(Enum): CALL = 0 DELEGATE_CALL = 1 class MultiSendTx: """ Wrapper for a single MultiSendTx """ def __init__( self, operation: MultiSendOperation, to: str, value: int, data: EthereumData, old_encoding: bool = False, ): """ :param operation: MultisendOperation, CALL or DELEGATE_CALL :param to: Address :param value: Value in Wei :param data: data as hex string or bytes :param old_encoding: True if using old multisend ABI Encoded data, False otherwise """ self.operation = operation self.to = to self.value = value self.data = HexBytes(data) if data else b"" self.old_encoding = old_encoding def __eq__(self, other): if not isinstance(other, MultiSendTx): return NotImplemented return ( self.operation == other.operation and self.to == other.to and self.value == other.value and self.data == other.data ) def __len__(self): """ :return: Size on bytes of the tx """ return 21 + 32 * 2 + self.data_length def __repr__(self): data = self.data[:4].hex() + ("..." if len(self.data) > 4 else "") return ( f"MultisendTx operation={self.operation.name} to={self.to} value={self.value} " f"data={data}" ) @property def data_length(self) -> int: return len(self.data) @property def encoded_data(self): operation = HexBytes("{:0>2x}".format(self.operation.value)) # Operation 1 byte to = HexBytes("{:0>40x}".format(int(self.to, 16))) # Address 20 bytes value = HexBytes("{:0>64x}".format(self.value)) # Value 32 bytes data_length = HexBytes( "{:0>64x}".format(self.data_length) ) # Data length 32 bytes return operation + to + value + data_length + self.data @classmethod def from_bytes(cls, encoded_multisend_tx: Union[str, bytes]) -> "MultiSendTx": """ Decoded one MultiSend transaction. ABI must be used to get the `transactions` parameter and use that data for this function :param encoded_multisend_tx: :return: """ encoded_multisend_tx = HexBytes(encoded_multisend_tx) try: return cls._decode_multisend_data(encoded_multisend_tx) except ValueError: # Try using the old decoding method return cls._decode_multisend_old_transaction(encoded_multisend_tx) @classmethod def _decode_multisend_data(cls, encoded_multisend_tx: Union[str, bytes]): """ Decodes one Multisend transaction. If there's more data after `data` it's ignored. Fallbacks to the old multisend structure if this structure cannot be decoded. https://etherscan.io/address/0x8D29bE29923b68abfDD21e541b9374737B49cdAD#code Structure: - operation -> MultiSendOperation 1 byte - to -> ethereum address 20 bytes - value -> tx value 32 bytes - data_length -> 32 bytes - data -> `data_length` bytes :param encoded_multisend_tx: 1 multisend transaction encoded :return: Tx as a MultisendTx """ encoded_multisend_tx = HexBytes(encoded_multisend_tx) operation = MultiSendOperation(encoded_multisend_tx[0]) to = fast_bytes_to_checksum_address(encoded_multisend_tx[1 : 1 + 20]) value = int.from_bytes(encoded_multisend_tx[21 : 21 + 32], byteorder="big") data_length = int.from_bytes( encoded_multisend_tx[21 + 32 : 21 + 32 * 2], byteorder="big" ) data = encoded_multisend_tx[21 + 32 * 2 : 21 + 32 * 2 + data_length] len_data = len(data) if len_data != data_length: raise ValueError( f"Data length {data_length} is different from len(data) {len_data}" ) return cls(operation, to, value, data, old_encoding=False) @classmethod def _decode_multisend_old_transaction( cls, encoded_multisend_tx: Union[str, bytes] ) -> "MultiSendTx": """ Decodes one old multisend transaction. If there's more data after `data` it's ignored. The difference with the new MultiSend is that every value but `data` is padded to 32 bytes, wasting a lot of bytes. https://etherscan.io/address/0xE74d6AF1670FB6560dd61EE29eB57C7Bc027Ce4E#code Structure: - operation -> MultiSendOperation 32 byte - to -> ethereum address 32 bytes - value -> tx value 32 bytes - data_length -> 32 bytes - data -> `data_length` bytes :param encoded_multisend_tx: 1 multisend transaction encoded :return: Tx as a MultisendTx """ encoded_multisend_tx = HexBytes(encoded_multisend_tx) operation = MultiSendOperation( int.from_bytes(encoded_multisend_tx[:32], byteorder="big") ) to = fast_bytes_to_checksum_address(encoded_multisend_tx[32:64][-20:]) value = int.from_bytes(encoded_multisend_tx[64:96], byteorder="big") data_length = int.from_bytes(encoded_multisend_tx[128:160], byteorder="big") data = encoded_multisend_tx[160 : 160 + data_length] len_data = len(data) if len_data != data_length: raise ValueError( f"Data length {data_length} is different from len(data) {len_data}" ) return cls(operation, to, value, data, old_encoding=True) class MultiSend: dummy_w3 = Web3() MULTISEND_ADDRESSES = ( "0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761", # MultiSend v1.3.0 "0x998739BFdAAdde7C933B942a68053933098f9EDa", # MultiSend v1.3.0 (EIP-155) ) MULTISEND_CALL_ONLY_ADDRESSES = ( "0x40A2aCCbd92BCA938b02010E17A5b8929b49130D", # MultiSend Call Only v1.3.0 "0xA1dabEF33b3B82c7814B6D82A79e50F4AC44102B", # MultiSend Call Only v1.3.0 (EIP-155) ) def __init__( self, ethereum_client: Optional[EthereumClient] = None, address: Optional[ChecksumAddress] = None, call_only: bool = True, ): """ :param ethereum_client: Required for detecting the address in the network. :param address: If not provided, will try to detect it from the hardcoded addresses using `ethereum_client`. :param call_only: If `True` use `call only` MultiSend, otherwise use regular one. Only if `address` not provided """ self.address = address self.ethereum_client = ethereum_client self.call_only = call_only addresses = ( self.MULTISEND_CALL_ONLY_ADDRESSES if call_only else self.MULTISEND_ADDRESSES ) if address: assert fast_is_checksum_address(address), ( "%s proxy factory address not valid" % address ) elif ethereum_client: # Try to detect MultiSend address if not provided for address in addresses: if ethereum_client.is_contract(address): self.address = address break else: self.address = addresses[0] if not self.address: raise ValueError( f"Cannot find a MultiSend contract for chainId={self.ethereum_client.get_chain_id()}" ) @property def w3(self): return (self.ethereum_client and self.ethereum_client.w3) or Web3() @classmethod def from_bytes(cls, encoded_multisend_txs: Union[str, bytes]) -> List[MultiSendTx]: """ Decodes one or more multisend transactions from `bytes transactions` (Abi decoded) :param encoded_multisend_txs: :return: List of MultiSendTxs """ if not encoded_multisend_txs: return [] encoded_multisend_txs = HexBytes(encoded_multisend_txs) multisend_tx = MultiSendTx.from_bytes(encoded_multisend_txs) multisend_tx_size = len(multisend_tx) assert ( multisend_tx_size > 0 ), "Multisend tx cannot be empty" # This should never happen, just in case if multisend_tx.old_encoding: next_data_position = ( (multisend_tx.data_length + 0x1F) // 0x20 * 0x20 ) + 0xA0 else: next_data_position = multisend_tx_size remaining_data = encoded_multisend_txs[next_data_position:] return [multisend_tx] + cls.from_bytes(remaining_data) @classmethod def from_transaction_data( cls, multisend_data: Union[str, bytes] ) -> List[MultiSendTx]: """ Decodes multisend transactions from transaction data (ABI encoded with selector) :return: """ try: _, data = get_multi_send_contract(cls.dummy_w3).decode_function_input( multisend_data ) return cls.from_bytes(data["transactions"]) except ValueError: return [] @staticmethod def deploy_contract( ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy proxy factory contract :param ethereum_client: :param deployer_account: Ethereum Account :return: deployed contract address """ contract = get_multi_send_contract(ethereum_client.w3) tx = contract.constructor().build_transaction( {"from": deployer_account.address} ) tx_hash = ethereum_client.send_unsigned_transaction( tx, private_key=deployer_account.key ) tx_receipt = ethereum_client.get_transaction_receipt(tx_hash, timeout=120) assert tx_receipt assert tx_receipt["status"] contract_address = tx_receipt["contractAddress"] logger.info( "Deployed and initialized Proxy Factory Contract=%s by %s", contract_address, deployer_account.address, ) return EthereumTxSent(tx_hash, tx, contract_address) def get_contract(self): return get_multi_send_contract(self.w3, self.address) def build_tx_data(self, multi_send_txs: List[MultiSendTx]) -> bytes: """ Txs don't need to be valid to get through :param multi_send_txs: :return: """ multisend_contract = self.get_contract() encoded_multisend_data = b"".join([x.encoded_data for x in multi_send_txs]) return multisend_contract.functions.multiSend( encoded_multisend_data ).build_transaction({"gas": 1, "gasPrice": 1})["data"]
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/safe/multi_send.py
0.915252
0.451206
multi_send.py
pypi
from abc import ABC, abstractmethod from enum import Enum from logging import getLogger from typing import List, Union from eth_abi import decode_single, encode_single from eth_abi.exceptions import DecodingError from eth_account.messages import defunct_hash_message from eth_typing import ChecksumAddress from hexbytes import HexBytes from web3.exceptions import BadFunctionCallOutput from gnosis.eth import EthereumClient from gnosis.eth.contracts import get_safe_contract, get_safe_V1_1_1_contract from gnosis.eth.utils import fast_to_checksum_address from gnosis.safe.signatures import ( get_signing_address, signature_split, signature_to_bytes, ) logger = getLogger(__name__) EthereumBytes = Union[bytes, str] class SafeSignatureException(Exception): pass class CannotCheckEIP1271ContractSignature(SafeSignatureException): pass class SafeSignatureType(Enum): CONTRACT_SIGNATURE = 0 APPROVED_HASH = 1 EOA = 2 ETH_SIGN = 3 @staticmethod def from_v(v: int): if v == 0: return SafeSignatureType.CONTRACT_SIGNATURE elif v == 1: return SafeSignatureType.APPROVED_HASH elif v > 30: return SafeSignatureType.ETH_SIGN else: return SafeSignatureType.EOA def uint_to_address(value: int) -> ChecksumAddress: """ Convert a Solidity `uint` value to a checksummed `address`, removing invalid padding bytes if present :return: Checksummed address """ encoded = encode_single("uint", value) # Remove padding bytes, as Solidity will ignore it but `eth_abi` will not encoded_without_padding_bytes = b"\x00" * 12 + encoded[-20:] return fast_to_checksum_address( decode_single("address", encoded_without_padding_bytes) ) class SafeSignature(ABC): def __init__(self, signature: EthereumBytes, safe_tx_hash: EthereumBytes): self.signature = HexBytes(signature) self.safe_tx_hash = HexBytes(safe_tx_hash) self.v, self.r, self.s = signature_split(self.signature) def __str__(self): return f"SafeSignature type={self.signature_type.name} owner={self.owner}" @classmethod def parse_signature( cls, signatures: EthereumBytes, safe_tx_hash: EthereumBytes, ignore_trailing: bool = True, ) -> List["SafeSignature"]: """ :param signatures: One or more signatures appended. EIP1271 data at the end is supported. :param safe_tx_hash: :param ignore_trailing: Ignore trailing data on the signature. Some libraries pad it and add some zeroes at the end :return: List of SafeSignatures decoded """ if not signatures: return [] elif isinstance(signatures, str): signatures = HexBytes(signatures) signature_size = 65 # For contract signatures there'll be some data at the end data_position = len( signatures ) # For contract signatures, to stop parsing at data position safe_signatures = [] for i in range(0, len(signatures), signature_size): if ( i >= data_position ): # If contract signature data position is reached, stop break signature = signatures[i : i + signature_size] if ignore_trailing and len(signature) < 65: # Trailing stuff break v, r, s = signature_split(signature) signature_type = SafeSignatureType.from_v(v) safe_signature: "SafeSignature" if signature_type == SafeSignatureType.CONTRACT_SIGNATURE: if s < data_position: data_position = s contract_signature_len = int.from_bytes( signatures[s : s + 32], "big" ) # Len size is 32 bytes contract_signature = signatures[ s + 32 : s + 32 + contract_signature_len ] # Skip array size (32 bytes) safe_signature = SafeSignatureContract( signature, safe_tx_hash, contract_signature ) elif signature_type == SafeSignatureType.APPROVED_HASH: safe_signature = SafeSignatureApprovedHash(signature, safe_tx_hash) elif signature_type == SafeSignatureType.EOA: safe_signature = SafeSignatureEOA(signature, safe_tx_hash) elif signature_type == SafeSignatureType.ETH_SIGN: safe_signature = SafeSignatureEthSign(signature, safe_tx_hash) safe_signatures.append(safe_signature) return safe_signatures def export_signature(self) -> HexBytes: """ Exports signature in a format that's valid individually. That's important for contract signatures, as it will fix the offset :return: """ return self.signature @property @abstractmethod def owner(self): """ :return: Decode owner from signature, without any further validation (signature can be not valid) """ raise NotImplementedError @abstractmethod def is_valid(self, ethereum_client: EthereumClient, safe_address: str) -> bool: """ :param ethereum_client: Required for Contract Signature and Approved Hash check :param safe_address: Required for Approved Hash check :return: `True` if signature is valid, `False` otherwise """ raise NotImplementedError @property @abstractmethod def signature_type(self) -> SafeSignatureType: raise NotImplementedError class SafeSignatureContract(SafeSignature): EIP1271_MAGIC_VALUE = HexBytes(0x20C13B0B) EIP1271_MAGIC_VALUE_UPDATED = HexBytes(0x1626BA7E) def __init__( self, signature: EthereumBytes, safe_tx_hash: EthereumBytes, contract_signature: EthereumBytes, ): super().__init__(signature, safe_tx_hash) self.contract_signature = HexBytes(contract_signature) @property def owner(self) -> ChecksumAddress: """ :return: Address of contract signing. No further checks to get the owner are needed, but it could be a non existing contract """ return uint_to_address(self.r) @property def signature_type(self) -> SafeSignatureType: return SafeSignatureType.CONTRACT_SIGNATURE def export_signature(self) -> HexBytes: """ Fix offset (s) and append `contract_signature` at the end of the signature :return: """ return HexBytes( signature_to_bytes(self.v, self.r, 65) + encode_single("bytes", self.contract_signature) ) def is_valid(self, ethereum_client: EthereumClient, *args) -> bool: safe_contract = get_safe_V1_1_1_contract(ethereum_client.w3, self.owner) # Newest versions of the Safe contract have `isValidSignature` on the compatibility fallback handler for block_identifier in ("pending", "latest"): try: return safe_contract.functions.isValidSignature( self.safe_tx_hash, self.contract_signature ).call(block_identifier=block_identifier) in ( self.EIP1271_MAGIC_VALUE, self.EIP1271_MAGIC_VALUE_UPDATED, ) except (ValueError, BadFunctionCallOutput, DecodingError): # Error using `pending` block identifier or contract does not exist logger.warning( "Cannot check EIP1271 signature from contract %s", self.owner ) return False class SafeSignatureApprovedHash(SafeSignature): @property def owner(self): return uint_to_address(self.r) @property def signature_type(self): return SafeSignatureType.APPROVED_HASH @classmethod def build_for_owner( cls, owner: str, safe_tx_hash: str ) -> "SafeSignatureApprovedHash": r = owner.lower().replace("0x", "").rjust(64, "0") s = "0" * 64 v = "01" return cls(HexBytes(r + s + v), safe_tx_hash) def is_valid(self, ethereum_client: EthereumClient, safe_address: str) -> bool: safe_contract = get_safe_contract(ethereum_client.w3, safe_address) exception: Exception for block_identifier in ("pending", "latest"): try: return ( safe_contract.functions.approvedHashes( self.owner, self.safe_tx_hash ).call(block_identifier=block_identifier) == 1 ) except BadFunctionCallOutput as e: # Error using `pending` block identifier exception = e raise exception # This should never happen class SafeSignatureEthSign(SafeSignature): @property def owner(self): # defunct_hash_message prepends `\x19Ethereum Signed Message:\n32` message_hash = defunct_hash_message(primitive=self.safe_tx_hash) return get_signing_address(message_hash, self.v - 4, self.r, self.s) @property def signature_type(self): return SafeSignatureType.ETH_SIGN def is_valid(self, *args) -> bool: return True class SafeSignatureEOA(SafeSignature): @property def owner(self): return get_signing_address(self.safe_tx_hash, self.v, self.r, self.s) @property def signature_type(self): return SafeSignatureType.EOA def is_valid(self, *args) -> bool: return True
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/safe/safe_signature.py
0.917409
0.276031
safe_signature.py
pypi
from typing import Any, Dict, List, NoReturn, Optional, Tuple, Type from eip712_structs import Address, Bytes, EIP712Struct, Uint, make_domain from eip712_structs.struct import StructTuple from eth_account import Account from hexbytes import HexBytes from packaging.version import Version from web3.exceptions import BadFunctionCallOutput, ContractLogicError from web3.types import BlockIdentifier, TxParams, Wei from gnosis.eth import EthereumClient from gnosis.eth.constants import NULL_ADDRESS from gnosis.eth.contracts import get_safe_contract from gnosis.util import cached_property from ..eth.ethereum_client import TxSpeed from ..eth.utils import fast_keccak from .exceptions import ( CouldNotFinishInitialization, CouldNotPayGasWithEther, CouldNotPayGasWithToken, HashHasNotBeenApproved, InvalidContractSignatureLocation, InvalidInternalTx, InvalidMultisigTx, InvalidOwnerProvided, InvalidSignaturesProvided, MethodCanOnlyBeCalledFromThisContract, ModuleManagerException, NotEnoughSafeTransactionGas, OnlyOwnersCanApproveAHash, OwnerManagerException, SafeTransactionFailedWhenGasPriceAndSafeTxGasEmpty, SignatureNotProvidedByOwner, SignaturesDataTooShort, ThresholdNeedsToBeDefined, ) from .safe_signature import SafeSignature from .signatures import signature_to_bytes class EIP712SafeTx(EIP712Struct): to = Address() value = Uint(256) data = Bytes() operation = Uint(8) safeTxGas = Uint(256) baseGas = Uint(256) # `dataGas` was renamed to `baseGas` in 1.0.0 gasPrice = Uint(256) gasToken = Address() refundReceiver = Address() nonce = Uint(256) class EIP712LegacySafeTx(EIP712Struct): to = Address() value = Uint(256) data = Bytes() operation = Uint(8) safeTxGas = Uint(256) dataGas = Uint(256) gasPrice = Uint(256) gasToken = Address() refundReceiver = Address() nonce = Uint(256) EIP712SafeTx.type_name = "SafeTx" EIP712LegacySafeTx.type_name = "SafeTx" class SafeTx: def __init__( self, ethereum_client: EthereumClient, safe_address: str, to: Optional[str], value: int, data: bytes, operation: int, safe_tx_gas: int, base_gas: int, gas_price: int, gas_token: Optional[str], refund_receiver: Optional[str], signatures: Optional[bytes] = None, safe_nonce: Optional[int] = None, safe_version: str = None, chain_id: Optional[int] = None, ): """ :param ethereum_client: :param safe_address: :param to: :param value: :param data: :param operation: :param safe_tx_gas: :param base_gas: :param gas_price: :param gas_token: :param refund_receiver: :param signatures: :param safe_nonce: Current nonce of the Safe. If not provided, it will be retrieved from network :param safe_version: Safe version 1.0.0 renamed `baseGas` to `dataGas`. Safe version 1.3.0 added `chainId` to the `domainSeparator`. If not provided, it will be retrieved from network :param chain_id: Ethereum network chain_id is used in hash calculation for Safes >= 1.3.0. If not provided, it will be retrieved from the provided ethereum_client """ self.ethereum_client = ethereum_client self.safe_address = safe_address self.to = to or NULL_ADDRESS self.value = int(value) self.data = HexBytes(data) if data else b"" self.operation = int(operation) self.safe_tx_gas = int(safe_tx_gas) self.base_gas = int(base_gas) self.gas_price = int(gas_price) self.gas_token = gas_token or NULL_ADDRESS self.refund_receiver = refund_receiver or NULL_ADDRESS self.signatures = signatures or b"" self._safe_nonce = safe_nonce and int(safe_nonce) self._safe_version = safe_version self._chain_id = chain_id and int(chain_id) self.tx: Optional[TxParams] = None # If executed, `tx` is set self.tx_hash: Optional[bytes] = None # If executed, `tx_hash` is set def __str__(self): return ( f"SafeTx - safe={self.safe_address} - to={self.to} - value={self.value} - data={self.data.hex()} - " f"operation={self.operation} - safe-tx-gas={self.safe_tx_gas} - base-gas={self.base_gas} - " f"gas-price={self.gas_price} - gas-token={self.gas_token} - refund-receiver={self.refund_receiver} - " f"signers = {self.signers}" ) @property def w3(self): return self.ethereum_client.w3 @cached_property def contract(self): return get_safe_contract(self.w3, address=self.safe_address) @cached_property def chain_id(self) -> int: if self._chain_id is not None: return self._chain_id else: return self.ethereum_client.get_chain_id() @cached_property def safe_nonce(self) -> str: if self._safe_nonce is not None: return self._safe_nonce else: return self.contract.functions.nonce().call() @cached_property def safe_version(self) -> str: if self._safe_version is not None: return self._safe_version else: return self.contract.functions.VERSION().call() @property def _eip712_payload(self) -> StructTuple: data = self.data.hex() if self.data else "" safe_version = Version(self.safe_version) cls = EIP712SafeTx if safe_version >= Version("1.0.0") else EIP712LegacySafeTx message = cls( to=self.to, value=self.value, data=data, operation=self.operation, safeTxGas=self.safe_tx_gas, baseGas=self.base_gas, dataGas=self.base_gas, gasPrice=self.gas_price, gasToken=self.gas_token, refundReceiver=self.refund_receiver, nonce=self.safe_nonce, ) domain = make_domain( verifyingContract=self.safe_address, chainId=self.chain_id if safe_version >= Version("1.3.0") else None, ) return StructTuple(message, domain) @property def eip712_structured_data(self) -> Dict: message, domain = self._eip712_payload return message.to_message(domain) @property def safe_tx_hash(self) -> HexBytes: message, domain = self._eip712_payload signable_bytes = message.signable_bytes(domain) return HexBytes(fast_keccak(signable_bytes)) @property def signers(self) -> List[str]: if not self.signatures: return [] else: return [ safe_signature.owner for safe_signature in SafeSignature.parse_signature( self.signatures, self.safe_tx_hash ) ] @property def sorted_signers(self): return sorted(self.signers, key=lambda x: int(x, 16)) @property def w3_tx(self): """ :return: Web3 contract tx prepared for `call`, `transact` or `build_transaction` """ return self.contract.functions.execTransaction( self.to, self.value, self.data, self.operation, self.safe_tx_gas, self.base_gas, self.gas_price, self.gas_token, self.refund_receiver, self.signatures, ) def _raise_safe_vm_exception(self, message: str) -> NoReturn: error_with_exception: Dict[str, Type[InvalidMultisigTx]] = { # https://github.com/safe-global/safe-contracts/blob/v1.3.0/docs/error_codes.md "GS000": CouldNotFinishInitialization, "GS001": ThresholdNeedsToBeDefined, "Could not pay gas costs with ether": CouldNotPayGasWithEther, "GS011": CouldNotPayGasWithEther, "Could not pay gas costs with token": CouldNotPayGasWithToken, "GS012": CouldNotPayGasWithToken, "GS013": SafeTransactionFailedWhenGasPriceAndSafeTxGasEmpty, "Hash has not been approved": HashHasNotBeenApproved, "Hash not approved": HashHasNotBeenApproved, "GS025": HashHasNotBeenApproved, "Invalid contract signature location: data not complete": InvalidContractSignatureLocation, "GS023": InvalidContractSignatureLocation, "Invalid contract signature location: inside static part": InvalidContractSignatureLocation, "GS021": InvalidContractSignatureLocation, "Invalid contract signature location: length not present": InvalidContractSignatureLocation, "GS022": InvalidContractSignatureLocation, "Invalid contract signature provided": InvalidContractSignatureLocation, "GS024": InvalidContractSignatureLocation, "Invalid owner provided": InvalidOwnerProvided, "Invalid owner address provided": InvalidOwnerProvided, "GS026": InvalidOwnerProvided, "Invalid signatures provided": InvalidSignaturesProvided, "Not enough gas to execute safe transaction": NotEnoughSafeTransactionGas, "GS010": NotEnoughSafeTransactionGas, "Only owners can approve a hash": OnlyOwnersCanApproveAHash, "GS030": OnlyOwnersCanApproveAHash, "GS031": MethodCanOnlyBeCalledFromThisContract, "Signature not provided by owner": SignatureNotProvidedByOwner, "Signatures data too short": SignaturesDataTooShort, "GS020": SignaturesDataTooShort, # ModuleManager "GS100": ModuleManagerException, "Invalid module address provided": ModuleManagerException, "GS101": ModuleManagerException, "GS102": ModuleManagerException, "Invalid prevModule, module pair provided": ModuleManagerException, "GS103": ModuleManagerException, "Method can only be called from an enabled module": ModuleManagerException, "GS104": ModuleManagerException, "Module has already been added": ModuleManagerException, # OwnerManager "Address is already an owner": OwnerManagerException, "GS200": OwnerManagerException, # Owners have already been setup "GS201": OwnerManagerException, # Threshold cannot exceed owner count "GS202": OwnerManagerException, # Invalid owner address provided "GS203": OwnerManagerException, # Invalid ower address provided "GS204": OwnerManagerException, # Address is already an owner "GS205": OwnerManagerException, # Invalid prevOwner, owner pair provided "Invalid prevOwner, owner pair provided": OwnerManagerException, "New owner count needs to be larger than new threshold": OwnerManagerException, "Threshold cannot exceed owner count": OwnerManagerException, "Threshold needs to be greater than 0": OwnerManagerException, } for reason, custom_exception in error_with_exception.items(): if reason in message: raise custom_exception(message) raise InvalidMultisigTx(message) def call( self, tx_sender_address: Optional[str] = None, tx_gas: Optional[int] = None, block_identifier: Optional[BlockIdentifier] = "latest", ) -> int: """ :param tx_sender_address: :param tx_gas: Force a gas limit :param block_identifier: :return: `1` if everything ok """ parameters: Dict[str, Any] = { "from": tx_sender_address if tx_sender_address else self.safe_address } if tx_gas: parameters["gas"] = tx_gas try: success = self.w3_tx.call(parameters, block_identifier=block_identifier) if not success: raise InvalidInternalTx( "Success bit is %d, should be equal to 1" % success ) return success except (ContractLogicError, BadFunctionCallOutput, ValueError) as exc: # e.g. web3.exceptions.ContractLogicError: execution reverted: Invalid owner provided return self._raise_safe_vm_exception(str(exc)) except ValueError as exc: # Parity """ Parity throws a ValueError, e.g. {'code': -32015, 'message': 'VM execution error.', 'data': 'Reverted 0x08c379a0000000000000000000000000000000000000000000000000000000000000020000000000000000 000000000000000000000000000000000000000000000001b496e76616c6964207369676e6174757265732070726f7669 6465640000000000' } """ error_dict = exc.args[0] data = error_dict.get("data") if data and isinstance(data, str) and "Reverted " in data: # Parity result = HexBytes(data.replace("Reverted ", "")) return self._raise_safe_vm_exception(str(result)) else: raise exc def recommended_gas(self) -> Wei: """ :return: Recommended gas to use on the ethereum_tx """ return Wei(self.base_gas + self.safe_tx_gas + 75000) def execute( self, tx_sender_private_key: str, tx_gas: Optional[int] = None, tx_gas_price: Optional[int] = None, tx_nonce: Optional[int] = None, block_identifier: Optional[BlockIdentifier] = "latest", eip1559_speed: Optional[TxSpeed] = None, ) -> Tuple[HexBytes, TxParams]: """ Send multisig tx to the Safe :param tx_sender_private_key: Sender private key :param tx_gas: Gas for the external tx. If not, `(safe_tx_gas + base_gas) * 2` will be used :param tx_gas_price: Gas price of the external tx. If not, `gas_price` will be used :param tx_nonce: Force nonce for `tx_sender` :param block_identifier: `latest` or `pending` :param eip1559_speed: If provided, use EIP1559 transaction :return: Tuple(tx_hash, tx) :raises: InvalidMultisigTx: If user tx cannot go through the Safe """ sender_account = Account.from_key(tx_sender_private_key) if eip1559_speed and self.ethereum_client.is_eip1559_supported(): tx_parameters = self.ethereum_client.set_eip1559_fees( { "from": sender_account.address, }, tx_speed=eip1559_speed, ) else: tx_parameters = { "from": sender_account.address, "gasPrice": tx_gas_price or self.w3.eth.gas_price, } if tx_gas: tx_parameters["gas"] = tx_gas if tx_nonce is not None: tx_parameters["nonce"] = tx_nonce self.tx = self.w3_tx.build_transaction(tx_parameters) self.tx["gas"] = Wei( tx_gas or (max(self.tx["gas"] + 75000, self.recommended_gas())) ) self.tx_hash = self.ethereum_client.send_unsigned_transaction( self.tx, private_key=sender_account.key, retry=False if tx_nonce is not None else True, block_identifier=block_identifier, ) # Set signatures empty after executing the tx. `Nonce` is increased even if it fails, # so signatures are not valid anymore self.signatures = b"" return self.tx_hash, self.tx def sign(self, private_key: str) -> bytes: """ {bytes32 r}{bytes32 s}{uint8 v} :param private_key: :return: Signature """ account = Account.from_key(private_key) signature_dict = account.signHash(self.safe_tx_hash) signature = signature_to_bytes( signature_dict["v"], signature_dict["r"], signature_dict["s"] ) # Insert signature sorted if account.address not in self.signers: new_owners = self.signers + [account.address] new_owner_pos = sorted(new_owners, key=lambda x: int(x, 16)).index( account.address ) self.signatures = ( self.signatures[: 65 * new_owner_pos] + signature + self.signatures[65 * new_owner_pos :] ) return signature def unsign(self, address: str) -> bool: for pos, signer in enumerate(self.signers): if signer == address: self.signatures = self.signatures.replace( self.signatures[pos * 65 : pos * 65 + 65], b"" ) return True return False
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/safe/safe_tx.py
0.909125
0.18939
safe_tx.py
pypi
import dataclasses import math from enum import Enum from logging import getLogger from typing import Callable, List, NamedTuple, Optional, Union from eth_abi import encode_abi from eth_abi.packed import encode_abi_packed from eth_account import Account from eth_account.signers.local import LocalAccount from eth_typing import ChecksumAddress, Hash32 from hexbytes import HexBytes from web3 import Web3 from web3.contract import Contract from web3.exceptions import BadFunctionCallOutput from web3.types import BlockIdentifier, Wei from gnosis.eth import EthereumClient, EthereumTxSent from gnosis.eth.constants import GAS_CALL_DATA_BYTE, NULL_ADDRESS, SENTINEL_ADDRESS from gnosis.eth.contracts import ( get_compatibility_fallback_handler_V1_3_0_contract, get_delegate_constructor_proxy_contract, get_safe_contract, get_safe_V0_0_1_contract, get_safe_V1_0_0_contract, get_safe_V1_1_1_contract, get_safe_V1_3_0_contract, ) from gnosis.eth.utils import ( fast_bytes_to_checksum_address, fast_is_checksum_address, fast_keccak, get_eth_address_with_key, ) from gnosis.safe.proxy_factory import ProxyFactory from gnosis.util import cached_property from ..eth.typing import EthereumData from .exceptions import ( CannotEstimateGas, CannotRetrieveSafeInfoException, InvalidPaymentToken, ) from .safe_create2_tx import SafeCreate2Tx, SafeCreate2TxBuilder from .safe_creation_tx import InvalidERC20Token, SafeCreationTx from .safe_tx import SafeTx logger = getLogger(__name__) class SafeCreationEstimate(NamedTuple): gas: int gas_price: int payment: int payment_token: Optional[str] class SafeOperation(Enum): CALL = 0 DELEGATE_CALL = 1 CREATE = 2 @dataclasses.dataclass class SafeInfo: address: ChecksumAddress fallback_handler: ChecksumAddress guard: ChecksumAddress master_copy: ChecksumAddress modules: List[ChecksumAddress] nonce: int owners: List[ChecksumAddress] threshold: int version: str class Safe: """ Class to manage a Gnosis Safe """ # keccak256("fallback_manager.handler.address") FALLBACK_HANDLER_STORAGE_SLOT = ( 0x6C9A6C4A39284E37ED1CF53D337577D14212A4870FB976A4366C693B939918D5 ) # keccak256("guard_manager.guard.address") GUARD_STORAGE_SLOT = ( 0x4A204F620C8C5CCDCA3FD54D003BADD85BA500436A431F0CBDA4F558C93C34C8 ) # keccak256("EIP712Domain(uint256 chainId,address verifyingContract)"); DOMAIN_TYPEHASH = bytes.fromhex( "47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218" ) # keccak256("SafeMessage(bytes message)"); SAFE_MESSAGE_TYPEHASH = bytes.fromhex( "60b3cbf8b4a223d68d641b3b6ddf9a298e7f33710cf3d3a9d1146b5a6150fbca" ) def __init__(self, address: ChecksumAddress, ethereum_client: EthereumClient): """ :param address: Safe address :param ethereum_client: Initialized ethereum client """ assert fast_is_checksum_address(address), "%s is not a valid address" % address self.ethereum_client = ethereum_client self.w3 = self.ethereum_client.w3 self.address = address def __str__(self): return f"Safe={self.address}" @staticmethod def create( ethereum_client: EthereumClient, deployer_account: LocalAccount, master_copy_address: str, owners: List[str], threshold: int, fallback_handler: str = NULL_ADDRESS, proxy_factory_address: Optional[str] = None, payment_token: str = NULL_ADDRESS, payment: int = 0, payment_receiver: str = NULL_ADDRESS, ) -> EthereumTxSent: """ Deploy new Safe proxy pointing to the specified `master_copy` address and configured with the provided `owners` and `threshold`. By default, payment for the deployer of the tx will be `0`. If `proxy_factory_address` is set deployment will be done using the proxy factory instead of calling the `constructor` of a new `DelegatedProxy` Using `proxy_factory_address` is recommended, as it takes less gas. (Testing with `Ganache` and 1 owner 261534 without proxy vs 229022 with Proxy) """ assert owners, "At least one owner must be set" assert 1 <= threshold <= len(owners), "Threshold=%d must be <= %d" % ( threshold, len(owners), ) initializer = ( get_safe_contract(ethereum_client.w3, NULL_ADDRESS) .functions.setup( owners, threshold, NULL_ADDRESS, # Contract address for optional delegate call b"", # Data payload for optional delegate call fallback_handler, # Handler for fallback calls to this contract, payment_token, payment, payment_receiver, ) .build_transaction({"gas": Wei(1), "gasPrice": Wei(1)})["data"] ) if proxy_factory_address: proxy_factory = ProxyFactory(proxy_factory_address, ethereum_client) return proxy_factory.deploy_proxy_contract( deployer_account, master_copy_address, initializer=HexBytes(initializer) ) proxy_contract = get_delegate_constructor_proxy_contract(ethereum_client.w3) tx = proxy_contract.constructor( master_copy_address, initializer ).build_transaction({"from": deployer_account.address}) tx["gas"] = tx["gas"] * 100000 tx_hash = ethereum_client.send_unsigned_transaction( tx, private_key=deployer_account.key ) tx_receipt = ethereum_client.get_transaction_receipt(tx_hash, timeout=60) assert tx_receipt assert tx_receipt["status"] contract_address = tx_receipt["contractAddress"] return EthereumTxSent(tx_hash, tx, contract_address) @staticmethod def _deploy_master_contract( ethereum_client: EthereumClient, deployer_account: LocalAccount, contract_fn: Callable[[Web3, Optional[str]], Contract], ) -> EthereumTxSent: """ Deploy master contract. Takes deployer_account (if unlocked in the node) or the deployer private key Safe with version > v1.1.1 doesn't need to be initialized as it already has a constructor :param ethereum_client: :param deployer_account: Ethereum account :param contract_fn: get contract function :return: deployed contract address """ safe_contract = contract_fn(ethereum_client.w3) constructor_tx = safe_contract.constructor().build_transaction() tx_hash = ethereum_client.send_unsigned_transaction( constructor_tx, private_key=deployer_account.key ) tx_receipt = ethereum_client.get_transaction_receipt(tx_hash, timeout=60) assert tx_receipt assert tx_receipt["status"] ethereum_tx_sent = EthereumTxSent( tx_hash, constructor_tx, tx_receipt["contractAddress"] ) logger.info( "Deployed and initialized Safe Master Contract version=%s on address %s by %s", contract_fn(ethereum_client.w3, ethereum_tx_sent.contract_address) .functions.VERSION() .call(), ethereum_tx_sent.contract_address, deployer_account.address, ) return ethereum_tx_sent @classmethod def deploy_compatibility_fallback_handler( cls, ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy Compatibility Fallback handler v1.3.0 :param ethereum_client: :param deployer_account: Ethereum account :return: deployed contract address """ contract = get_compatibility_fallback_handler_V1_3_0_contract( ethereum_client.w3 ) constructor_tx = contract.constructor().build_transaction() tx_hash = ethereum_client.send_unsigned_transaction( constructor_tx, private_key=deployer_account.key ) tx_receipt = ethereum_client.get_transaction_receipt(tx_hash, timeout=60) assert tx_receipt assert tx_receipt["status"] ethereum_tx_sent = EthereumTxSent( tx_hash, constructor_tx, tx_receipt["contractAddress"] ) logger.info( "Deployed and initialized Compatibility Fallback Handler version=%s on address %s by %s", "1.3.0", ethereum_tx_sent.contract_address, deployer_account.address, ) return ethereum_tx_sent @classmethod def deploy_master_contract_v1_3_0( cls, ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy master contract v1.3.0. Takes deployer_account (if unlocked in the node) or the deployer private key Safe with version > v1.1.1 doesn't need to be initialized as it already has a constructor :param ethereum_client: :param deployer_account: Ethereum account :return: deployed contract address """ return cls._deploy_master_contract( ethereum_client, deployer_account, get_safe_V1_3_0_contract ) @classmethod def deploy_master_contract_v1_1_1( cls, ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy master contract v1.1.1. Takes deployer_account (if unlocked in the node) or the deployer private key Safe with version > v1.1.1 doesn't need to be initialized as it already has a constructor :param ethereum_client: :param deployer_account: Ethereum account :return: deployed contract address """ return cls._deploy_master_contract( ethereum_client, deployer_account, get_safe_V1_1_1_contract ) @staticmethod def deploy_master_contract_v1_0_0( ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy master contract. Takes deployer_account (if unlocked in the node) or the deployer private key :param ethereum_client: :param deployer_account: Ethereum account :return: deployed contract address """ safe_contract = get_safe_V1_0_0_contract(ethereum_client.w3) constructor_data = safe_contract.constructor().build_transaction({"gas": 0})[ "data" ] initializer_data = safe_contract.functions.setup( # We use 2 owners that nobody controls for the master copy [ "0x0000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000003", ], 2, # Threshold. Maximum security NULL_ADDRESS, # Address for optional DELEGATE CALL b"", # Data for optional DELEGATE CALL NULL_ADDRESS, # Payment token 0, # Payment NULL_ADDRESS, # Refund receiver ).build_transaction({"to": NULL_ADDRESS})["data"] ethereum_tx_sent = ethereum_client.deploy_and_initialize_contract( deployer_account, constructor_data, HexBytes(initializer_data) ) logger.info( "Deployed and initialized Safe Master Contract=%s by %s", ethereum_tx_sent.contract_address, deployer_account.address, ) return ethereum_tx_sent @staticmethod def deploy_master_contract_v0_0_1( ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy master contract. Takes deployer_account (if unlocked in the node) or the deployer private key :param ethereum_client: :param deployer_account: Ethereum account :return: deployed contract address """ safe_contract = get_safe_V0_0_1_contract(ethereum_client.w3) constructor_data = safe_contract.constructor().build_transaction({"gas": 0})[ "data" ] initializer_data = safe_contract.functions.setup( # We use 2 owners that nobody controls for the master copy [ "0x0000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000003", ], 2, # Threshold. Maximum security NULL_ADDRESS, # Address for optional DELEGATE CALL b"", # Data for optional DELEGATE CALL ).build_transaction({"to": NULL_ADDRESS})["data"] ethereum_tx_sent = ethereum_client.deploy_and_initialize_contract( deployer_account, constructor_data, HexBytes(initializer_data) ) logger.info( "Deployed and initialized Old Safe Master Contract=%s by %s", ethereum_tx_sent.contract_address, deployer_account.address, ) return ethereum_tx_sent @staticmethod def estimate_safe_creation( ethereum_client: EthereumClient, old_master_copy_address: str, number_owners: int, gas_price: int, payment_token: Optional[str], payment_receiver: str = NULL_ADDRESS, payment_token_eth_value: float = 1.0, fixed_creation_cost: Optional[int] = None, ) -> SafeCreationEstimate: s = 15 owners = [get_eth_address_with_key()[0] for _ in range(number_owners)] threshold = number_owners safe_creation_tx = SafeCreationTx( w3=ethereum_client.w3, owners=owners, threshold=threshold, signature_s=s, master_copy=old_master_copy_address, gas_price=gas_price, funder=payment_receiver, payment_token=payment_token, payment_token_eth_value=payment_token_eth_value, fixed_creation_cost=fixed_creation_cost, ) return SafeCreationEstimate( safe_creation_tx.gas, safe_creation_tx.gas_price, safe_creation_tx.payment, safe_creation_tx.payment_token, ) @staticmethod def estimate_safe_creation_2( ethereum_client: EthereumClient, master_copy_address: str, proxy_factory_address: str, number_owners: int, gas_price: int, payment_token: Optional[str], payment_receiver: str = NULL_ADDRESS, fallback_handler: Optional[str] = None, payment_token_eth_value: float = 1.0, fixed_creation_cost: Optional[int] = None, ) -> SafeCreationEstimate: salt_nonce = 15 owners = [Account.create().address for _ in range(number_owners)] threshold = number_owners if not fallback_handler: fallback_handler = ( Account.create().address ) # Better estimate it, it's required for new Safes safe_creation_tx = SafeCreate2TxBuilder( w3=ethereum_client.w3, master_copy_address=master_copy_address, proxy_factory_address=proxy_factory_address, ).build( owners=owners, threshold=threshold, fallback_handler=fallback_handler, salt_nonce=salt_nonce, gas_price=gas_price, payment_receiver=payment_receiver, payment_token=payment_token, payment_token_eth_value=payment_token_eth_value, fixed_creation_cost=fixed_creation_cost, ) return SafeCreationEstimate( safe_creation_tx.gas, safe_creation_tx.gas_price, safe_creation_tx.payment, safe_creation_tx.payment_token, ) @staticmethod def build_safe_creation_tx( ethereum_client: EthereumClient, master_copy_old_address: str, s: int, owners: List[str], threshold: int, gas_price: int, payment_token: Optional[str], payment_receiver: str, payment_token_eth_value: float = 1.0, fixed_creation_cost: Optional[int] = None, ) -> SafeCreationTx: try: safe_creation_tx = SafeCreationTx( w3=ethereum_client.w3, owners=owners, threshold=threshold, signature_s=s, master_copy=master_copy_old_address, gas_price=gas_price, funder=payment_receiver, payment_token=payment_token, payment_token_eth_value=payment_token_eth_value, fixed_creation_cost=fixed_creation_cost, ) except InvalidERC20Token as exc: raise InvalidPaymentToken( "Invalid payment token %s" % payment_token ) from exc assert safe_creation_tx.tx_pyethereum.nonce == 0 return safe_creation_tx @staticmethod def build_safe_create2_tx( ethereum_client: EthereumClient, master_copy_address: str, proxy_factory_address: str, salt_nonce: int, owners: List[str], threshold: int, gas_price: int, payment_token: Optional[str], payment_receiver: Optional[str] = None, # If none, it will be `tx.origin` fallback_handler: Optional[str] = NULL_ADDRESS, payment_token_eth_value: float = 1.0, fixed_creation_cost: Optional[int] = None, ) -> SafeCreate2Tx: """ Prepare safe proxy deployment for being relayed. It calculates and sets the costs of deployment to be returned to the sender of the tx. If you are an advanced user you may prefer to use `create` function """ try: safe_creation_tx = SafeCreate2TxBuilder( w3=ethereum_client.w3, master_copy_address=master_copy_address, proxy_factory_address=proxy_factory_address, ).build( owners=owners, threshold=threshold, fallback_handler=fallback_handler, salt_nonce=salt_nonce, gas_price=gas_price, payment_receiver=payment_receiver, payment_token=payment_token, payment_token_eth_value=payment_token_eth_value, fixed_creation_cost=fixed_creation_cost, ) except InvalidERC20Token as exc: raise InvalidPaymentToken( "Invalid payment token %s" % payment_token ) from exc return safe_creation_tx @cached_property def contract(self) -> Contract: v_1_3_0_contract = get_safe_V1_3_0_contract(self.w3, address=self.address) version = v_1_3_0_contract.functions.VERSION().call() if version == "1.3.0": return v_1_3_0_contract else: return get_safe_V1_1_1_contract(self.w3, address=self.address) @cached_property def domain_separator(self): return fast_keccak( encode_abi( ["bytes32", "uint256", "address"], [ self.DOMAIN_TYPEHASH, self.ethereum_client.get_chain_id(), self.address, ], ) ) def check_funds_for_tx_gas( self, safe_tx_gas: int, base_gas: int, gas_price: int, gas_token: str ) -> bool: """ Check safe has enough funds to pay for a tx :param safe_tx_gas: Safe tx gas :param base_gas: Data gas :param gas_price: Gas Price :param gas_token: Gas Token, to use token instead of ether for the gas :return: `True` if enough funds, `False` otherwise """ if gas_token == NULL_ADDRESS: balance = self.ethereum_client.get_balance(self.address) else: balance = self.ethereum_client.erc20.get_balance(self.address, gas_token) return balance >= (safe_tx_gas + base_gas) * gas_price def estimate_tx_base_gas( self, to: str, value: int, data: bytes, operation: int, gas_token: str, estimated_tx_gas: int, ) -> int: """ Calculate gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund...) :param to: :param value: :param data: :param operation: :param gas_token: :param estimated_tx_gas: gas calculated with `estimate_tx_gas` :return: """ data = data or b"" safe_contract = self.contract threshold = self.retrieve_threshold() nonce = self.retrieve_nonce() # Every byte == 0 -> 4 Gas # Every byte != 0 -> 16 Gas (68 before Istanbul) # numbers < 256 (0x00(31*2)..ff) are 192 -> 31 * 4 + 1 * GAS_CALL_DATA_BYTE # numbers < 65535 (0x(30*2)..ffff) are 256 -> 30 * 4 + 2 * GAS_CALL_DATA_BYTE # Calculate gas for signatures # (array count (3 -> r, s, v) + ecrecover costs) * signature count # ecrecover for ecdsa ~= 4K gas, we use 6K ecrecover_gas = 6000 signature_gas = threshold * ( 1 * GAS_CALL_DATA_BYTE + 2 * 32 * GAS_CALL_DATA_BYTE + ecrecover_gas ) safe_tx_gas = estimated_tx_gas base_gas = 0 gas_price = 1 gas_token = gas_token or NULL_ADDRESS signatures = b"" refund_receiver = NULL_ADDRESS data = HexBytes( safe_contract.functions.execTransaction( to, value, data, operation, safe_tx_gas, base_gas, gas_price, gas_token, refund_receiver, signatures, ).build_transaction({"gas": 1, "gasPrice": 1})["data"] ) # If nonce == 0, nonce storage has to be initialized if nonce == 0: nonce_gas = 20000 else: nonce_gas = 5000 # Keccak costs for the hash of the safe tx hash_generation_gas = 1500 base_gas = ( signature_gas + self.ethereum_client.estimate_data_gas(data) + nonce_gas + hash_generation_gas ) # Add additional gas costs if base_gas > 65536: base_gas += 64 else: base_gas += 128 base_gas += 32000 # Base tx costs, transfer costs... return base_gas def estimate_tx_gas_with_safe( self, to: str, value: int, data: bytes, operation: int, gas_limit: Optional[int] = None, block_identifier: Optional[BlockIdentifier] = "latest", ) -> int: """ Estimate tx gas using safe `requiredTxGas` method :return: int: Estimated gas :raises: CannotEstimateGas: If gas cannot be estimated :raises: ValueError: Cannot decode received data """ safe_address = self.address data = data or b"" def parse_revert_data(result: bytes) -> int: # 4 bytes - error method id # 32 bytes - position # 32 bytes - length # Last 32 bytes - value of revert (if everything went right) gas_estimation_offset = 4 + 32 + 32 gas_estimation = result[gas_estimation_offset:] # Estimated gas must be 32 bytes if len(gas_estimation) != 32: gas_limit_text = ( f"with gas limit={gas_limit} " if gas_limit is not None else "without gas limit set " ) logger.warning( "Safe=%s Problem estimating gas, returned value %sis %s for tx=%s", safe_address, gas_limit_text, result.hex(), tx, ) raise CannotEstimateGas("Received %s for tx=%s" % (result.hex(), tx)) return int(gas_estimation.hex(), 16) tx = self.contract.functions.requiredTxGas( to, value, data, operation ).build_transaction( { "from": safe_address, "gas": 0, # Don't call estimate "gasPrice": 0, # Don't get gas price } ) tx_params = { "from": safe_address, "to": safe_address, "data": tx["data"], } if gas_limit: tx_params["gas"] = hex(gas_limit) query = { "jsonrpc": "2.0", "method": "eth_call", "params": [tx_params, block_identifier], "id": 1, } response = self.ethereum_client.http_session.post( self.ethereum_client.ethereum_node_url, json=query, timeout=30 ) if response.ok: response_data = response.json() error_data: Optional[str] = None if "error" in response_data and "data" in response_data["error"]: error_data = response_data["error"]["data"] elif "result" in response_data: # Ganache-cli error_data = response_data["result"] if error_data: if "0x" in error_data: return parse_revert_data( HexBytes(error_data[error_data.find("0x") :]) ) raise CannotEstimateGas( f"Received {response.status_code} - {response.content} from ethereum node" ) def estimate_tx_gas_with_web3(self, to: str, value: int, data: EthereumData) -> int: """ :param to: :param value: :param data: :return: Estimation using web3 `estimate_gas` """ try: return self.ethereum_client.estimate_gas( to, from_=self.address, value=value, data=data ) except ValueError as exc: raise CannotEstimateGas( f"Cannot estimate gas with `eth_estimateGas`: {exc}" ) from exc def estimate_tx_gas_by_trying( self, to: str, value: int, data: Union[bytes, str], operation: int ): """ Try to get an estimation with Safe's `requiredTxGas`. If estimation if successful, try to set a gas limit and estimate again. If gas estimation is ok, same gas estimation should be returned, if it's less than required estimation will not be completed, so estimation was not accurate and gas limit needs to be increased. :param to: :param value: :param data: :param operation: :return: Estimated gas calling `requiredTxGas` setting a gas limit and checking if `eth_call` is successful :raises: CannotEstimateGas """ if not data: data = b"" elif isinstance(data, str): data = HexBytes(data) gas_estimated = self.estimate_tx_gas_with_safe(to, value, data, operation) block_gas_limit: Optional[int] = None base_gas: Optional[int] = self.ethereum_client.estimate_data_gas(data) for i in range( 1, 30 ): # Make sure tx can be executed, fixing for example 63/64th problem try: self.estimate_tx_gas_with_safe( to, value, data, operation, gas_limit=gas_estimated + base_gas + 32000, ) return gas_estimated except CannotEstimateGas: logger.warning( "Safe=%s - Found 63/64 problem gas-estimated=%d to=%s data=%s", self.address, gas_estimated, to, data.hex(), ) block_gas_limit = ( block_gas_limit or self.w3.eth.get_block("latest", full_transactions=False)[ "gasLimit" ] ) gas_estimated = math.floor((1 + i * 0.03) * gas_estimated) if gas_estimated >= block_gas_limit: return block_gas_limit return gas_estimated def estimate_tx_gas(self, to: str, value: int, data: bytes, operation: int) -> int: """ Estimate tx gas. Use `requiredTxGas` on the Safe contract and fallbacks to `eth_estimateGas` if that method fails. Note: `eth_estimateGas` cannot estimate delegate calls :param to: :param value: :param data: :param operation: :return: Estimated gas for Safe inner tx :raises: CannotEstimateGas """ # Costs to route through the proxy and nested calls PROXY_GAS = 1000 # https://github.com/ethereum/solidity/blob/dfe3193c7382c80f1814247a162663a97c3f5e67/libsolidity/codegen/ExpressionCompiler.cpp#L1764 # This was `false` before solc 0.4.21 -> `m_context.evmVersion().canOverchargeGasForCall()` # So gas needed by caller will be around 35k OLD_CALL_GAS = 35000 # Web3 `estimate_gas` estimates less gas WEB3_ESTIMATION_OFFSET = 20000 ADDITIONAL_GAS = PROXY_GAS + OLD_CALL_GAS try: return ( self.estimate_tx_gas_by_trying(to, value, data, operation) + ADDITIONAL_GAS ) except CannotEstimateGas: return ( self.estimate_tx_gas_with_web3(to, value, data) + ADDITIONAL_GAS + WEB3_ESTIMATION_OFFSET ) def estimate_tx_operational_gas(self, data_bytes_length: int) -> int: """ DEPRECATED. `estimate_tx_base_gas` already includes this. Estimates the gas for the verification of the signatures and other safe related tasks before and after executing a transaction. Calculation will be the sum of: - Base cost of 15000 gas - 100 of gas per word of `data_bytes` - Validate the signatures 5000 * threshold (ecrecover for ecdsa ~= 4K gas) :param data_bytes_length: Length of the data (in bytes, so `len(HexBytes('0x12'))` would be `1` :return: gas costs per signature * threshold of Safe """ threshold = self.retrieve_threshold() return 15000 + data_bytes_length // 32 * 100 + 5000 * threshold def get_message_hash(self, message: Union[str, Hash32]) -> Hash32: """ Return hash of a message that can be signed by owners. :param message: Message that should be hashed :return: Message hash """ if isinstance(message, str): message = message.encode() message_hash = fast_keccak(message) safe_message_hash = Web3.keccak( encode_abi( ["bytes32", "bytes32"], [self.SAFE_MESSAGE_TYPEHASH, message_hash] ) ) return Web3.keccak( encode_abi_packed( ["bytes1", "bytes1", "bytes32", "bytes32"], [ bytes.fromhex("19"), bytes.fromhex("01"), self.domain_separator, safe_message_hash, ], ) ) def retrieve_all_info( self, block_identifier: Optional[BlockIdentifier] = "latest" ) -> SafeInfo: """ Get all Safe info in the same batch call. :param block_identifier: :return: :raises: CannotRetrieveSafeInfoException """ try: contract = self.contract master_copy = self.retrieve_master_copy_address() fallback_handler = self.retrieve_fallback_handler() guard = self.retrieve_guard() results = self.ethereum_client.batch_call( [ contract.functions.getModulesPaginated( SENTINEL_ADDRESS, 20 ), # Does not exist in version < 1.1.1 contract.functions.nonce(), contract.functions.getOwners(), contract.functions.getThreshold(), contract.functions.VERSION(), ], from_address=self.address, block_identifier=block_identifier, raise_exception=False, ) modules_response, nonce, owners, threshold, version = results if modules_response: modules, next_module = modules_response if ( not modules_response or next_module != SENTINEL_ADDRESS ): # < 1.1.1 or still more elements in the list modules = self.retrieve_modules() return SafeInfo( self.address, fallback_handler, guard, master_copy, modules, nonce, owners, threshold, version, ) except (ValueError, BadFunctionCallOutput) as e: raise CannotRetrieveSafeInfoException(self.address) from e def retrieve_code(self) -> HexBytes: return self.w3.eth.get_code(self.address) def retrieve_fallback_handler( self, block_identifier: Optional[BlockIdentifier] = "latest" ) -> ChecksumAddress: address = self.ethereum_client.w3.eth.get_storage_at( self.address, self.FALLBACK_HANDLER_STORAGE_SLOT, block_identifier=block_identifier, )[-20:].rjust(20, b"\0") if len(address) == 20: return fast_bytes_to_checksum_address(address) else: return NULL_ADDRESS def retrieve_guard( self, block_identifier: Optional[BlockIdentifier] = "latest" ) -> ChecksumAddress: address = self.ethereum_client.w3.eth.get_storage_at( self.address, self.GUARD_STORAGE_SLOT, block_identifier=block_identifier )[-20:].rjust(20, b"\0") if len(address) == 20: return fast_bytes_to_checksum_address(address) else: return NULL_ADDRESS def retrieve_master_copy_address( self, block_identifier: Optional[BlockIdentifier] = "latest" ) -> ChecksumAddress: address = self.w3.eth.get_storage_at( self.address, "0x00", block_identifier=block_identifier )[-20:].rjust(20, b"\0") return fast_bytes_to_checksum_address(address) def retrieve_modules( self, pagination: Optional[int] = 50, block_identifier: Optional[BlockIdentifier] = "latest", ) -> List[str]: """ :param pagination: Number of modules to get per request :param block_identifier: :return: List of module addresses """ try: # Contracts with Safe version < 1.1.0 were not paginated contract = get_safe_V1_0_0_contract( self.ethereum_client.w3, address=self.address ) return contract.functions.getModules().call( block_identifier=block_identifier ) except BadFunctionCallOutput: pass contract = self.contract address = SENTINEL_ADDRESS all_modules: List[str] = [] while True: (modules, address) = contract.functions.getModulesPaginated( address, pagination ).call(block_identifier=block_identifier) all_modules.extend(modules) if address == SENTINEL_ADDRESS: break else: all_modules.append(address) return all_modules def retrieve_is_hash_approved( self, owner: str, safe_hash: bytes, block_identifier: Optional[BlockIdentifier] = "latest", ) -> bool: return ( self.contract.functions.approvedHashes(owner, safe_hash).call( block_identifier=block_identifier ) == 1 ) def retrieve_is_message_signed( self, message_hash: bytes, block_identifier: Optional[BlockIdentifier] = "latest", ) -> bool: return self.contract.functions.signedMessages(message_hash).call( block_identifier=block_identifier ) def retrieve_is_owner( self, owner: str, block_identifier: Optional[BlockIdentifier] = "latest" ) -> bool: return self.contract.functions.isOwner(owner).call( block_identifier=block_identifier ) def retrieve_nonce( self, block_identifier: Optional[BlockIdentifier] = "latest" ) -> int: return self.contract.functions.nonce().call(block_identifier=block_identifier) def retrieve_owners( self, block_identifier: Optional[BlockIdentifier] = "latest" ) -> List[str]: return self.contract.functions.getOwners().call( block_identifier=block_identifier ) def retrieve_threshold( self, block_identifier: Optional[BlockIdentifier] = "latest" ) -> int: return self.contract.functions.getThreshold().call( block_identifier=block_identifier ) def retrieve_version( self, block_identifier: Optional[BlockIdentifier] = "latest" ) -> str: return self.contract.functions.VERSION().call(block_identifier=block_identifier) def build_multisig_tx( self, to: str, value: int, data: bytes, operation: int = SafeOperation.CALL.value, safe_tx_gas: int = 0, base_gas: int = 0, gas_price: int = 0, gas_token: str = NULL_ADDRESS, refund_receiver: str = NULL_ADDRESS, signatures: bytes = b"", safe_nonce: Optional[int] = None, safe_version: Optional[str] = None, ) -> SafeTx: """ Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction. The fees are always transfered, even if the user transaction fails :param to: Destination address of Safe transaction :param value: Ether value of Safe transaction :param data: Data payload of Safe transaction :param operation: Operation type of Safe transaction :param safe_tx_gas: Gas that should be used for the Safe transaction :param base_gas: Gas costs for that are independent of the transaction execution (e.g. base transaction fee, signature check, payment of the refund) :param gas_price: Gas price that should be used for the payment calculation :param gas_token: Token address (or `0x000..000` if ETH) that is used for the payment :param refund_receiver: Address of receiver of gas payment (or `0x000..000` if tx.origin). :param signatures: Packed signature data ({bytes32 r}{bytes32 s}{uint8 v}) :param safe_nonce: Nonce of the safe (to calculate hash) :param safe_version: Safe version (to calculate hash) :return: """ if safe_nonce is None: safe_nonce = self.retrieve_nonce() safe_version = safe_version or self.retrieve_version() return SafeTx( self.ethereum_client, self.address, to, value, data, operation, safe_tx_gas, base_gas, gas_price, gas_token, refund_receiver, signatures=signatures, safe_nonce=safe_nonce, safe_version=safe_version, ) def send_multisig_tx( self, to: str, value: int, data: bytes, operation: int, safe_tx_gas: int, base_gas: int, gas_price: int, gas_token: str, refund_receiver: str, signatures: bytes, tx_sender_private_key: str, tx_gas=None, tx_gas_price=None, block_identifier: Optional[BlockIdentifier] = "latest", ) -> EthereumTxSent: """ Build and send Safe tx :param to: :param value: :param data: :param operation: :param safe_tx_gas: :param base_gas: :param gas_price: :param gas_token: :param refund_receiver: :param signatures: :param tx_sender_private_key: :param tx_gas: Gas for the external tx. If not, `(safe_tx_gas + data_gas) * 2` will be used :param tx_gas_price: Gas price of the external tx. If not, `gas_price` will be used :param block_identifier: :return: Tuple(tx_hash, tx) :raises: InvalidMultisigTx: If user tx cannot go through the Safe """ safe_tx = self.build_multisig_tx( to, value, data, operation, safe_tx_gas, base_gas, gas_price, gas_token, refund_receiver, signatures, ) tx_sender_address = Account.from_key(tx_sender_private_key).address safe_tx.call( tx_sender_address=tx_sender_address, block_identifier=block_identifier ) tx_hash, tx = safe_tx.execute( tx_sender_private_key=tx_sender_private_key, tx_gas=tx_gas, tx_gas_price=tx_gas_price, block_identifier=block_identifier, ) return EthereumTxSent(tx_hash, tx, None)
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/safe/safe.py
0.890425
0.166506
safe.py
pypi
from logging import getLogger from typing import Optional from eth_account.signers.local import LocalAccount from eth_typing import ChecksumAddress from web3.contract import Contract from gnosis.eth import EthereumClient, EthereumTxSent from gnosis.eth.contracts import ( get_paying_proxy_deployed_bytecode, get_proxy_1_0_0_deployed_bytecode, get_proxy_1_1_1_deployed_bytecode, get_proxy_1_1_1_mainnet_deployed_bytecode, get_proxy_1_3_0_deployed_bytecode, get_proxy_factory_contract, get_proxy_factory_V1_0_0_contract, get_proxy_factory_V1_1_1_contract, ) from gnosis.eth.utils import compare_byte_code, fast_is_checksum_address try: from functools import cache except ImportError: from functools import lru_cache cache = lru_cache(maxsize=None) logger = getLogger(__name__) class ProxyFactory: def __init__(self, address: ChecksumAddress, ethereum_client: EthereumClient): assert fast_is_checksum_address(address), ( "%s proxy factory address not valid" % address ) self.address = address self.ethereum_client = ethereum_client self.w3 = ethereum_client.w3 @staticmethod def _deploy_proxy_factory_contract( ethereum_client: EthereumClient, deployer_account: LocalAccount, contract: Contract, ) -> EthereumTxSent: tx = contract.constructor().build_transaction( {"from": deployer_account.address} ) tx_hash = ethereum_client.send_unsigned_transaction( tx, private_key=deployer_account.key ) tx_receipt = ethereum_client.get_transaction_receipt(tx_hash, timeout=120) assert tx_receipt assert tx_receipt["status"] contract_address = tx_receipt["contractAddress"] logger.info( "Deployed and initialized Proxy Factory Contract=%s by %s", contract_address, deployer_account.address, ) return EthereumTxSent(tx_hash, tx, contract_address) @classmethod def deploy_proxy_factory_contract( cls, ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy proxy factory contract last version (v1.3.0) :param ethereum_client: :param deployer_account: Ethereum Account :return: deployed contract address """ proxy_factory_contract = get_proxy_factory_contract(ethereum_client.w3) return cls._deploy_proxy_factory_contract( ethereum_client, deployer_account, proxy_factory_contract ) @classmethod def deploy_proxy_factory_contract_v1_1_1( cls, ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy proxy factory contract v1.1.1 :param ethereum_client: :param deployer_account: Ethereum Account :return: deployed contract address """ proxy_factory_contract = get_proxy_factory_V1_1_1_contract(ethereum_client.w3) return cls._deploy_proxy_factory_contract( ethereum_client, deployer_account, proxy_factory_contract ) @classmethod def deploy_proxy_factory_contract_v1_0_0( cls, ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy proxy factory contract v1.0.0 :param ethereum_client: :param deployer_account: Ethereum Account :return: deployed contract address """ proxy_factory_contract = get_proxy_factory_V1_0_0_contract(ethereum_client.w3) return cls._deploy_proxy_factory_contract( ethereum_client, deployer_account, proxy_factory_contract ) def check_proxy_code(self, address: ChecksumAddress) -> bool: """ Check if proxy is valid :param address: Ethereum address to check :return: True if proxy is valid, False otherwise """ deployed_proxy_code = self.w3.eth.get_code(address) proxy_code_fns = ( get_proxy_1_3_0_deployed_bytecode, get_proxy_1_1_1_deployed_bytecode, get_proxy_1_1_1_mainnet_deployed_bytecode, get_proxy_1_0_0_deployed_bytecode, get_paying_proxy_deployed_bytecode, self.get_proxy_runtime_code, ) for proxy_code_fn in proxy_code_fns: if compare_byte_code(deployed_proxy_code, proxy_code_fn()): return True return False def deploy_proxy_contract( self, deployer_account: LocalAccount, master_copy: ChecksumAddress, initializer: bytes = b"", gas: Optional[int] = None, gas_price: Optional[int] = None, ) -> EthereumTxSent: """ Deploy proxy contract via ProxyFactory using `createProxy` function :param deployer_account: Ethereum account :param master_copy: Address the proxy will point at :param initializer: Initializer :param gas: Gas :param gas_price: Gas Price :return: EthereumTxSent """ proxy_factory_contract = self.get_contract() create_proxy_fn = proxy_factory_contract.functions.createProxy( master_copy, initializer ) tx_parameters = {"from": deployer_account.address} contract_address = create_proxy_fn.call(tx_parameters) if gas_price is not None: tx_parameters["gasPrice"] = gas_price if gas is not None: tx_parameters["gas"] = gas tx = create_proxy_fn.build_transaction(tx_parameters) # Auto estimation of gas does not work. We use a little more gas just in case tx["gas"] = tx["gas"] + 50000 tx_hash = self.ethereum_client.send_unsigned_transaction( tx, private_key=deployer_account.key ) return EthereumTxSent(tx_hash, tx, contract_address) def deploy_proxy_contract_with_nonce( self, deployer_account: LocalAccount, master_copy: ChecksumAddress, initializer: bytes, salt_nonce: int, gas: Optional[int] = None, gas_price: Optional[int] = None, nonce: Optional[int] = None, ) -> EthereumTxSent: """ Deploy proxy contract via Proxy Factory using `createProxyWithNonce` (create2) :param deployer_account: Ethereum account :param master_copy: Address the proxy will point at :param initializer: Data for safe creation :param salt_nonce: Uint256 for `create2` salt :param gas: Gas :param gas_price: Gas Price :param nonce: Nonce :return: Tuple(tx-hash, tx, deployed contract address) """ proxy_factory_contract = self.get_contract() create_proxy_fn = proxy_factory_contract.functions.createProxyWithNonce( master_copy, initializer, salt_nonce ) tx_parameters = {"from": deployer_account.address} contract_address = create_proxy_fn.call(tx_parameters) if gas_price is not None: tx_parameters["gasPrice"] = gas_price if gas is not None: tx_parameters["gas"] = gas if nonce is not None: tx_parameters["nonce"] = nonce tx = create_proxy_fn.build_transaction(tx_parameters) # Auto estimation of gas does not work. We use a little more gas just in case tx["gas"] = tx["gas"] + 50000 tx_hash = self.ethereum_client.send_unsigned_transaction( tx, private_key=deployer_account.key ) return EthereumTxSent(tx_hash, tx, contract_address) def get_contract(self, address: Optional[ChecksumAddress] = None): address = address or self.address return get_proxy_factory_contract(self.ethereum_client.w3, address) @cache def get_proxy_runtime_code(self, address: Optional[ChecksumAddress] = None): """ Get runtime code for current proxy factory """ address = address or self.address return self.get_contract(address=address).functions.proxyRuntimeCode().call()
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/safe/proxy_factory.py
0.917096
0.158435
proxy_factory.py
pypi
from rest_framework import serializers from rest_framework.exceptions import ValidationError from gnosis.eth.constants import ( SIGNATURE_R_MAX_VALUE, SIGNATURE_R_MIN_VALUE, SIGNATURE_S_MAX_VALUE, SIGNATURE_S_MIN_VALUE, SIGNATURE_V_MAX_VALUE, SIGNATURE_V_MIN_VALUE, ) from gnosis.eth.django.serializers import EthereumAddressField, HexadecimalField from .safe import SafeOperation class SafeSignatureSerializer(serializers.Serializer): """ When using safe signatures `v` can have more values """ v = serializers.IntegerField(min_value=0) r = serializers.IntegerField(min_value=0) s = serializers.IntegerField(min_value=0) def validate_v(self, v): if v == 0: # Contract signature return v elif v == 1: # Approved hash return v elif v > 30 and self.check_v(v - 4): # Support eth_sign return v elif self.check_v(v): return v else: raise serializers.ValidationError( "v should be 0, 1 or be in %d-%d" % (SIGNATURE_V_MIN_VALUE, SIGNATURE_V_MAX_VALUE) ) def validate(self, data): super().validate(data) v = data["v"] r = data["r"] s = data["s"] if v not in [0, 1]: # Disable checks for `r` and `s` if v is 0 or 1 if not self.check_r(r): raise serializers.ValidationError("r not valid") elif not self.check_s(s): raise serializers.ValidationError("s not valid") return data def check_v(self, v): return SIGNATURE_V_MIN_VALUE <= v <= SIGNATURE_V_MAX_VALUE def check_r(self, r): return SIGNATURE_R_MIN_VALUE <= r <= SIGNATURE_R_MAX_VALUE def check_s(self, s): return SIGNATURE_S_MIN_VALUE <= s <= SIGNATURE_S_MAX_VALUE class SafeMultisigEstimateTxSerializer(serializers.Serializer): safe = EthereumAddressField() to = EthereumAddressField() value = serializers.IntegerField(min_value=0) data = HexadecimalField(default=None, allow_null=True, allow_blank=True) operation = serializers.IntegerField(min_value=0) gas_token = EthereumAddressField( default=None, allow_null=True, allow_zero_address=True ) def validate_operation(self, value): try: return SafeOperation(value).value except ValueError: raise ValidationError("Unknown operation") def validate(self, data): super().validate(data) if not data["to"] and not data["data"]: raise ValidationError("`data` and `to` cannot both be null") if not data["to"] and not data["data"]: raise ValidationError("`data` and `to` cannot both be null") if data["operation"] == SafeOperation.CREATE.value: raise ValidationError( "Operation CREATE not supported. Please use Gnosis Safe CreateLib" ) # if data['to']: # raise ValidationError('Operation is Create, but `to` was provided') # elif not data['data']: # raise ValidationError('Operation is Create, but not `data` was provided') return data class SafeMultisigTxSerializer(SafeMultisigEstimateTxSerializer): """ DEPRECATED, use `SafeMultisigTxSerializerV1` instead """ safe_tx_gas = serializers.IntegerField(min_value=0) data_gas = serializers.IntegerField(min_value=0) gas_price = serializers.IntegerField(min_value=0) refund_receiver = EthereumAddressField( default=None, allow_null=True, allow_zero_address=True ) nonce = serializers.IntegerField(min_value=0) class SafeMultisigTxSerializerV1(SafeMultisigEstimateTxSerializer): """ Version 1.0.0 of the Safe changes `data_gas` to `base_gas` """ safe_tx_gas = serializers.IntegerField(min_value=0) base_gas = serializers.IntegerField(min_value=0) gas_price = serializers.IntegerField(min_value=0) refund_receiver = EthereumAddressField( default=None, allow_null=True, allow_zero_address=True ) nonce = serializers.IntegerField(min_value=0)
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/safe/serializers.py
0.78838
0.331039
serializers.py
pypi
import math import os from logging import getLogger from typing import Any, Dict, List, Optional, Tuple import rlp from eth.vm.forks.frontier.transactions import FrontierTransaction from eth_keys.exceptions import BadSignature from hexbytes import HexBytes from web3 import Web3 from web3.contract import ContractConstructor from gnosis.eth.constants import GAS_CALL_DATA_BYTE, NULL_ADDRESS, SECPK1_N from gnosis.eth.contracts import ( get_erc20_contract, get_paying_proxy_contract, get_safe_V0_0_1_contract, ) from gnosis.eth.utils import ( fast_is_checksum_address, fast_to_checksum_address, mk_contract_address, ) logger = getLogger(__name__) class InvalidERC20Token(Exception): pass class SafeCreationTx: def __init__( self, w3: Web3, owners: List[str], threshold: int, signature_s: int, master_copy: str, gas_price: int, funder: Optional[str], payment_token: Optional[str] = None, payment_token_eth_value: float = 1.0, fixed_creation_cost: Optional[int] = None, ): """ Prepare Safe creation :param w3: Web3 instance :param owners: Owners of the Safe :param threshold: Minimum number of users required to operate the Safe :param signature_s: Random s value for ecdsa signature :param master_copy: Safe master copy address :param gas_price: Gas Price :param funder: Address to refund when the Safe is created. Address(0) if no need to refund :param payment_token: Payment token instead of paying the funder with ether. If None Ether will be used :param payment_token_eth_value: Value of payment token per 1 Ether :param fixed_creation_cost: Fixed creation cost of Safe (Wei) """ assert 0 < threshold <= len(owners) funder = funder or NULL_ADDRESS payment_token = payment_token or NULL_ADDRESS assert fast_is_checksum_address(master_copy) assert fast_is_checksum_address(funder) assert fast_is_checksum_address(payment_token) self.w3 = w3 self.owners = owners self.threshold = threshold self.s = signature_s self.master_copy = master_copy self.gas_price = gas_price self.funder = funder self.payment_token = payment_token self.payment_token_eth_value = payment_token_eth_value self.fixed_creation_cost = fixed_creation_cost # Get bytes for `setup(address[] calldata _owners, uint256 _threshold, address to, bytes calldata data)` # This initializer will be passed to the proxy and will be called right after proxy is deployed safe_setup_data: bytes = self._get_initial_setup_safe_data(owners, threshold) # Calculate gas based on experience of previous deployments of the safe calculated_gas: int = self._calculate_gas( owners, safe_setup_data, payment_token ) # Estimate gas using web3 estimated_gas: int = self._estimate_gas( master_copy, safe_setup_data, funder, payment_token ) self.gas = max(calculated_gas, estimated_gas) # Payment will be safe deploy cost + transfer fees for sending ether to the deployer self.payment = self._calculate_refund_payment( self.gas, gas_price, fixed_creation_cost, payment_token_eth_value ) self.tx_dict: Dict[str, Any] = self._build_proxy_contract_creation_tx( master_copy=master_copy, initializer=safe_setup_data, funder=funder, payment_token=payment_token, payment=self.payment, gas=self.gas, gas_price=gas_price, ) self.tx_pyethereum: FrontierTransaction = ( self._build_contract_creation_tx_with_valid_signature(self.tx_dict, self.s) ) self.tx_raw = rlp.encode(self.tx_pyethereum) self.tx_hash = self.tx_pyethereum.hash self.deployer_address = fast_to_checksum_address(self.tx_pyethereum.sender) self.safe_address = mk_contract_address(self.tx_pyethereum.sender, 0) self.v = self.tx_pyethereum.v self.r = self.tx_pyethereum.r self.safe_setup_data = safe_setup_data assert mk_contract_address(self.deployer_address, nonce=0) == self.safe_address @property def payment_ether(self): return self.gas * self.gas_price @staticmethod def find_valid_random_signature(s: int) -> Tuple[int, int]: """ Find v and r valid values for a given s :param s: random value :return: v, r """ for _ in range(10000): r = int(os.urandom(31).hex(), 16) v = (r % 2) + 27 if r < SECPK1_N: tx = FrontierTransaction(0, 1, 21000, b"", 0, b"", v=v, r=r, s=s) try: tx.sender return v, r except (BadSignature, ValueError): logger.debug("Cannot find signature with v=%d r=%d s=%d", v, r, s) raise ValueError("Valid signature not found with s=%d", s) @staticmethod def _calculate_gas( owners: List[str], safe_setup_data: bytes, payment_token: str ) -> int: """ Calculate gas manually, based on tests of previosly deployed safes :param owners: Safe owners :param safe_setup_data: Data for proxy setup :param payment_token: If payment token, we will need more gas to transfer and maybe storage if first time :return: total gas needed for deployment """ # TODO Do gas calculation estimating the call instead this magic base_gas = 60580 # Transaction standard gas # If we already have the token, we don't have to pay for storage, so it will be just 5K instead of 20K. # The other 1K is for overhead of making the call if payment_token != NULL_ADDRESS: payment_token_gas = 55000 else: payment_token_gas = 0 data_gas = GAS_CALL_DATA_BYTE * len(safe_setup_data) # Data gas gas_per_owner = 18020 # Magic number calculated by testing and averaging owners return ( base_gas + data_gas + payment_token_gas + 270000 + len(owners) * gas_per_owner ) @staticmethod def _calculate_refund_payment( gas: int, gas_price: int, fixed_creation_cost: Optional[int], payment_token_eth_value: float, ) -> int: if fixed_creation_cost is None: # Payment will be safe deploy cost + transfer fees for sending ether to the deployer base_payment: int = (gas + 23000) * gas_price # Calculate payment for tokens using the conversion (if used) return math.ceil(base_payment / payment_token_eth_value) else: return fixed_creation_cost def _build_proxy_contract_creation_constructor( self, master_copy: str, initializer: bytes, funder: str, payment_token: str, payment: int, ) -> ContractConstructor: """ :param master_copy: Master Copy of Gnosis Safe already deployed :param initializer: Data initializer to send to GnosisSafe setup method :param funder: Address that should get the payment (if payment set) :param payment_token: Address if a token is used. If not set, 0x0 will be ether :param payment: Payment :return: Transaction dictionary """ if not funder or funder == NULL_ADDRESS: funder = NULL_ADDRESS payment = 0 return get_paying_proxy_contract(self.w3).constructor( master_copy, initializer, funder, payment_token, payment ) def _build_proxy_contract_creation_tx( self, master_copy: str, initializer: bytes, funder: str, payment_token: str, payment: int, gas: int, gas_price: int, nonce: int = 0, ): """ :param master_copy: Master Copy of Gnosis Safe already deployed :param initializer: Data initializer to send to GnosisSafe setup method :param funder: Address that should get the payment (if payment set) :param payment_token: Address if a token is used. If not set, 0x0 will be ether :param payment: Payment :return: Transaction dictionary """ return self._build_proxy_contract_creation_constructor( master_copy, initializer, funder, payment_token, payment ).build_transaction( { "gas": gas, "gasPrice": gas_price, "nonce": nonce, } ) def _build_contract_creation_tx_with_valid_signature( self, tx_dict: Dict[str, Any], s: int ) -> FrontierTransaction: """ Use pyethereum `Transaction` to generate valid tx using a random signature :param tx_dict: Web3 tx dictionary :param s: Signature s value :return: PyEthereum creation tx for the proxy contract """ zero_address = HexBytes("0x" + "0" * 40) f_address = HexBytes("0x" + "f" * 40) nonce = tx_dict["nonce"] gas_price = tx_dict["gasPrice"] gas = tx_dict["gas"] to = tx_dict.get("to", b"") # Contract creation should always have `to` empty value = tx_dict["value"] data = tx_dict["data"] for _ in range(100): try: v, r = self.find_valid_random_signature(s) contract_creation_tx = FrontierTransaction( nonce, gas_price, gas, to, value, HexBytes(data), v=v, r=r, s=s ) sender_address = contract_creation_tx.sender contract_address: bytes = HexBytes( mk_contract_address(sender_address, nonce) ) if sender_address in (zero_address, f_address) or contract_address in ( zero_address, f_address, ): raise ValueError("Invalid transaction") return contract_creation_tx except BadSignature: pass raise ValueError("Valid signature not found with s=%d", s) def _estimate_gas( self, master_copy: str, initializer: bytes, funder: str, payment_token: str ) -> int: """ Gas estimation done using web3 and calling the node Payment cannot be estimated, as no ether is in the address. So we add some gas later. :param master_copy: Master Copy of Gnosis Safe already deployed :param initializer: Data initializer to send to GnosisSafe setup method :param funder: Address that should get the payment (if payment set) :param payment_token: Address if a token is used. If not set, 0x0 will be ether :return: Total gas estimation """ # Estimate the contract deployment. We cannot estimate the refunding, as the safe address has not any fund gas: int = self._build_proxy_contract_creation_constructor( master_copy, initializer, funder, payment_token, 0 ).estimate_gas() # We estimate the refund as a new tx if payment_token == NULL_ADDRESS: # Same cost to send 1 ether than 1000 gas += self.w3.eth.estimate_gas({"to": funder, "value": 1}) else: # Top should be around 52000 when storage is needed (funder no previous owner of token), # we use value 1 as we are simulating an internal call, and in that calls you don't pay for the data. # If it was a new tx sending 5000 tokens would be more expensive than sending 1 because of data costs try: gas += ( get_erc20_contract(self.w3, payment_token) .functions.transfer(funder, 1) .estimate_gas({"from": payment_token}) ) except ValueError as exc: if "transfer amount exceeds balance" in str(exc): return 70000 raise InvalidERC20Token from exc return gas def _get_initial_setup_safe_data(self, owners: List[str], threshold: int) -> bytes: return ( get_safe_V0_0_1_contract(self.w3, self.master_copy) .functions.setup( owners, threshold, NULL_ADDRESS, # Contract address for optional delegate call b"", # Data payload for optional delegate call ) .build_transaction( { "gas": 1, "gasPrice": 1, } )["data"] )
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/safe/safe_creation_tx.py
0.798344
0.373476
safe_creation_tx.py
pypi
from typing import List, Tuple, Union from eth_keys import keys from eth_keys.exceptions import BadSignature from hexbytes import HexBytes from gnosis.eth.constants import NULL_ADDRESS def signature_split( signatures: Union[bytes, str], pos: int = 0 ) -> Tuple[int, int, int]: """ :param signatures: signatures in form of {bytes32 r}{bytes32 s}{uint8 v} :param pos: position of the signature :return: Tuple with v, r, s """ signatures = HexBytes(signatures) signature_pos = 65 * pos if len(signatures[signature_pos : signature_pos + 65]) < 65: raise ValueError(f"Signature must be at least 65 bytes {signatures.hex()}") r = int.from_bytes(signatures[signature_pos : 32 + signature_pos], "big") s = int.from_bytes(signatures[32 + signature_pos : 64 + signature_pos], "big") v = signatures[64 + signature_pos] return v, r, s def signature_to_bytes(v: int, r: int, s: int) -> bytes: """ Convert ecdsa signature to bytes :param v: :param r: :param s: :return: signature in form of {bytes32 r}{bytes32 s}{uint8 v} """ byte_order = "big" return ( r.to_bytes(32, byteorder=byte_order) + s.to_bytes(32, byteorder=byte_order) + v.to_bytes(1, byteorder=byte_order) ) def signatures_to_bytes(signatures: List[Tuple[int, int, int]]) -> bytes: """ Convert signatures to bytes :param signatures: list of tuples(v, r, s) :return: 65 bytes per signature """ return b"".join([signature_to_bytes(v, r, s) for v, r, s in signatures]) def get_signing_address(signed_hash: Union[bytes, str], v: int, r: int, s: int) -> str: """ :return: checksummed ethereum address, for example `0x568c93675A8dEb121700A6FAdDdfE7DFAb66Ae4A` :rtype: str or `NULL_ADDRESS` if signature is not valid """ try: public_key = keys.ecdsa_recover(signed_hash, keys.Signature(vrs=(v - 27, r, s))) return public_key.to_checksum_address() except BadSignature: return NULL_ADDRESS
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/safe/signatures.py
0.923049
0.493958
signatures.py
pypi
from urllib.parse import urljoin import requests from eth_typing import ChecksumAddress, HexStr from gnosis.eth.ethereum_client import EthereumNetwork from .. import SafeTx from ..signatures import signature_split from .base_api import SafeAPIException, SafeBaseAPI try: from typing import TypedDict except ImportError: from typing_extensions import TypedDict class RelayEstimation(TypedDict): safeTxGas: int baseGas: int gasPrice: int lastUsedNonce: int gasToken: ChecksumAddress refundReceiver: ChecksumAddress class RelaySentTransaction(TypedDict): safeTxHash: HexStr txHash: HexStr class RelayServiceApi(SafeBaseAPI): URL_BY_NETWORK = { EthereumNetwork.GOERLI: "https://safe-relay.goerli.gnosis.io/", EthereumNetwork.MAINNET: "https://safe-relay.gnosis.io", EthereumNetwork.RINKEBY: "https://safe-relay.rinkeby.gnosis.io", } def send_transaction( self, safe_address: str, safe_tx: SafeTx ) -> RelaySentTransaction: url = urljoin(self.base_url, f"/api/v1/safes/{safe_address}/transactions/") signatures = [] for i in range(len(safe_tx.signatures) // 65): v, r, s = signature_split(safe_tx.signatures, i) signatures.append( { "v": v, "r": r, "s": s, } ) data = { "to": safe_tx.to, "value": safe_tx.value, "data": safe_tx.data.hex() if safe_tx.data else None, "operation": safe_tx.operation, "gasToken": safe_tx.gas_token, "safeTxGas": safe_tx.safe_tx_gas, "dataGas": safe_tx.base_gas, "gasPrice": safe_tx.gas_price, "refundReceiver": safe_tx.refund_receiver, "nonce": safe_tx.safe_nonce, "signatures": signatures, } response = requests.post(url, json=data) if not response.ok: raise SafeAPIException(f"Error posting transaction: {response.content}") else: return RelaySentTransaction(response.json()) def get_estimation(self, safe_address: str, safe_tx: SafeTx) -> RelayEstimation: """ :param safe_address: :param safe_tx: :return: RelayEstimation """ url = urljoin( self.base_url, f"/api/v2/safes/{safe_address}/transactions/estimate/" ) data = { "to": safe_tx.to, "value": safe_tx.value, "data": safe_tx.data.hex() if safe_tx.data else None, "operation": safe_tx.operation, "gasToken": safe_tx.gas_token, } response = requests.post(url, json=data) if not response.ok: raise SafeAPIException(f"Error posting transaction: {response.content}") else: response_json = response.json() # Convert values to int for key in ("safeTxGas", "baseGas", "gasPrice"): response_json[key] = int(response_json[key]) return RelayEstimation(response_json)
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/safe/api/relay_service_api.py
0.676406
0.207556
relay_service_api.py
pypi
import logging import time from typing import Any, Dict, List, Optional, Tuple, Union from eth_account.signers.local import LocalAccount from eth_typing import HexStr from hexbytes import HexBytes from web3 import Web3 from gnosis.eth import EthereumNetwork from gnosis.safe import SafeTx from .base_api import SafeAPIException, SafeBaseAPI logger = logging.getLogger(__name__) class TransactionServiceApi(SafeBaseAPI): URL_BY_NETWORK = { EthereumNetwork.ARBITRUM: "https://safe-transaction-arbitrum.safe.global", EthereumNetwork.AURORA: "https://safe-transaction-aurora.safe.global", EthereumNetwork.AVALANCHE: "https://safe-transaction-avalanche.safe.global", EthereumNetwork.BINANCE: "https://safe-transaction-bsc.safe.global", EthereumNetwork.ENERGY_WEB_CHAIN: "https://safe-transaction-ewc.safe.global", EthereumNetwork.GOERLI: "https://safe-transaction-goerli.safe.global", EthereumNetwork.MAINNET: "https://safe-transaction-mainnet.safe.global", EthereumNetwork.MATIC: "https://safe-transaction-polygon.safe.global", EthereumNetwork.OPTIMISTIC: "https://safe-transaction-optimism.safe.global", EthereumNetwork.VOLTA: "https://safe-transaction-volta.safe.global", EthereumNetwork.XDAI: "https://safe-transaction-xdai.safe.global", } @classmethod def create_delegate_message_hash(cls, delegate_address: str) -> str: totp = int(time.time()) // 3600 hash_to_sign = Web3.keccak(text=delegate_address + str(totp)) return hash_to_sign @classmethod def data_decoded_to_text(cls, data_decoded: Dict[str, Any]) -> Optional[str]: """ Decoded data decoded to text :param data_decoded: :return: """ if not data_decoded: return None method = data_decoded["method"] parameters = data_decoded.get("parameters", []) text = "" for ( parameter ) in parameters: # Multisend or executeTransaction from another Safe if "decodedValue" in parameter: text += ( method + ":\n - " + "\n - ".join( [ cls.data_decoded_to_text( decoded_value.get("decodedData", {}) ) for decoded_value in parameter.get("decodedValue", {}) ] ) + "\n" ) if text: return text.strip() else: return ( method + ": " + ",".join([str(parameter["value"]) for parameter in parameters]) ) @classmethod def parse_signatures(cls, raw_tx: Dict[str, Any]) -> Optional[HexBytes]: if raw_tx["signatures"]: # Tx was executed and signatures field is populated return raw_tx["signatures"] elif raw_tx["confirmations"]: # Parse offchain transactions return b"".join( [ HexBytes(confirmation["signature"]) for confirmation in sorted( raw_tx["confirmations"], key=lambda x: int(x["owner"], 16) ) if confirmation["signatureType"] == "EOA" ] ) def get_balances(self, safe_address: str) -> List[Dict[str, Any]]: response = self._get_request(f"/api/v1/safes/{safe_address}/balances/") if not response.ok: raise SafeAPIException(f"Cannot get balances: {response.content}") else: return response.json() def get_safe_transaction( self, safe_tx_hash: Union[bytes, HexStr] ) -> Tuple[SafeTx, Optional[HexBytes]]: """ :param safe_tx_hash: :return: SafeTx and `tx-hash` if transaction was executed """ safe_tx_hash = HexBytes(safe_tx_hash).hex() response = self._get_request(f"/api/v1/multisig-transactions/{safe_tx_hash}/") if not response.ok: raise SafeAPIException( f"Cannot get transaction with safe-tx-hash={safe_tx_hash}: {response.content}" ) else: result = response.json() # TODO return tx-hash if executed signatures = self.parse_signatures(result) if not self.ethereum_client: logger.warning( "EthereumClient should be defined to get a executable SafeTx" ) safe_tx = SafeTx( self.ethereum_client, result["safe"], result["to"], int(result["value"]), HexBytes(result["data"]) if result["data"] else b"", int(result["operation"]), int(result["safeTxGas"]), int(result["baseGas"]), int(result["gasPrice"]), result["gasToken"], result["refundReceiver"], signatures=signatures if signatures else b"", safe_nonce=int(result["nonce"]), chain_id=self.network.value, ) tx_hash = ( HexBytes(result["transactionHash"]) if result["transactionHash"] else None ) if tx_hash: safe_tx.tx_hash = tx_hash return (safe_tx, tx_hash) def get_transactions(self, safe_address: str) -> List[Dict[str, Any]]: response = self._get_request( f"/api/v1/safes/{safe_address}/multisig-transactions/" ) if not response.ok: raise SafeAPIException(f"Cannot get transactions: {response.content}") else: return response.json().get("results", []) def get_delegates(self, safe_address: str) -> List[Dict[str, Any]]: response = self._get_request(f"/api/v1/safes/{safe_address}/delegates/") if not response.ok: raise SafeAPIException(f"Cannot get delegates: {response.content}") else: return response.json().get("results", []) def post_signatures(self, safe_tx_hash: bytes, signatures: bytes) -> None: safe_tx_hash = HexBytes(safe_tx_hash).hex() response = self._post_request( f"/api/v1/multisig-transactions/{safe_tx_hash}/confirmations/", payload={"signature": HexBytes(signatures).hex()}, ) if not response.ok: raise SafeAPIException( f"Cannot post signatures for tx with safe-tx-hash={safe_tx_hash}: {response.content}" ) def add_delegate( self, safe_address: str, delegate_address: str, label: str, signer_account: LocalAccount, ): hash_to_sign = self.create_delegate_message_hash(delegate_address) signature = signer_account.signHash(hash_to_sign) add_payload = { "safe": safe_address, "delegate": delegate_address, "signature": signature.signature.hex(), "label": label, } response = self._post_request( f"/api/v1/safes/{safe_address}/delegates/", add_payload ) if not response.ok: raise SafeAPIException(f"Cannot add delegate: {response.content}") def remove_delegate( self, safe_address: str, delegate_address: str, signer_account: LocalAccount ): hash_to_sign = self.create_delegate_message_hash(delegate_address) signature = signer_account.signHash(hash_to_sign) remove_payload = {"signature": signature.signature.hex()} response = self._delete_request( f"/api/v1/safes/{safe_address}/delegates/{delegate_address}/", remove_payload, ) if not response.ok: raise SafeAPIException(f"Cannot remove delegate: {response.content}") def post_transaction(self, safe_tx: SafeTx): random_sender = "0x0000000000000000000000000000000000000002" sender = safe_tx.sorted_signers[0] if safe_tx.sorted_signers else random_sender data = { "to": safe_tx.to, "value": safe_tx.value, "data": safe_tx.data.hex() if safe_tx.data else None, "operation": safe_tx.operation, "gasToken": safe_tx.gas_token, "safeTxGas": safe_tx.safe_tx_gas, "baseGas": safe_tx.base_gas, "gasPrice": safe_tx.gas_price, "refundReceiver": safe_tx.refund_receiver, "nonce": safe_tx.safe_nonce, "contractTransactionHash": safe_tx.safe_tx_hash.hex(), "sender": sender, "signature": safe_tx.signatures.hex() if safe_tx.signatures else None, "origin": "Safe-CLI", } response = self._post_request( f"/api/v1/safes/{safe_tx.safe_address}/multisig-transactions/", data ) if not response.ok: raise SafeAPIException(f"Error posting transaction: {response.content}")
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/safe/api/transaction_service_api.py
0.740174
0.23316
transaction_service_api.py
pypi
from typing import Any, Dict, List, Optional, Union, cast import requests from eip712_structs import make_domain from eth_account import Account from eth_account.messages import encode_defunct from eth_typing import AnyAddress, ChecksumAddress, HexStr from hexbytes import HexBytes from web3 import Web3 from gnosis.eth import EthereumNetwork, EthereumNetworkNotSupported from gnosis.util import cached_property from .order import Order, OrderKind try: from typing import TypedDict # pylint: disable=no-name-in-module except ImportError: from typing_extensions import TypedDict class TradeResponse(TypedDict): blockNumber: int logIndex: int orderUid: HexStr buyAmount: str # Stringified int sellAmount: str # Stringified int sellAmountBeforeFees: str # Stringified int owner: AnyAddress # Not checksummed buyToken: AnyAddress sellToken: AnyAddress txHash: HexStr class AmountResponse(TypedDict): amount: str token: AnyAddress class ErrorResponse(TypedDict): errorType: str description: str class GnosisProtocolAPI: """ Client for GnosisProtocol API. More info: https://docs.cowswap.exchange/ """ settlement_contract_addresses = { EthereumNetwork.MAINNET: "0x9008D19f58AAbD9eD0D60971565AA8510560ab41", EthereumNetwork.GOERLI: "0x9008D19f58AAbD9eD0D60971565AA8510560ab41", EthereumNetwork.XDAI: "0x9008D19f58AAbD9eD0D60971565AA8510560ab41", } api_base_urls = { EthereumNetwork.MAINNET: "https://api.cow.fi/mainnet/api/v1/", EthereumNetwork.GOERLI: "https://api.cow.fi/goerli/api/v1/", EthereumNetwork.XDAI: "https://api.cow.fi/xdai/api/v1/", } def __init__(self, ethereum_network: EthereumNetwork): self.network = ethereum_network if self.network not in self.api_base_urls: raise EthereumNetworkNotSupported( f"{self.network.name} network not supported by Gnosis Protocol" ) self.domain_separator = self.build_domain_separator(self.network) self.base_url = self.api_base_urls[self.network] self.http_session = requests.Session() @cached_property def weth_address(self) -> ChecksumAddress: """ :return: Wrapped ether checksummed address """ if self.network == EthereumNetwork.MAINNET: return ChecksumAddress("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2") elif self.network == EthereumNetwork.RINKEBY: return ChecksumAddress("0xc778417E063141139Fce010982780140Aa0cD5Ab") else: # XDAI return ChecksumAddress("0x6A023CCd1ff6F2045C3309768eAd9E68F978f6e1") @classmethod def build_domain_separator(cls, ethereum_network: EthereumNetwork): return make_domain( name="Gnosis Protocol", version="v2", chainId=str(ethereum_network.value), verifyingContract=cls.settlement_contract_addresses[ethereum_network], ) def get_fee(self, order: Order) -> int: if order["kind"] == "sell": amount = order["sellAmount"] else: amount = order["buyAmount"] url = ( self.base_url + f'fee/?sellToken={order["sellToken"]}&buyToken={order["buyToken"]}' f'&amount={amount}&kind={order["kind"]}' ) result = self.http_session.get(url).json() if "amount" in result: return int(result["amount"]) else: return 0 def place_order( self, order: Order, private_key: HexStr ) -> Union[HexStr, ErrorResponse]: """ Place order. If `feeAmount=0` in Order it will be calculated calling `get_fee(order)` :return: UUID for the order as an hex hash """ assert ( order["buyAmount"] and order["sellAmount"] ), "Order buyAmount and sellAmount cannot be empty" url = self.base_url + "orders/" order["feeAmount"] = order["feeAmount"] or self.get_fee(order) signable_bytes = order.signable_bytes(domain=self.domain_separator) signable_hash = Web3.keccak(signable_bytes) message = encode_defunct(primitive=signable_hash) signed_message = Account.from_key(private_key).sign_message(message) data_json = { "sellToken": order["sellToken"].lower(), "buyToken": order["buyToken"].lower(), "sellAmount": str(order["sellAmount"]), "buyAmount": str(order["buyAmount"]), "validTo": order["validTo"], "appData": HexBytes(order["appData"]).hex() if isinstance(order["appData"], bytes) else order["appData"], "feeAmount": str(order["feeAmount"]), "kind": order["kind"], "partiallyFillable": order["partiallyFillable"], "signature": signed_message.signature.hex(), "signingScheme": "ethsign", "from": Account.from_key(private_key).address, } r = self.http_session.post(url, json=data_json) if r.ok: return HexStr(r.json()) else: return ErrorResponse(r.json()) def get_orders( self, owner: ChecksumAddress, offset: int = 0, limit=10 ) -> List[Dict[str, Any]]: """ :param owner: :param offset: Defaults to 0 :param limit: Defaults to 10. Maximum is 1000, minimum is 1 :return: Orders of one user paginated. The orders are ordered by their creation date descending (newest orders first). To enumerate all orders start with offset 0 and keep increasing the offset by the total number of returned results. When a response contains less than the limit the last page has been reached. """ url = self.base_url + f"account/{owner}/orders" r = self.http_session.get(url) if r.ok: return cast(List[Dict[str, Any]], r.json()) else: return ErrorResponse(r.json()) def get_trades( self, order_ui: Optional[HexStr] = None, owner: Optional[ChecksumAddress] = None ) -> List[TradeResponse]: assert bool(order_ui) ^ bool( owner ), "order_ui or owner must be provided, but not both" url = self.base_url + "trades/?" if order_ui: url += f"orderUid={order_ui}" elif owner: url += f"owner={owner}" r = self.http_session.get(url) if r.ok: return cast(List[TradeResponse], r.json()) else: return ErrorResponse(r.json()) def get_estimated_amount( self, base_token: ChecksumAddress, quote_token: ChecksumAddress, kind: OrderKind, amount: int, ) -> Union[AmountResponse, ErrorResponse]: """ The estimated amount in quote token for either buying or selling amount of baseToken. """ url = self.base_url + f"markets/{base_token}-{quote_token}/{kind.name}/{amount}" r = self.http_session.get(url) if r.ok: return AmountResponse(r.json()) else: return ErrorResponse(r.json())
/safe-eth-py-axon-4.6.0.tar.gz/safe-eth-py-axon-4.6.0/gnosis/protocol/gnosis_protocol_api.py
0.876687
0.221698
gnosis_protocol_api.py
pypi
from enum import Enum, unique class EthereumNetworkNotSupported(Exception): pass @unique class EthereumNetwork(Enum): """ Use https://chainlist.org/ as a reference """ UNKNOWN = -1 OLYMPIC = 0 MAINNET = 1 ROPSTEN = 3 RINKEBY = 4 GOERLI = 5 ETC_KOTTI = 6 TCH = 7 UBQ = 8 OPTIMISTIC = 10 META = 11 META_TESTNET = 12 DIODE_TESTNET = 13 FLR_FLARE = 14 DIODE = 15 FLR_COSTON = 16 TCH_THAIFI = 17 TST_TESTNET = 18 SGB_SONGBIRD = 19 BOBA_RINKEBY = 28 RSK = 30 RSK_TESTNET = 31 GOOD_TESTNET = 32 GOOD = 33 TBWG = 35 VAL = 38 TLOS = 40 TLOS_TESTNET = 41 KOVAN = 42 PANGOLIN_FREE_TESTNET = 43 CRAB_CRAB_NETWORK = 44 XDC = 50 TXDC_TESTNET = 51 CSC = 52 CSC_TESTNET = 53 BINANCE = 56 SYS = 57 ONTOLOGY = 58 EOS = 59 GO = 60 ELLA = 64 OKEXCHAIN_TESTNET = 65 OKEXCHAIN = 66 DBM_TESTNET = 67 SOTER = 68 MIX = 76 POA_SOKOL = 77 PC = 78 GENECHAIN = 80 METER = 82 METER_TESTNET = 83 GTTEST_TESTNET = 85 GT = 86 TOMO = 88 EOS_TESTNET = 95 BSC_CHAPEL = 97 POA_CORE = 99 XDAI = 100 WEB3GAMES_TESTNET = 102 VELAS_MAINNET = 106 TT = 108 XPR_TESTNET = 110 ETL = 111 FUSE_MAINNET = 122 FUSE_SPARK = 123 DWU = 124 FETH_FACTORY127 = 127 HECO = 128 MATIC = 137 DAX = 142 PHT_SIRIUS = 162 PHT = 163 RESIL_TESTNET = 172 AOX_XDAI = 200 ENERGY_WEB_CHAIN = 246 FANTOM = 250 HECO_TESTNET = 256 HPB = 269 BOBA = 288 KCC_TESTNET = 322 THETA = 361 THETA_TESTNET_SAPPHIRE = 363 THETA_TESTNET_AMBER = 364 THETA_TESTNET = 365 CRO = 385 RUPX = 499 TAO_CORE = 558 METIS_TESTNET = 588 MACA_TESTNET = 595 KAR = 686 FETH_FACTORY127_TESTNET = 721 CHEAPETH_CHEAPNET = 777 ACA = 787 HAIC = 803 WAN = 888 YETI = 977 WAN_TESTNET = 999 KLAY_BAOBAB = 1001 NEW_TESTNET = 1007 EURUS_MAINNET = 1008 EVC_EVRICE = 1010 NEW = 1012 SAKURA = 1022 CLOVER_TESTNET = 1023 CLOVER = 1024 METIS = 1088 MATH = 1139 MATH_TESTNET = 1140 MOON_MOONBEAM = 1284 MOON_MOONRIVER = 1285 MOON_MOONROCK = 1286 MOON_MOONBASE = 1287 MOON_MOONSHADOW = 1288 GANACHE = 1337 CATECHAIN = 1618 EURUS_TESTNET = 1984 EGEM = 1987 EDG = 2021 EDG_BERESHEET = 2022 KORTHO = 2559 FANTOM_TESTNET = 4002 IOTEX_IO = 4689 IOTEX_IO_TESTNET = 4690 ESN = 5197 SYS_TESTNET = 5700 ONTOLOGY_TESTNET = 5851 RBD = 5869 SHYFT = 7341 MDGL_TESTNET = 8029 GENECHAIN_ADENINE = 8080 KLAY_CYPRESS = 8217 KORTHO_TEST = 8285 OLO = 8723 OLO_TESTNET = 8724 BLOXBERG = 8995 SMARTBCH = 10000 SMARTBCHTEST_TESTNET = 10001 GEN = 10101 SHYFT_TESTNET = 11437 REI_TESTNET = 12357 MTT = 16000 MTTTEST_DEVNET = 16001 GO_TESTNET = 31337 FSN = 32659 NRG = 39797 ARBITRUM = 42161 CELO = 42220 ATH_ATHEREUM = 43110 AVALANCHE = 43114 CELO_ALFAJORES = 44787 REI_MAINNET = 47805 NRG_TESTNET = 49797 CELO_BAKLAVA = 62320 VOLTA = 73799 AKA = 200625 ARTIS_SIGMA1 = 246529 ARTIS_TAU1 = 246785 SPARTA_TESTNET = 333888 OLYMPUS = 333999 ARBITRUM_TESTNET = 421611 ETHO = 1313114 XERO = 1313500 MUSIC = 7762959 MUMBAI = 80001 PEP_TESTNET = 13371337 ILT = 18289463 QKI = 20181205 AUX = 28945486 JOYS = 35855456 AQUA = 61717561 TOYS_TESTNET = 99415706 OLT = 311752642 IPOS = 1122334455 AURORA = 1313161554 AURORA_TESTNET = 1313161555 AURORA_BETANET = 1313161556 PIRL = 3125659152 OLT_TESTNET = 4216137055 PALM_TESTNET = 11297108099 PALM = 11297108109 GATHER_DEVNET = 486217935 GATHER_TESTNET = 356256156 GATHER_MAINNET = 192837465 EVMOS_TESTNET = 9000 EVMOS_MAINNET = 9001 @classmethod def _missing_(cls, value): return cls.UNKNOWN
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/eth/ethereum_network.py
0.458349
0.411052
ethereum_network.py
pypi
from secrets import token_bytes from typing import Tuple, Union import eth_abi from eth._utils.address import generate_contract_address from eth_keys import keys from eth_utils import to_canonical_address, to_checksum_address from hexbytes import HexBytes from web3 import Web3 def get_eth_address_with_key() -> Tuple[str, bytes]: private_key = keys.PrivateKey(token_bytes(32)) address = private_key.public_key.to_checksum_address() return address, private_key.to_bytes() def get_eth_address_with_invalid_checksum() -> str: address, _ = get_eth_address_with_key() return "0x" + "".join( [c.lower() if c.isupper() else c.upper() for c in address[2:]] ) def generate_address_2( from_: Union[str, bytes], salt: Union[str, bytes], init_code: Union[str, bytes] ) -> str: """ Generates an address for a contract created using CREATE2. :param from_: The address which is creating this new address (need to be 20 bytes) :param salt: A salt (32 bytes) :param init_code: A init code of the contract being created :return: Address of the new contract """ from_ = HexBytes(from_) salt = HexBytes(salt) init_code = HexBytes(init_code) assert len(from_) == 20, f"Address {from_.hex()} is not valid. Must be 20 bytes" assert len(salt) == 32, f"Salt {salt.hex()} is not valid. Must be 32 bytes" assert len(init_code) > 0, f"Init code {init_code.hex()} is not valid" init_code_hash = Web3.keccak(init_code) contract_address = Web3.keccak(HexBytes("ff") + from_ + salt + init_code_hash) return Web3.toChecksumAddress(contract_address[12:]) def decode_string_or_bytes32(data: bytes) -> str: try: return eth_abi.decode_abi(["string"], data)[0] except OverflowError: name = eth_abi.decode_abi(["bytes32"], data)[0] end_position = name.find(b"\x00") if end_position == -1: return name.decode() else: return name[:end_position].decode() def remove_swarm_metadata(code: bytes) -> bytes: """ Remove swarm metadata from Solidity bytecode :param code: :return: Code without metadata """ swarm = b"\xa1\x65bzzr0" position = code.rfind(swarm) if position == -1: raise ValueError("Swarm metadata not found in code %s" % code.hex()) return code[:position] def compare_byte_code(code_1: bytes, code_2: bytes) -> bool: """ Compare code, removing swarm metadata if necessary :param code_1: :param code_2: :return: True if same code, False otherwise """ if code_1 == code_2: return True else: codes = [] for code in (code_1, code_2): try: codes.append(remove_swarm_metadata(code)) except ValueError: codes.append(code) return codes[0] == codes[1] def mk_contract_address(address: Union[str, bytes], nonce: int) -> str: return to_checksum_address( generate_contract_address(to_canonical_address(address), nonce) )
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/eth/utils.py
0.899293
0.368747
utils.py
pypi
import logging from dataclasses import dataclass from typing import Any, List, Optional, Sequence, Tuple from eth_abi.exceptions import DecodingError from eth_account.signers.local import LocalAccount from eth_typing import BlockIdentifier, BlockNumber, ChecksumAddress from hexbytes import HexBytes from web3 import Web3 from web3._utils.abi import map_abi_data from web3._utils.normalizers import BASE_RETURN_NORMALIZERS from web3.contract import ContractFunction from web3.exceptions import ContractLogicError from . import EthereumClient, EthereumNetwork, EthereumNetworkNotSupported from .ethereum_client import EthereumTxSent from .exceptions import BatchCallFunctionFailed from .oracles.abis.makerdao import multicall_v2_abi, multicall_v2_bytecode logger = logging.getLogger(__name__) @dataclass class MulticallResult: success: bool return_data: Optional[bytes] @dataclass class MulticallDecodedResult: success: bool return_data_decoded: Optional[Any] class Multicall: ADDRESSES = { EthereumNetwork.MAINNET: "0x5BA1e12693Dc8F9c48aAD8770482f4739bEeD696", EthereumNetwork.ARBITRUM: "0x021CeAC7e681dBCE9b5039d2535ED97590eB395c", EthereumNetwork.BINANCE: "0xed386Fe855C1EFf2f843B910923Dd8846E45C5A4", EthereumNetwork.GOERLI: "0x5BA1e12693Dc8F9c48aAD8770482f4739bEeD696", EthereumNetwork.KOVAN: "0x5BA1e12693Dc8F9c48aAD8770482f4739bEeD696", EthereumNetwork.MATIC: "0xed386Fe855C1EFf2f843B910923Dd8846E45C5A4", EthereumNetwork.MUMBAI: "0xed386Fe855C1EFf2f843B910923Dd8846E45C5A4", EthereumNetwork.RINKEBY: "0x5BA1e12693Dc8F9c48aAD8770482f4739bEeD696", EthereumNetwork.ROPSTEN: "0x5BA1e12693Dc8F9c48aAD8770482f4739bEeD696", EthereumNetwork.XDAI: "0x08612d3C4A5Dfe2FaaFaFe6a4ff712C2dC675bF7", EthereumNetwork.FANTOM: "0xD98e3dBE5950Ca8Ce5a4b59630a5652110403E5c", EthereumNetwork.AVALANCHE: "0xAbeC56f92a89eEe33F5194Ca4151DD59785c2C74", } def __init__( self, ethereum_client: EthereumClient, multicall_contract_address: Optional[ChecksumAddress] = None, ): self.ethereum_client = ethereum_client self.w3 = ethereum_client.w3 ethereum_network = ethereum_client.get_network() address = multicall_contract_address or self.ADDRESSES.get(ethereum_network) if not address: raise EthereumNetworkNotSupported( "Multicall contract not available for %s", ethereum_network.name ) self.contract = self.get_contract(self.w3, address) def get_contract(self, w3: Web3, address: Optional[ChecksumAddress] = None): return w3.eth.contract( address, abi=multicall_v2_abi, bytecode=multicall_v2_bytecode ) @classmethod def deploy_contract( cls, ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy contract :param ethereum_client: :param deployer_account: Ethereum Account :return: deployed contract address """ contract = cls.get_contract(cls, ethereum_client.w3) tx = contract.constructor().buildTransaction({"from": deployer_account.address}) tx_hash = ethereum_client.send_unsigned_transaction( tx, private_key=deployer_account.key ) tx_receipt = ethereum_client.get_transaction_receipt(tx_hash, timeout=120) assert tx_receipt and tx_receipt["status"] contract_address = tx_receipt["contractAddress"] logger.info( "Deployed Multicall V2 Contract %s by %s", contract_address, deployer_account.address, ) # Add address to addresses dictionary cls.ADDRESSES[ethereum_client.get_network()] = contract_address return EthereumTxSent(tx_hash, tx, contract_address) @staticmethod def _build_payload( contract_functions: Sequence[ContractFunction], ) -> Tuple[List[Tuple[ChecksumAddress, bytes]], List[List[Any]]]: targets_with_data = [] output_types = [] for contract_function in contract_functions: targets_with_data.append( ( contract_function.address, HexBytes(contract_function._encode_transaction_data()), ) ) output_types.append( [output["type"] for output in contract_function.abi["outputs"]] ) return targets_with_data, output_types def _build_payload_same_function( self, contract_function: ContractFunction, contract_addresses: Sequence[ChecksumAddress], ) -> Tuple[List[Tuple[ChecksumAddress, bytes]], List[List[Any]]]: targets_with_data = [] output_types = [] tx_data = HexBytes(contract_function._encode_transaction_data()) for contract_address in contract_addresses: targets_with_data.append((contract_address, tx_data)) output_types.append( [output["type"] for output in contract_function.abi["outputs"]] ) return targets_with_data, output_types def _decode_data(self, output_type: Sequence[str], data: bytes) -> Optional[Any]: """ :param output_type: :param data: :return: :raises: DecodingError """ if data: try: decoded_values = self.w3.codec.decode_abi(output_type, data) normalized_data = map_abi_data( BASE_RETURN_NORMALIZERS, output_type, decoded_values ) if len(normalized_data) == 1: return normalized_data[0] else: return normalized_data except DecodingError: logger.warning( "Cannot decode %s using output-type %s", data, output_type ) return data def _aggregate( self, targets_with_data: Sequence[Tuple[ChecksumAddress, bytes]], block_identifier: Optional[BlockIdentifier] = "latest", ) -> Tuple[BlockNumber, List[Optional[Any]]]: """ :param targets_with_data: List of target `addresses` and `data` to be called in each Contract :param block_identifier: :return: :raises: BatchCallFunctionFailed """ aggregate_parameter = [ {"target": target, "callData": data} for target, data in targets_with_data ] try: return self.contract.functions.aggregate(aggregate_parameter).call( block_identifier=block_identifier ) except (ContractLogicError, OverflowError): raise BatchCallFunctionFailed def aggregate( self, contract_functions: Sequence[ContractFunction], block_identifier: Optional[BlockIdentifier] = "latest", ) -> Tuple[BlockNumber, List[Optional[Any]]]: """ Calls ``aggregate`` on MakerDAO's Multicall contract. If a function called raises an error execution is stopped :param contract_functions: :param block_identifier: :return: A tuple with the ``blockNumber`` and a list with the decoded return values :raises: BatchCallFunctionFailed """ targets_with_data, output_types = self._build_payload(contract_functions) block_number, results = self._aggregate( targets_with_data, block_identifier=block_identifier ) decoded_results = [ self._decode_data(output_type, data) for output_type, data in zip(output_types, results) ] return block_number, decoded_results def _try_aggregate( self, targets_with_data: Sequence[Tuple[ChecksumAddress, bytes]], require_success: bool = False, block_identifier: Optional[BlockIdentifier] = "latest", ) -> List[MulticallResult]: """ Calls ``try_aggregate`` on MakerDAO's Multicall contract. :param targets_with_data: :param require_success: If ``True``, an exception in any of the functions will stop the execution. Also, an invalid decoded value will stop the execution :param block_identifier: :return: A list with the decoded return values """ aggregate_parameter = [ {"target": target, "callData": data} for target, data in targets_with_data ] try: result = self.contract.functions.tryAggregate( require_success, aggregate_parameter ).call(block_identifier=block_identifier) if require_success and b"" in (data for _, data in result): # `b''` values are decoding errors/missing contracts/missing functions raise BatchCallFunctionFailed return [ MulticallResult(success, data if data else None) for success, data in result ] except (ContractLogicError, OverflowError, ValueError): raise BatchCallFunctionFailed def try_aggregate( self, contract_functions: Sequence[ContractFunction], require_success: bool = False, block_identifier: Optional[BlockIdentifier] = "latest", ) -> List[MulticallDecodedResult]: """ Calls ``try_aggregate`` on MakerDAO's Multicall contract. :param contract_functions: :param require_success: If ``True``, an exception in any of the functions will stop the execution :param block_identifier: :return: A list with the decoded return values """ targets_with_data, output_types = self._build_payload(contract_functions) results = self._try_aggregate( targets_with_data, require_success=require_success, block_identifier=block_identifier, ) return [ MulticallDecodedResult( multicall_result.success, self._decode_data(output_type, multicall_result.return_data) if multicall_result.success else multicall_result.return_data, ) for output_type, multicall_result in zip(output_types, results) ] def try_aggregate_same_function( self, contract_function: ContractFunction, contract_addresses: Sequence[ChecksumAddress], require_success: bool = False, block_identifier: Optional[BlockIdentifier] = "latest", ) -> List[MulticallDecodedResult]: """ Calls ``try_aggregate`` on MakerDAO's Multicall contract. Reuse same function with multiple contract addresses. It's more optimal due to instantiating ``ContractFunction`` objects is very demanding :param contract_function: :param contract_addresses: :param require_success: If ``True``, an exception in any of the functions will stop the execution :param block_identifier: :return: A list with the decoded return values """ targets_with_data, output_types = self._build_payload_same_function( contract_function, contract_addresses ) results = self._try_aggregate( targets_with_data, require_success=require_success, block_identifier=block_identifier, ) return [ MulticallDecodedResult( multicall_result.success, self._decode_data(output_type, multicall_result.return_data) if multicall_result.success else multicall_result.return_data, ) for output_type, multicall_result in zip(output_types, results) ]
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/eth/multicall.py
0.891746
0.221267
multicall.py
pypi
import json import time from typing import Any, Dict, Optional from urllib.parse import urljoin import requests from .. import EthereumNetwork from .contract_metadata import ContractMetadata class EtherscanClientException(Exception): pass class EtherscanClientConfigurationProblem(Exception): pass class EtherscanRateLimitError(EtherscanClientException): pass class EtherscanClient: NETWORK_WITH_URL = { EthereumNetwork.MAINNET: "https://etherscan.io", EthereumNetwork.RINKEBY: "https://rinkeby.etherscan.io", EthereumNetwork.ROPSTEN: "https://ropsten.etherscan.io", EthereumNetwork.GOERLI: "https://goerli.etherscan.io", EthereumNetwork.KOVAN: "https://kovan.etherscan.io", EthereumNetwork.BINANCE: "https://bscscan.com", EthereumNetwork.MATIC: "https://polygonscan.com", EthereumNetwork.OPTIMISTIC: "https://optimistic.etherscan.io", EthereumNetwork.ARBITRUM: "https://arbiscan.io", EthereumNetwork.AVALANCHE: "https://snowtrace.io", } NETWORK_WITH_API_URL = { EthereumNetwork.MAINNET: "https://api.etherscan.io", EthereumNetwork.RINKEBY: "https://api-rinkeby.etherscan.io", EthereumNetwork.ROPSTEN: "https://api-ropsten.etherscan.io", EthereumNetwork.GOERLI: "https://api-goerli.etherscan.io/", EthereumNetwork.KOVAN: "https://api-kovan.etherscan.io/", EthereumNetwork.BINANCE: "https://api.bscscan.com", EthereumNetwork.MATIC: "https://api.polygonscan.com", EthereumNetwork.OPTIMISTIC: "https://api-optimistic.etherscan.io", EthereumNetwork.ARBITRUM: "https://api.arbiscan.io", EthereumNetwork.AVALANCHE: "https://api.snowtrace.io", } HTTP_HEADERS = { "User-Agent": "curl/7.77.0", } def __init__(self, network: EthereumNetwork, api_key: Optional[str] = None): self.network = network self.api_key = api_key self.base_url = self.NETWORK_WITH_URL.get(network) self.base_api_url = self.NETWORK_WITH_API_URL.get(network) if self.base_api_url is None: raise EtherscanClientConfigurationProblem( f"Network {network.name} - {network.value} not supported" ) self.http_session = requests.Session() self.http_session.headers = self.HTTP_HEADERS def build_url(self, path: str): url = urljoin(self.base_api_url, path) if self.api_key: url += f"&apikey={self.api_key}" return url def _do_request(self, url: str) -> Optional[Dict[str, Any]]: response = self.http_session.get(url) if response.ok: response_json = response.json() result = response_json["result"] if "Max rate limit reached" in result: # Max rate limit reached, please use API Key for higher rate limit raise EtherscanRateLimitError if response_json["status"] == "1": return result def _retry_request(self, url: str, retry: bool = True) -> Optional[Dict[str, Any]]: for _ in range(3): try: return self._do_request(url) except EtherscanRateLimitError as exc: if not retry: raise exc else: time.sleep(5) def get_contract_metadata( self, contract_address: str, retry: bool = True ) -> Optional[ContractMetadata]: contract_source_code = self.get_contract_source_code( contract_address, retry=retry ) if contract_source_code: contract_name = contract_source_code["ContractName"] contract_abi = contract_source_code["ABI"] if contract_abi: return ContractMetadata(contract_name, contract_abi, False) def get_contract_source_code(self, contract_address: str, retry: bool = True): """ Get source code for a contract. Source code query also returns: - ContractName: "", - CompilerVersion: "", - OptimizationUsed: "", - Runs: "", - ConstructorArguments: "" - EVMVersion: "Default", - Library: "", - LicenseType: "", - Proxy: "0", - Implementation: "", - SwarmSource: "" :param contract_address: :param retry: if ``True``, try again if there's Rate Limit Error :return: """ url = self.build_url( f"api?module=contract&action=getsourcecode&address={contract_address}" ) result = self._retry_request(url, retry=retry) # Returns a list if result: result = result[0] abi_str = result["ABI"] result["ABI"] = json.loads(abi_str) if abi_str.startswith("[") else None return result def get_contract_abi(self, contract_address: str, retry: bool = True): url = self.build_url( f"api?module=contract&action=getabi&address={contract_address}" ) result = self._retry_request(url, retry=retry) if result: return json.loads(result)
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/eth/clients/etherscan_client.py
0.761139
0.268366
etherscan_client.py
pypi
from typing import Any, Dict, List, Optional from urllib.parse import urljoin import requests from web3 import Web3 from .. import EthereumNetwork from .contract_metadata import ContractMetadata class Sourcify: """ Get contract metadata from Sourcify. Matches can be full or partial: - Full: Both the source files as well as the meta data files were an exact match between the deployed bytecode and the published files. - Partial: Source code compiles to the same bytecode and thus the contract behaves in the same way, but the source code can be different: Variables can have misleading names, comments can be different and especially the NatSpec comments could have been modified. """ def __init__( self, network: EthereumNetwork = EthereumNetwork.MAINNET, base_url: str = "https://repo.sourcify.dev/", ): self.network = network self.base_url = base_url self.http_session = requests.session() def _get_abi_from_metadata(self, metadata: Dict[str, Any]) -> List[Dict[str, Any]]: return metadata["output"]["abi"] def _get_name_from_metadata(self, metadata: Dict[str, Any]) -> Optional[str]: values = list(metadata["settings"].get("compilationTarget", {}).values()) if values: return values[0] def _do_request(self, url: str) -> Optional[Dict[str, Any]]: response = self.http_session.get(url, timeout=10) if not response.ok: return None return response.json() def get_contract_metadata( self, contract_address: str ) -> Optional[ContractMetadata]: assert Web3.isChecksumAddress( contract_address ), "Expecting a checksummed address" for match_type in ("full_match", "partial_match"): url = urljoin( self.base_url, f"/contracts/{match_type}/{self.network.value}/{contract_address}/metadata.json", ) metadata = self._do_request(url) if metadata: abi = self._get_abi_from_metadata(metadata) name = self._get_name_from_metadata(metadata) return ContractMetadata(name, abi, match_type == "partial_match") return None
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/eth/clients/sourcify.py
0.899682
0.369088
sourcify.py
pypi
import json from typing import Any, Dict, Optional from urllib.parse import urljoin import requests from eth_typing import ChecksumAddress from .. import EthereumNetwork from .contract_metadata import ContractMetadata class BlockscoutClientException(Exception): pass class BlockScoutConfigurationProblem(BlockscoutClientException): pass class BlockscoutClient: NETWORK_WITH_URL = { EthereumNetwork.XDAI: "https://blockscout.com/poa/xdai/", EthereumNetwork.MATIC: "https://polygon-explorer-mainnet.chainstacklabs.com/", EthereumNetwork.MUMBAI: "https://polygon-explorer-mumbai.chainstacklabs.com/", EthereumNetwork.ENERGY_WEB_CHAIN: "https://explorer.energyweb.org/", EthereumNetwork.VOLTA: "https://volta-explorer.energyweb.org/", EthereumNetwork.OLYMPUS: "https://explorer.polis.tech", EthereumNetwork.BOBA_RINKEBY: "https://blockexplorer.rinkeby.boba.network/", EthereumNetwork.BOBA: "https://blockexplorer.boba.network/", EthereumNetwork.GATHER_DEVNET: "https://devnet-explorer.gather.network/", EthereumNetwork.GATHER_TESTNET: "https://testnet-explorer.gather.network/", EthereumNetwork.GATHER_MAINNET: "https://explorer.gather.network/", EthereumNetwork.METIS_TESTNET: "https://stardust-explorer.metis.io/", EthereumNetwork.METIS: "https://andromeda-explorer.metis.io/", EthereumNetwork.FUSE_MAINNET: "https://explorer.fuse.io/", EthereumNetwork.VELAS_MAINNET: "https://evmexplorer.velas.com/", EthereumNetwork.REI_MAINNET: "https://scan.rei.network/", EthereumNetwork.REI_TESTNET: "https://scan-test.rei.network/", EthereumNetwork.METER: "https://scan.meter.io/", EthereumNetwork.METER_TESTNET: "https://scan-warringstakes.meter.io/", } def __init__(self, network: EthereumNetwork): self.network = network self.base_url = self.NETWORK_WITH_URL.get(network) if self.base_url is None: raise BlockScoutConfigurationProblem( f"Network {network.name} - {network.value} not supported" ) self.grahpql_url = self.base_url + "/graphiql" self.http_session = requests.Session() def build_url(self, path: str): return urljoin(self.base_url, path) def _do_request(self, url: str, query: str) -> Optional[Dict[str, Any]]: response = self.http_session.post(url, json={"query": query}, timeout=10) if not response.ok: return None return response.json() def get_contract_metadata( self, address: ChecksumAddress ) -> Optional[ContractMetadata]: query = '{address(hash: "%s") { hash, smartContract {name, abi} }}' % address result = self._do_request(self.grahpql_url, query) if ( result and "error" not in result and result.get("data", {}).get("address", {}) and result["data"]["address"]["smartContract"] ): smart_contract = result["data"]["address"]["smartContract"] return ContractMetadata( smart_contract["name"], json.loads(smart_contract["abi"]), False )
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/eth/clients/blockscout_client.py
0.785144
0.29906
blockscout_client.py
pypi
import binascii from typing import Optional, Union from django.core import exceptions from django.db import models from django.utils.translation import gettext_lazy as _ from eth_typing import ChecksumAddress from eth_utils import to_checksum_address from hexbytes import HexBytes from .filters import EthereumAddressFieldForm, Keccak256FieldForm from .validators import validate_checksumed_address try: from django.db import DefaultConnectionProxy connection = DefaultConnectionProxy() except ImportError: from django.db import connections connection = connections["default"] class EthereumAddressField(models.CharField): default_validators = [validate_checksumed_address] description = "DEPRECATED. Use `EthereumAddressV2Field`. Ethereum address (EIP55)" default_error_messages = { "invalid": _('"%(value)s" value must be an EIP55 checksummed address.'), } def __init__(self, *args, **kwargs): kwargs["max_length"] = 42 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs def from_db_value(self, value, expression, connection): return self.to_python(value) def to_python(self, value): value = super().to_python(value) if value: try: return to_checksum_address(value) except ValueError: raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) else: return value def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) class EthereumAddressV2Field(models.Field): default_validators = [validate_checksumed_address] description = "Ethereum address (EIP55)" default_error_messages = { "invalid": _('"%(value)s" value must be an EIP55 checksummed address.'), } def get_internal_type(self): return "BinaryField" def from_db_value( self, value: memoryview, expression, connection ) -> Optional[ChecksumAddress]: if value: return to_checksum_address(value.hex()) def get_prep_value(self, value: ChecksumAddress) -> Optional[bytes]: if value: return HexBytes(self.to_python(value)) def to_python(self, value) -> Optional[ChecksumAddress]: if value is not None: try: return to_checksum_address(value) except ValueError: raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def formfield(self, **kwargs): defaults = { "form_class": EthereumAddressFieldForm, "max_length": 2 + 40, } defaults.update(kwargs) return super().formfield(**defaults) class Uint256Field(models.DecimalField): description = _("Ethereum uint256 number") """ Field to store ethereum uint256 values. Uses Decimal db type without decimals to store in the database, but retrieve as `int` instead of `Decimal` (https://docs.python.org/3/library/decimal.html) """ def __init__(self, *args, **kwargs): kwargs["max_digits"] = 79 # 2 ** 256 is 78 digits kwargs["decimal_places"] = 0 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_digits"] del kwargs["decimal_places"] return name, path, args, kwargs def from_db_value(self, value, expression, connection): if value is None: return value return int(value) class HexField(models.CharField): """ Field to store hex values (without 0x). Returns hex with 0x prefix. On Database side a CharField is used. """ description = "Stores a hex value into an CharField" def from_db_value(self, value, expression, connection): return self.to_python(value) def to_python(self, value): return value if value is None else HexBytes(value).hex() def get_prep_value(self, value): if value is None: return value elif isinstance(value, HexBytes): return value.hex()[ 2: ] # HexBytes.hex() retrieves hexadecimal with '0x', remove it elif isinstance(value, bytes): return value.hex() # bytes.hex() retrieves hexadecimal without '0x' else: # str return HexBytes(value).hex()[2:] def formfield(self, **kwargs): # We need max_lenght + 2 on forms because of `0x` defaults = {"max_length": self.max_length + 2} # TODO: Handle multiple backends with different feature flags. if self.null and not connection.features.interprets_empty_strings_as_nulls: defaults["empty_value"] = None defaults.update(kwargs) return super().formfield(**defaults) def clean(self, value, model_instance): value = self.to_python(value) self.validate(value, model_instance) # Validation didn't work because of `0x` self.run_validators(value[2:]) return value class Sha3HashField(HexField): description = "DEPRECATED. Use `Keccak256Field`" def __init__(self, *args, **kwargs): kwargs["max_length"] = 64 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs class Keccak256Field(models.BinaryField): description = "Keccak256 hash stored as binary" default_error_messages = { "invalid": _('"%(value)s" hash must be a 32 bytes hexadecimal.'), "length": _('"%(value)s" hash must have exactly 32 bytes.'), } def _to_bytes(self, value) -> Optional[bytes]: if value is None: return else: try: result = HexBytes(value) if len(result) != 32: raise exceptions.ValidationError( self.error_messages["length"], code="length", params={"value": value}, ) return result except (ValueError, binascii.Error): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def from_db_value( self, value: memoryview, expression, connection ) -> Optional[bytes]: if value: return HexBytes(value.tobytes()).hex() def get_prep_value(self, value: Union[bytes, str]) -> Optional[bytes]: if value: return self._to_bytes(value) def to_python(self, value) -> Optional[str]: if value is not None: try: return self._to_bytes(value) except (ValueError, binascii.Error): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def formfield(self, **kwargs): defaults = { "form_class": Keccak256FieldForm, "max_length": 2 + 64, } defaults.update(kwargs) return super().formfield(**defaults)
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/eth/django/models.py
0.839865
0.192824
models.py
pypi
mooniswap_abi = [ { "inputs": [ {"internalType": "contract IERC20", "name": "_token0", "type": "address"}, {"internalType": "contract IERC20", "name": "_token1", "type": "address"}, {"internalType": "string", "name": "name", "type": "string"}, {"internalType": "string", "name": "symbol", "type": "string"}, { "internalType": "contract IMooniswapFactoryGovernance", "name": "_mooniswapFactoryGovernance", "type": "address", }, ], "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": True, "internalType": "address", "name": "spender", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "user", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "decayPeriod", "type": "uint256", }, { "indexed": False, "internalType": "bool", "name": "isDefault", "type": "bool", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, ], "name": "DecayPeriodVoteUpdate", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "receiver", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "share", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "token0Amount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "token1Amount", "type": "uint256", }, ], "name": "Deposited", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "string", "name": "reason", "type": "string", } ], "name": "Error", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "user", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "fee", "type": "uint256", }, { "indexed": False, "internalType": "bool", "name": "isDefault", "type": "bool", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, ], "name": "FeeVoteUpdate", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "previousOwner", "type": "address", }, { "indexed": True, "internalType": "address", "name": "newOwner", "type": "address", }, ], "name": "OwnershipTransferred", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "user", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "slippageFee", "type": "uint256", }, { "indexed": False, "internalType": "bool", "name": "isDefault", "type": "bool", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, ], "name": "SlippageFeeVoteUpdate", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "receiver", "type": "address", }, { "indexed": True, "internalType": "address", "name": "srcToken", "type": "address", }, { "indexed": False, "internalType": "address", "name": "dstToken", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "result", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "srcAdditionBalance", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "dstRemovalBalance", "type": "uint256", }, { "indexed": False, "internalType": "address", "name": "referral", "type": "address", }, ], "name": "Swapped", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint256", "name": "srcBalance", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "dstBalance", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "fee", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "slippageFee", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "referralShare", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "governanceShare", "type": "uint256", }, ], "name": "Sync", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "to", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "receiver", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "share", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "token0Amount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "token1Amount", "type": "uint256", }, ], "name": "Withdrawn", "type": "event", }, { "inputs": [ {"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}, ], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "decayPeriod", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "uint256", "name": "vote", "type": "uint256"}], "name": "decayPeriodVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "decayPeriodVotes", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "decimals", "outputs": [{"internalType": "uint8", "name": "", "type": "uint8"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "subtractedValue", "type": "uint256"}, ], "name": "decreaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint256[2]", "name": "maxAmounts", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "minAmounts", "type": "uint256[2]"}, ], "name": "deposit", "outputs": [ {"internalType": "uint256", "name": "fairSupply", "type": "uint256"}, { "internalType": "uint256[2]", "name": "receivedAmounts", "type": "uint256[2]", }, ], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "uint256[2]", "name": "maxAmounts", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "minAmounts", "type": "uint256[2]"}, {"internalType": "address", "name": "target", "type": "address"}, ], "name": "depositFor", "outputs": [ {"internalType": "uint256", "name": "fairSupply", "type": "uint256"}, { "internalType": "uint256[2]", "name": "receivedAmounts", "type": "uint256[2]", }, ], "stateMutability": "payable", "type": "function", }, { "inputs": [], "name": "discardDecayPeriodVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "discardFeeVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "discardSlippageFeeVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "fee", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "uint256", "name": "vote", "type": "uint256"}], "name": "feeVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "feeVotes", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "token", "type": "address"} ], "name": "getBalanceForAddition", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "token", "type": "address"} ], "name": "getBalanceForRemoval", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "src", "type": "address"}, {"internalType": "contract IERC20", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "getReturn", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "getTokens", "outputs": [ {"internalType": "contract IERC20[]", "name": "tokens", "type": "address[]"} ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "addedValue", "type": "uint256"}, ], "name": "increaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "mooniswapFactoryGovernance", "outputs": [ { "internalType": "contract IMooniswapFactoryGovernance", "name": "", "type": "address", } ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "name", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "owner", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "rescueFunds", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "contract IMooniswapFactoryGovernance", "name": "newMooniswapFactoryGovernance", "type": "address", } ], "name": "setMooniswapFactoryGovernance", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "slippageFee", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "uint256", "name": "vote", "type": "uint256"}], "name": "slippageFeeVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "slippageFeeVotes", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "src", "type": "address"}, {"internalType": "contract IERC20", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256", "name": "minReturn", "type": "uint256"}, {"internalType": "address", "name": "referral", "type": "address"}, ], "name": "swap", "outputs": [{"internalType": "uint256", "name": "result", "type": "uint256"}], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "src", "type": "address"}, {"internalType": "contract IERC20", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256", "name": "minReturn", "type": "uint256"}, {"internalType": "address", "name": "referral", "type": "address"}, {"internalType": "address payable", "name": "receiver", "type": "address"}, ], "name": "swapFor", "outputs": [{"internalType": "uint256", "name": "result", "type": "uint256"}], "stateMutability": "payable", "type": "function", }, { "inputs": [], "name": "symbol", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "token0", "outputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "token1", "outputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "uint256", "name": "i", "type": "uint256"}], "name": "tokens", "outputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "sender", "type": "address"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "newOwner", "type": "address"}], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "name": "virtualBalancesForAddition", "outputs": [ {"internalType": "uint216", "name": "balance", "type": "uint216"}, {"internalType": "uint40", "name": "time", "type": "uint40"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "name": "virtualBalancesForRemoval", "outputs": [ {"internalType": "uint216", "name": "balance", "type": "uint216"}, {"internalType": "uint40", "name": "time", "type": "uint40"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "virtualDecayPeriod", "outputs": [ {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint48", "name": "", "type": "uint48"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "virtualFee", "outputs": [ {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint48", "name": "", "type": "uint48"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "virtualSlippageFee", "outputs": [ {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint48", "name": "", "type": "uint48"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "name": "volumes", "outputs": [ {"internalType": "uint128", "name": "confirmed", "type": "uint128"}, {"internalType": "uint128", "name": "result", "type": "uint128"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256[]", "name": "minReturns", "type": "uint256[]"}, ], "name": "withdraw", "outputs": [ { "internalType": "uint256[2]", "name": "withdrawnAmounts", "type": "uint256[2]", } ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256[]", "name": "minReturns", "type": "uint256[]"}, {"internalType": "address payable", "name": "target", "type": "address"}, ], "name": "withdrawFor", "outputs": [ { "internalType": "uint256[2]", "name": "withdrawnAmounts", "type": "uint256[2]", } ], "stateMutability": "nonpayable", "type": "function", }, ]
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/eth/oracles/abis/mooniswap_abis.py
0.535098
0.515315
mooniswap_abis.py
pypi
AAVE_ATOKEN_ABI = [ { "inputs": [ { "internalType": "contract ILendingPool", "name": "pool", "type": "address", }, { "internalType": "address", "name": "underlyingAssetAddress", "type": "address", }, { "internalType": "address", "name": "reserveTreasuryAddress", "type": "address", }, {"internalType": "string", "name": "tokenName", "type": "string"}, {"internalType": "string", "name": "tokenSymbol", "type": "string"}, { "internalType": "address", "name": "incentivesController", "type": "address", }, ], "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": True, "internalType": "address", "name": "spender", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "to", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "index", "type": "uint256", }, ], "name": "BalanceTransfer", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "target", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "index", "type": "uint256", }, ], "name": "Burn", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "underlyingAsset", "type": "address", }, { "indexed": True, "internalType": "address", "name": "pool", "type": "address", }, { "indexed": False, "internalType": "address", "name": "treasury", "type": "address", }, { "indexed": False, "internalType": "address", "name": "incentivesController", "type": "address", }, { "indexed": False, "internalType": "uint8", "name": "aTokenDecimals", "type": "uint8", }, { "indexed": False, "internalType": "string", "name": "aTokenName", "type": "string", }, { "indexed": False, "internalType": "string", "name": "aTokenSymbol", "type": "string", }, { "indexed": False, "internalType": "bytes", "name": "params", "type": "bytes", }, ], "name": "Initialized", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "index", "type": "uint256", }, ], "name": "Mint", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "to", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "inputs": [], "name": "ATOKEN_REVISION", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "DOMAIN_SEPARATOR", "outputs": [{"internalType": "bytes32", "name": "", "type": "bytes32"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "EIP712_REVISION", "outputs": [{"internalType": "bytes", "name": "", "type": "bytes"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "PERMIT_TYPEHASH", "outputs": [{"internalType": "bytes32", "name": "", "type": "bytes32"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "POOL", "outputs": [ {"internalType": "contract ILendingPool", "name": "", "type": "address"} ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "RESERVE_TREASURY_ADDRESS", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "UINT_MAX_VALUE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "UNDERLYING_ASSET_ADDRESS", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "address", "name": "", "type": "address"}], "name": "_nonces", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}, ], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "user", "type": "address"}, { "internalType": "address", "name": "receiverOfUnderlying", "type": "address", }, {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256", "name": "index", "type": "uint256"}, ], "name": "burn", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "decimals", "outputs": [{"internalType": "uint8", "name": "", "type": "uint8"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "subtractedValue", "type": "uint256"}, ], "name": "decreaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "getIncentivesController", "outputs": [ { "internalType": "contract IAaveIncentivesController", "name": "", "type": "address", } ], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "getScaledUserBalanceAndSupply", "outputs": [ {"internalType": "uint256", "name": "", "type": "uint256"}, {"internalType": "uint256", "name": "", "type": "uint256"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "addedValue", "type": "uint256"}, ], "name": "increaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "uint8", "name": "underlyingAssetDecimals", "type": "uint8", }, {"internalType": "string", "name": "tokenName", "type": "string"}, {"internalType": "string", "name": "tokenSymbol", "type": "string"}, ], "name": "initialize", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "user", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256", "name": "index", "type": "uint256"}, ], "name": "mint", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256", "name": "index", "type": "uint256"}, ], "name": "mintToTreasury", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "name", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}, {"internalType": "uint256", "name": "deadline", "type": "uint256"}, {"internalType": "uint8", "name": "v", "type": "uint8"}, {"internalType": "bytes32", "name": "r", "type": "bytes32"}, {"internalType": "bytes32", "name": "s", "type": "bytes32"}, ], "name": "permit", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "scaledBalanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "scaledTotalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "symbol", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "sender", "type": "address"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "from", "type": "address"}, {"internalType": "address", "name": "to", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}, ], "name": "transferOnLiquidation", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "target", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transferUnderlyingTo", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "nonpayable", "type": "function", }, ]
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/eth/oracles/abis/aave_abis.py
0.566019
0.415847
aave_abis.py
pypi
curve_address_provider_abi = [ { "name": "NewAddressIdentifier", "inputs": [ {"type": "uint256", "name": "id", "indexed": True}, {"type": "address", "name": "addr", "indexed": False}, {"type": "string", "name": "description", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "AddressModified", "inputs": [ {"type": "uint256", "name": "id", "indexed": True}, {"type": "address", "name": "new_address", "indexed": False}, {"type": "uint256", "name": "version", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "CommitNewAdmin", "inputs": [ {"type": "uint256", "name": "deadline", "indexed": True}, {"type": "address", "name": "admin", "indexed": True}, ], "anonymous": False, "type": "event", }, { "name": "NewAdmin", "inputs": [{"type": "address", "name": "admin", "indexed": True}], "anonymous": False, "type": "event", }, { "outputs": [], "inputs": [{"type": "address", "name": "_admin"}], "stateMutability": "nonpayable", "type": "constructor", }, { "name": "get_registry", "outputs": [{"type": "address", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 1061, }, { "name": "max_id", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 1258, }, { "name": "get_address", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "uint256", "name": "_id"}], "stateMutability": "view", "type": "function", "gas": 1308, }, { "name": "add_new_id", "outputs": [{"type": "uint256", "name": ""}], "inputs": [ {"type": "address", "name": "_address"}, {"type": "string", "name": "_description"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 291275, }, { "name": "set_address", "outputs": [{"type": "bool", "name": ""}], "inputs": [ {"type": "uint256", "name": "_id"}, {"type": "address", "name": "_address"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 182430, }, { "name": "unset_address", "outputs": [{"type": "bool", "name": ""}], "inputs": [{"type": "uint256", "name": "_id"}], "stateMutability": "nonpayable", "type": "function", "gas": 101348, }, { "name": "commit_transfer_ownership", "outputs": [{"type": "bool", "name": ""}], "inputs": [{"type": "address", "name": "_new_admin"}], "stateMutability": "nonpayable", "type": "function", "gas": 74048, }, { "name": "apply_transfer_ownership", "outputs": [{"type": "bool", "name": ""}], "inputs": [], "stateMutability": "nonpayable", "type": "function", "gas": 60125, }, { "name": "revert_transfer_ownership", "outputs": [{"type": "bool", "name": ""}], "inputs": [], "stateMutability": "nonpayable", "type": "function", "gas": 21400, }, { "name": "admin", "outputs": [{"type": "address", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 1331, }, { "name": "transfer_ownership_deadline", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 1361, }, { "name": "future_admin", "outputs": [{"type": "address", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 1391, }, { "name": "get_id_info", "outputs": [ {"type": "address", "name": "addr"}, {"type": "bool", "name": "is_active"}, {"type": "uint256", "name": "version"}, {"type": "uint256", "name": "last_modified"}, {"type": "string", "name": "description"}, ], "inputs": [{"type": "uint256", "name": "arg0"}], "stateMutability": "view", "type": "function", "gas": 12168, }, ] curve_registry_abi = [ { "name": "PoolAdded", "inputs": [ {"type": "address", "name": "pool", "indexed": True}, {"type": "bytes", "name": "rate_method_id", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "PoolRemoved", "inputs": [{"type": "address", "name": "pool", "indexed": True}], "anonymous": False, "type": "event", }, { "outputs": [], "inputs": [ {"type": "address", "name": "_address_provider"}, {"type": "address", "name": "_gauge_controller"}, ], "stateMutability": "nonpayable", "type": "constructor", }, { "name": "find_pool_for_coins", "outputs": [{"type": "address", "name": ""}], "inputs": [ {"type": "address", "name": "_from"}, {"type": "address", "name": "_to"}, ], "stateMutability": "view", "type": "function", }, { "name": "find_pool_for_coins", "outputs": [{"type": "address", "name": ""}], "inputs": [ {"type": "address", "name": "_from"}, {"type": "address", "name": "_to"}, {"type": "uint256", "name": "i"}, ], "stateMutability": "view", "type": "function", }, { "name": "get_n_coins", "outputs": [{"type": "uint256[2]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 1704, }, { "name": "get_coins", "outputs": [{"type": "address[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 12285, }, { "name": "get_underlying_coins", "outputs": [{"type": "address[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 12347, }, { "name": "get_decimals", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 8199, }, { "name": "get_underlying_decimals", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 8261, }, { "name": "get_rates", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 34780, }, { "name": "get_gauges", "outputs": [ {"type": "address[10]", "name": ""}, {"type": "int128[10]", "name": ""}, ], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 20310, }, { "name": "get_balances", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 16818, }, { "name": "get_underlying_balances", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 158953, }, { "name": "get_virtual_price_from_lp_token", "outputs": [{"type": "uint256", "name": ""}], "inputs": [{"type": "address", "name": "_token"}], "stateMutability": "view", "type": "function", "gas": 2080, }, { "name": "get_A", "outputs": [{"type": "uint256", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 1198, }, { "name": "get_parameters", "outputs": [ {"type": "uint256", "name": "A"}, {"type": "uint256", "name": "future_A"}, {"type": "uint256", "name": "fee"}, {"type": "uint256", "name": "admin_fee"}, {"type": "uint256", "name": "future_fee"}, {"type": "uint256", "name": "future_admin_fee"}, {"type": "address", "name": "future_owner"}, {"type": "uint256", "name": "initial_A"}, {"type": "uint256", "name": "initial_A_time"}, {"type": "uint256", "name": "future_A_time"}, ], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 6458, }, { "name": "get_fees", "outputs": [{"type": "uint256[2]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 1603, }, { "name": "get_admin_balances", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 36719, }, { "name": "get_coin_indices", "outputs": [ {"type": "int128", "name": ""}, {"type": "int128", "name": ""}, {"type": "bool", "name": ""}, ], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "address", "name": "_from"}, {"type": "address", "name": "_to"}, ], "stateMutability": "view", "type": "function", "gas": 27456, }, { "name": "estimate_gas_used", "outputs": [{"type": "uint256", "name": ""}], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "address", "name": "_from"}, {"type": "address", "name": "_to"}, ], "stateMutability": "view", "type": "function", "gas": 32329, }, { "name": "add_pool", "outputs": [], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "uint256", "name": "_n_coins"}, {"type": "address", "name": "_lp_token"}, {"type": "bytes32", "name": "_rate_method_id"}, {"type": "uint256", "name": "_decimals"}, {"type": "uint256", "name": "_underlying_decimals"}, {"type": "bool", "name": "_has_initial_A"}, {"type": "bool", "name": "_is_v1"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 10196577, }, { "name": "add_pool_without_underlying", "outputs": [], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "uint256", "name": "_n_coins"}, {"type": "address", "name": "_lp_token"}, {"type": "bytes32", "name": "_rate_method_id"}, {"type": "uint256", "name": "_decimals"}, {"type": "uint256", "name": "_use_rates"}, {"type": "bool", "name": "_has_initial_A"}, {"type": "bool", "name": "_is_v1"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 5590664, }, { "name": "add_metapool", "outputs": [], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "uint256", "name": "_n_coins"}, {"type": "address", "name": "_lp_token"}, {"type": "uint256", "name": "_decimals"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 10226976, }, { "name": "remove_pool", "outputs": [], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "nonpayable", "type": "function", "gas": 779646579509, }, { "name": "set_pool_gas_estimates", "outputs": [], "inputs": [ {"type": "address[5]", "name": "_addr"}, {"type": "uint256[2][5]", "name": "_amount"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 355578, }, { "name": "set_coin_gas_estimates", "outputs": [], "inputs": [ {"type": "address[10]", "name": "_addr"}, {"type": "uint256[10]", "name": "_amount"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 357165, }, { "name": "set_gas_estimate_contract", "outputs": [], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "address", "name": "_estimator"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 37747, }, { "name": "set_liquidity_gauges", "outputs": [], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "address[10]", "name": "_liquidity_gauges"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 365793, }, { "name": "address_provider", "outputs": [{"type": "address", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 2111, }, { "name": "gauge_controller", "outputs": [{"type": "address", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 2141, }, { "name": "pool_list", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "uint256", "name": "arg0"}], "stateMutability": "view", "type": "function", "gas": 2280, }, { "name": "pool_count", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 2201, }, { "name": "get_pool_from_lp_token", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "address", "name": "arg0"}], "stateMutability": "view", "type": "function", "gas": 2446, }, { "name": "get_lp_token", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "address", "name": "arg0"}], "stateMutability": "view", "type": "function", "gas": 2476, }, ] curve_pool_abi = [ { "name": "TokenExchange", "inputs": [ {"type": "address", "name": "buyer", "indexed": True}, {"type": "int128", "name": "sold_id", "indexed": False}, {"type": "uint256", "name": "tokens_sold", "indexed": False}, {"type": "int128", "name": "bought_id", "indexed": False}, {"type": "uint256", "name": "tokens_bought", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "TokenExchangeUnderlying", "inputs": [ {"type": "address", "name": "buyer", "indexed": True}, {"type": "int128", "name": "sold_id", "indexed": False}, {"type": "uint256", "name": "tokens_sold", "indexed": False}, {"type": "int128", "name": "bought_id", "indexed": False}, {"type": "uint256", "name": "tokens_bought", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "AddLiquidity", "inputs": [ {"type": "address", "name": "provider", "indexed": True}, {"type": "uint256[4]", "name": "token_amounts", "indexed": False}, {"type": "uint256[4]", "name": "fees", "indexed": False}, {"type": "uint256", "name": "invariant", "indexed": False}, {"type": "uint256", "name": "token_supply", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "RemoveLiquidity", "inputs": [ {"type": "address", "name": "provider", "indexed": True}, {"type": "uint256[4]", "name": "token_amounts", "indexed": False}, {"type": "uint256[4]", "name": "fees", "indexed": False}, {"type": "uint256", "name": "token_supply", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "RemoveLiquidityImbalance", "inputs": [ {"type": "address", "name": "provider", "indexed": True}, {"type": "uint256[4]", "name": "token_amounts", "indexed": False}, {"type": "uint256[4]", "name": "fees", "indexed": False}, {"type": "uint256", "name": "invariant", "indexed": False}, {"type": "uint256", "name": "token_supply", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "CommitNewAdmin", "inputs": [ {"type": "uint256", "name": "deadline", "indexed": True, "unit": "sec"}, {"type": "address", "name": "admin", "indexed": True}, ], "anonymous": False, "type": "event", }, { "name": "NewAdmin", "inputs": [{"type": "address", "name": "admin", "indexed": True}], "anonymous": False, "type": "event", }, { "name": "CommitNewParameters", "inputs": [ {"type": "uint256", "name": "deadline", "indexed": True, "unit": "sec"}, {"type": "uint256", "name": "A", "indexed": False}, {"type": "uint256", "name": "fee", "indexed": False}, {"type": "uint256", "name": "admin_fee", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "NewParameters", "inputs": [ {"type": "uint256", "name": "A", "indexed": False}, {"type": "uint256", "name": "fee", "indexed": False}, {"type": "uint256", "name": "admin_fee", "indexed": False}, ], "anonymous": False, "type": "event", }, { "outputs": [], "inputs": [ {"type": "address[4]", "name": "_coins"}, {"type": "address[4]", "name": "_underlying_coins"}, {"type": "address", "name": "_pool_token"}, {"type": "uint256", "name": "_A"}, {"type": "uint256", "name": "_fee"}, ], "constant": False, "payable": False, "type": "constructor", }, { "name": "get_virtual_price", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 1570535, }, { "name": "calc_token_amount", "outputs": [{"type": "uint256", "name": ""}], "inputs": [ {"type": "uint256[4]", "name": "amounts"}, {"type": "bool", "name": "deposit"}, ], "constant": True, "payable": False, "type": "function", "gas": 6103471, }, { "name": "add_liquidity", "outputs": [], "inputs": [ {"type": "uint256[4]", "name": "amounts"}, {"type": "uint256", "name": "min_mint_amount"}, ], "constant": False, "payable": False, "type": "function", "gas": 9331701, }, { "name": "get_dy", "outputs": [{"type": "uint256", "name": ""}], "inputs": [ {"type": "int128", "name": "i"}, {"type": "int128", "name": "j"}, {"type": "uint256", "name": "dx"}, ], "constant": True, "payable": False, "type": "function", "gas": 3489637, }, { "name": "get_dy_underlying", "outputs": [{"type": "uint256", "name": ""}], "inputs": [ {"type": "int128", "name": "i"}, {"type": "int128", "name": "j"}, {"type": "uint256", "name": "dx"}, ], "constant": True, "payable": False, "type": "function", "gas": 3489467, }, { "name": "exchange", "outputs": [], "inputs": [ {"type": "int128", "name": "i"}, {"type": "int128", "name": "j"}, {"type": "uint256", "name": "dx"}, {"type": "uint256", "name": "min_dy"}, ], "constant": False, "payable": False, "type": "function", "gas": 7034253, }, { "name": "exchange_underlying", "outputs": [], "inputs": [ {"type": "int128", "name": "i"}, {"type": "int128", "name": "j"}, {"type": "uint256", "name": "dx"}, {"type": "uint256", "name": "min_dy"}, ], "constant": False, "payable": False, "type": "function", "gas": 7050488, }, { "name": "remove_liquidity", "outputs": [], "inputs": [ {"type": "uint256", "name": "_amount"}, {"type": "uint256[4]", "name": "min_amounts"}, ], "constant": False, "payable": False, "type": "function", "gas": 241191, }, { "name": "remove_liquidity_imbalance", "outputs": [], "inputs": [ {"type": "uint256[4]", "name": "amounts"}, {"type": "uint256", "name": "max_burn_amount"}, ], "constant": False, "payable": False, "type": "function", "gas": 9330864, }, { "name": "commit_new_parameters", "outputs": [], "inputs": [ {"type": "uint256", "name": "amplification"}, {"type": "uint256", "name": "new_fee"}, {"type": "uint256", "name": "new_admin_fee"}, ], "constant": False, "payable": False, "type": "function", "gas": 146045, }, { "name": "apply_new_parameters", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 133452, }, { "name": "revert_new_parameters", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 21775, }, { "name": "commit_transfer_ownership", "outputs": [], "inputs": [{"type": "address", "name": "_owner"}], "constant": False, "payable": False, "type": "function", "gas": 74452, }, { "name": "apply_transfer_ownership", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 60508, }, { "name": "revert_transfer_ownership", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 21865, }, { "name": "withdraw_admin_fees", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 23448, }, { "name": "kill_me", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 37818, }, { "name": "unkill_me", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 21955, }, { "name": "coins", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "int128", "name": "arg0"}], "constant": True, "payable": False, "type": "function", "gas": 2130, }, { "name": "underlying_coins", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "int128", "name": "arg0"}], "constant": True, "payable": False, "type": "function", "gas": 2160, }, { "name": "balances", "outputs": [{"type": "uint256", "name": ""}], "inputs": [{"type": "int128", "name": "arg0"}], "constant": True, "payable": False, "type": "function", "gas": 2190, }, { "name": "A", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2021, }, { "name": "fee", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2051, }, { "name": "admin_fee", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2081, }, { "name": "owner", "outputs": [{"type": "address", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2111, }, { "name": "admin_actions_deadline", "outputs": [{"type": "uint256", "unit": "sec", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2141, }, { "name": "transfer_ownership_deadline", "outputs": [{"type": "uint256", "unit": "sec", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2171, }, { "name": "future_A", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2201, }, { "name": "future_fee", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2231, }, { "name": "future_admin_fee", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2261, }, { "name": "future_owner", "outputs": [{"type": "address", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2291, }, ]
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/eth/oracles/abis/curve_abis.py
0.663124
0.531149
curve_abis.py
pypi
cream_ctoken_abi = [ { "inputs": [ {"internalType": "address", "name": "underlying_", "type": "address"}, { "internalType": "contract ComptrollerInterface", "name": "comptroller_", "type": "address", }, { "internalType": "contract InterestRateModel", "name": "interestRateModel_", "type": "address", }, { "internalType": "uint256", "name": "initialExchangeRateMantissa_", "type": "uint256", }, {"internalType": "string", "name": "name_", "type": "string"}, {"internalType": "string", "name": "symbol_", "type": "string"}, {"internalType": "uint8", "name": "decimals_", "type": "uint8"}, {"internalType": "address payable", "name": "admin_", "type": "address"}, {"internalType": "address", "name": "implementation_", "type": "address"}, { "internalType": "bytes", "name": "becomeImplementationData", "type": "bytes", }, ], "payable": False, "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint256", "name": "cashPrior", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "interestAccumulated", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "borrowIndex", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "totalBorrows", "type": "uint256", }, ], "name": "AccrueInterest", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": True, "internalType": "address", "name": "spender", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "borrower", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "borrowAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "accountBorrows", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "totalBorrows", "type": "uint256", }, ], "name": "Borrow", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint256", "name": "error", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "info", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "detail", "type": "uint256", }, ], "name": "Failure", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "liquidator", "type": "address", }, { "indexed": False, "internalType": "address", "name": "borrower", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "repayAmount", "type": "uint256", }, { "indexed": False, "internalType": "address", "name": "cTokenCollateral", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "seizeTokens", "type": "uint256", }, ], "name": "LiquidateBorrow", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "minter", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "mintAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "mintTokens", "type": "uint256", }, ], "name": "Mint", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "oldAdmin", "type": "address", }, { "indexed": False, "internalType": "address", "name": "newAdmin", "type": "address", }, ], "name": "NewAdmin", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "contract ComptrollerInterface", "name": "oldComptroller", "type": "address", }, { "indexed": False, "internalType": "contract ComptrollerInterface", "name": "newComptroller", "type": "address", }, ], "name": "NewComptroller", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "oldImplementation", "type": "address", }, { "indexed": False, "internalType": "address", "name": "newImplementation", "type": "address", }, ], "name": "NewImplementation", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "contract InterestRateModel", "name": "oldInterestRateModel", "type": "address", }, { "indexed": False, "internalType": "contract InterestRateModel", "name": "newInterestRateModel", "type": "address", }, ], "name": "NewMarketInterestRateModel", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "oldPendingAdmin", "type": "address", }, { "indexed": False, "internalType": "address", "name": "newPendingAdmin", "type": "address", }, ], "name": "NewPendingAdmin", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint256", "name": "oldReserveFactorMantissa", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "newReserveFactorMantissa", "type": "uint256", }, ], "name": "NewReserveFactor", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "redeemer", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "redeemAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "redeemTokens", "type": "uint256", }, ], "name": "Redeem", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "payer", "type": "address", }, { "indexed": False, "internalType": "address", "name": "borrower", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "repayAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "accountBorrows", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "totalBorrows", "type": "uint256", }, ], "name": "RepayBorrow", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "benefactor", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "addAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "newTotalReserves", "type": "uint256", }, ], "name": "ReservesAdded", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "admin", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "reduceAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "newTotalReserves", "type": "uint256", }, ], "name": "ReservesReduced", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "to", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, {"payable": True, "stateMutability": "payable", "type": "fallback"}, { "constant": False, "inputs": [], "name": "_acceptAdmin", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "uint256", "name": "addAmount", "type": "uint256"}], "name": "_addReserves", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "reduceAmount", "type": "uint256"} ], "name": "_reduceReserves", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ { "internalType": "contract ComptrollerInterface", "name": "newComptroller", "type": "address", } ], "name": "_setComptroller", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "implementation_", "type": "address"}, {"internalType": "bool", "name": "allowResign", "type": "bool"}, { "internalType": "bytes", "name": "becomeImplementationData", "type": "bytes", }, ], "name": "_setImplementation", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ { "internalType": "contract InterestRateModel", "name": "newInterestRateModel", "type": "address", } ], "name": "_setInterestRateModel", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ { "internalType": "address payable", "name": "newPendingAdmin", "type": "address", } ], "name": "_setPendingAdmin", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ { "internalType": "uint256", "name": "newReserveFactorMantissa", "type": "uint256", } ], "name": "_setReserveFactor", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "accrualBlockNumber", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [], "name": "accrueInterest", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "admin", "outputs": [{"internalType": "address payable", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}, ], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "owner", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [{"internalType": "address", "name": "owner", "type": "address"}], "name": "balanceOfUnderlying", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "borrowAmount", "type": "uint256"} ], "name": "borrow", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "borrowBalanceCurrent", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "borrowBalanceStored", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "borrowIndex", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "borrowRatePerBlock", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "comptroller", "outputs": [ { "internalType": "contract ComptrollerInterface", "name": "", "type": "address", } ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "decimals", "outputs": [{"internalType": "uint8", "name": "", "type": "uint8"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [{"internalType": "bytes", "name": "data", "type": "bytes"}], "name": "delegateToImplementation", "outputs": [{"internalType": "bytes", "name": "", "type": "bytes"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "bytes", "name": "data", "type": "bytes"}], "name": "delegateToViewImplementation", "outputs": [{"internalType": "bytes", "name": "", "type": "bytes"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [], "name": "exchangeRateCurrent", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "exchangeRateStored", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "getAccountSnapshot", "outputs": [ {"internalType": "uint256", "name": "", "type": "uint256"}, {"internalType": "uint256", "name": "", "type": "uint256"}, {"internalType": "uint256", "name": "", "type": "uint256"}, {"internalType": "uint256", "name": "", "type": "uint256"}, ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getCash", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "implementation", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "interestRateModel", "outputs": [ { "internalType": "contract InterestRateModel", "name": "", "type": "address", } ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "isCToken", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "borrower", "type": "address"}, {"internalType": "uint256", "name": "repayAmount", "type": "uint256"}, { "internalType": "contract CTokenInterface", "name": "cTokenCollateral", "type": "address", }, ], "name": "liquidateBorrow", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "mintAmount", "type": "uint256"} ], "name": "mint", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "name", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "pendingAdmin", "outputs": [{"internalType": "address payable", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "redeemTokens", "type": "uint256"} ], "name": "redeem", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "redeemAmount", "type": "uint256"} ], "name": "redeemUnderlying", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "repayAmount", "type": "uint256"} ], "name": "repayBorrow", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "reserveFactorMantissa", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "liquidator", "type": "address"}, {"internalType": "address", "name": "borrower", "type": "address"}, {"internalType": "uint256", "name": "seizeTokens", "type": "uint256"}, ], "name": "seize", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "supplyRatePerBlock", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "symbol", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "totalBorrows", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [], "name": "totalBorrowsCurrent", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "totalReserves", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "src", "type": "address"}, {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "underlying", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, ]
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/eth/oracles/abis/cream_abis.py
0.577495
0.492249
cream_abis.py
pypi
multicall_v2_abi = [ { "inputs": [ { "components": [ {"internalType": "address", "name": "target", "type": "address"}, {"internalType": "bytes", "name": "callData", "type": "bytes"}, ], "internalType": "struct Multicall2.Call[]", "name": "calls", "type": "tuple[]", } ], "name": "aggregate", "outputs": [ {"internalType": "uint256", "name": "blockNumber", "type": "uint256"}, {"internalType": "bytes[]", "name": "returnData", "type": "bytes[]"}, ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "components": [ {"internalType": "address", "name": "target", "type": "address"}, {"internalType": "bytes", "name": "callData", "type": "bytes"}, ], "internalType": "struct Multicall2.Call[]", "name": "calls", "type": "tuple[]", } ], "name": "blockAndAggregate", "outputs": [ {"internalType": "uint256", "name": "blockNumber", "type": "uint256"}, {"internalType": "bytes32", "name": "blockHash", "type": "bytes32"}, { "components": [ {"internalType": "bool", "name": "success", "type": "bool"}, {"internalType": "bytes", "name": "returnData", "type": "bytes"}, ], "internalType": "struct Multicall2.Result[]", "name": "returnData", "type": "tuple[]", }, ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "blockNumber", "type": "uint256"} ], "name": "getBlockHash", "outputs": [ {"internalType": "bytes32", "name": "blockHash", "type": "bytes32"} ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "getBlockNumber", "outputs": [ {"internalType": "uint256", "name": "blockNumber", "type": "uint256"} ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "getCurrentBlockCoinbase", "outputs": [{"internalType": "address", "name": "coinbase", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "getCurrentBlockDifficulty", "outputs": [ {"internalType": "uint256", "name": "difficulty", "type": "uint256"} ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "getCurrentBlockGasLimit", "outputs": [{"internalType": "uint256", "name": "gaslimit", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "getCurrentBlockTimestamp", "outputs": [ {"internalType": "uint256", "name": "timestamp", "type": "uint256"} ], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "address", "name": "addr", "type": "address"}], "name": "getEthBalance", "outputs": [{"internalType": "uint256", "name": "balance", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "getLastBlockHash", "outputs": [ {"internalType": "bytes32", "name": "blockHash", "type": "bytes32"} ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "bool", "name": "requireSuccess", "type": "bool"}, { "components": [ {"internalType": "address", "name": "target", "type": "address"}, {"internalType": "bytes", "name": "callData", "type": "bytes"}, ], "internalType": "struct Multicall2.Call[]", "name": "calls", "type": "tuple[]", }, ], "name": "tryAggregate", "outputs": [ { "components": [ {"internalType": "bool", "name": "success", "type": "bool"}, {"internalType": "bytes", "name": "returnData", "type": "bytes"}, ], "internalType": "struct Multicall2.Result[]", "name": "returnData", "type": "tuple[]", } ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "bool", "name": "requireSuccess", "type": "bool"}, { "components": [ {"internalType": "address", "name": "target", "type": "address"}, {"internalType": "bytes", "name": "callData", "type": "bytes"}, ], "internalType": "struct Multicall2.Call[]", "name": "calls", "type": "tuple[]", }, ], "name": "tryBlockAndAggregate", "outputs": [ {"internalType": "uint256", "name": "blockNumber", "type": "uint256"}, {"internalType": "bytes32", "name": "blockHash", "type": "bytes32"}, { "components": [ {"internalType": "bool", "name": "success", "type": "bool"}, {"internalType": "bytes", "name": "returnData", "type": "bytes"}, ], "internalType": "struct Multicall2.Result[]", "name": "returnData", "type": "tuple[]", }, ], "stateMutability": "nonpayable", "type": "function", }, ] multicall_v2_bytecode = b'`\x80`@R4\x80\x15a\x00\x10W`\x00\x80\xfd[Pa\t\xd3\x80a\x00 `\x009`\x00\xf3\xfe`\x80`@R4\x80\x15a\x00\x10W`\x00\x80\xfd[P`\x046\x10a\x00\xb4W`\x005`\xe0\x1c\x80crB]\x9d\x11a\x00qW\x80crB]\x9d\x14a\x01:W\x80c\x86\xd5\x16\xe8\x14a\x01@W\x80c\xa8\xb0WN\x14a\x01FW\x80c\xbc\xe3\x8b\xd7\x14a\x01TW\x80c\xc3\x07\x7f\xa9\x14a\x01tW\x80c\xee\x82\xac^\x14a\x01\x87Wa\x00\xb4V[\x80c\x0f(\xc9}\x14a\x00\xb9W\x80c%-\xbaB\x14a\x00\xceW\x80c\'\xe8mn\x14a\x00\xefW\x80c9\x95B\xe9\x14a\x00\xf7W\x80cB\xcb\xb1\\\x14a\x01\x19W\x80cM#\x01\xcc\x14a\x01\x1fW[`\x00\x80\xfd[B[`@Q\x90\x81R` \x01[`@Q\x80\x91\x03\x90\xf3[a\x00\xe1a\x00\xdc6`\x04a\x06\xe2V[a\x01\x99V[`@Qa\x00\xc5\x92\x91\x90a\x08NV[a\x00\xbba\x03YV[a\x01\na\x01\x056`\x04a\x07\x1dV[a\x03lV[`@Qa\x00\xc5\x93\x92\x91\x90a\x08\xb6V[Ca\x00\xbbV[a\x00\xbba\x01-6`\x04a\x06\xc1V[`\x01`\x01`\xa0\x1b\x03\x161\x90V[Da\x00\xbbV[Ea\x00\xbbV[`@QA\x81R` \x01a\x00\xc5V[a\x01ga\x01b6`\x04a\x07\x1dV[a\x03\x84V[`@Qa\x00\xc5\x91\x90a\x08;V[a\x01\na\x01\x826`\x04a\x06\xe2V[a\x05vV[a\x00\xbba\x01\x956`\x04a\x07oV[@\x90V[\x80QC\x90``\x90g\xff\xff\xff\xff\xff\xff\xff\xff\x81\x11\x15a\x01\xc6WcNH{q`\xe0\x1b`\x00R`A`\x04R`$`\x00\xfd[`@Q\x90\x80\x82R\x80` \x02` \x01\x82\x01`@R\x80\x15a\x01\xf9W\x81` \x01[``\x81R` \x01\x90`\x01\x90\x03\x90\x81a\x01\xe4W\x90P[P\x90P`\x00[\x83Q\x81\x10\x15a\x03SW`\x00\x80\x85\x83\x81Q\x81\x10a\x02+WcNH{q`\xe0\x1b`\x00R`2`\x04R`$`\x00\xfd[` \x02` \x01\x01Q`\x00\x01Q`\x01`\x01`\xa0\x1b\x03\x16\x86\x84\x81Q\x81\x10a\x02`WcNH{q`\xe0\x1b`\x00R`2`\x04R`$`\x00\xfd[` \x02` \x01\x01Q` \x01Q`@Qa\x02y\x91\x90a\x08\x1fV[`\x00`@Q\x80\x83\x03\x81`\x00\x86Z\xf1\x91PP=\x80`\x00\x81\x14a\x02\xb6W`@Q\x91P`\x1f\x19`?=\x01\x16\x82\x01`@R=\x82R=`\x00` \x84\x01>a\x02\xbbV[``\x91P[P\x91P\x91P\x81a\x03\x12W`@QbF\x1b\xcd`\xe5\x1b\x81R` `\x04\x82\x01\x81\x90R`$\x82\x01R\x7fMulticall aggregate: call failed`D\x82\x01R`d\x01[`@Q\x80\x91\x03\x90\xfd[\x80\x84\x84\x81Q\x81\x10a\x033WcNH{q`\xe0\x1b`\x00R`2`\x04R`$`\x00\xfd[` \x02` \x01\x01\x81\x90RPPP\x80\x80a\x03K\x90a\tVV[\x91PPa\x01\xffV[P\x91P\x91V[`\x00a\x03f`\x01Ca\t\x0fV[@\x90P\x90V[C\x80@``a\x03{\x85\x85a\x03\x84V[\x90P\x92P\x92P\x92V[``\x81Qg\xff\xff\xff\xff\xff\xff\xff\xff\x81\x11\x15a\x03\xaeWcNH{q`\xe0\x1b`\x00R`A`\x04R`$`\x00\xfd[`@Q\x90\x80\x82R\x80` \x02` \x01\x82\x01`@R\x80\x15a\x03\xf4W\x81` \x01[`@\x80Q\x80\x82\x01\x90\x91R`\x00\x81R``` \x82\x01R\x81R` \x01\x90`\x01\x90\x03\x90\x81a\x03\xccW\x90P[P\x90P`\x00[\x82Q\x81\x10\x15a\x05oW`\x00\x80\x84\x83\x81Q\x81\x10a\x04&WcNH{q`\xe0\x1b`\x00R`2`\x04R`$`\x00\xfd[` \x02` \x01\x01Q`\x00\x01Q`\x01`\x01`\xa0\x1b\x03\x16\x85\x84\x81Q\x81\x10a\x04[WcNH{q`\xe0\x1b`\x00R`2`\x04R`$`\x00\xfd[` \x02` \x01\x01Q` \x01Q`@Qa\x04t\x91\x90a\x08\x1fV[`\x00`@Q\x80\x83\x03\x81`\x00\x86Z\xf1\x91PP=\x80`\x00\x81\x14a\x04\xb1W`@Q\x91P`\x1f\x19`?=\x01\x16\x82\x01`@R=\x82R=`\x00` \x84\x01>a\x04\xb6V[``\x91P[P\x91P\x91P\x85\x15a\x05\x18W\x81a\x05\x18W`@QbF\x1b\xcd`\xe5\x1b\x81R` `\x04\x82\x01R`!`$\x82\x01R\x7fMulticall2 aggregate: call faile`D\x82\x01R`\x19`\xfa\x1b`d\x82\x01R`\x84\x01a\x03\tV[`@Q\x80`@\x01`@R\x80\x83\x15\x15\x81R` \x01\x82\x81RP\x84\x84\x81Q\x81\x10a\x05OWcNH{q`\xe0\x1b`\x00R`2`\x04R`$`\x00\xfd[` \x02` \x01\x01\x81\x90RPPP\x80\x80a\x05g\x90a\tVV[\x91PPa\x03\xfaV[P\x92\x91PPV[`\x00\x80``a\x05\x86`\x01\x85a\x03lV[\x91\x96\x90\x95P\x90\x93P\x91PPV[\x805`\x01`\x01`\xa0\x1b\x03\x81\x16\x81\x14a\x05\xaaW`\x00\x80\xfd[\x91\x90PV[`\x00\x82`\x1f\x83\x01\x12a\x05\xbfW\x80\x81\xfd[\x815` g\xff\xff\xff\xff\xff\xff\xff\xff\x80\x83\x11\x15a\x05\xdcWa\x05\xdca\t\x87V[a\x05\xe9\x82\x83\x85\x02\x01a\x08\xdeV[\x83\x81R\x82\x81\x01\x90\x86\x84\x01\x86[\x86\x81\x10\x15a\x06\xb3W\x815\x89\x01`@`\x1f\x19\x81\x81\x84\x8f\x03\x01\x12\x15a\x06\x16W\x8a\x8b\xfd[a\x06\x1f\x82a\x08\xdeV[a\x06*\x8a\x85\x01a\x05\x93V[\x81R\x82\x84\x015\x89\x81\x11\x15a\x06<W\x8c\x8d\xfd[\x80\x85\x01\x94PP\x8d`?\x85\x01\x12a\x06PW\x8b\x8c\xfd[\x89\x84\x015\x89\x81\x11\x15a\x06dWa\x06da\t\x87V[a\x06t\x8b\x84`\x1f\x84\x01\x16\x01a\x08\xdeV[\x92P\x80\x83R\x8e\x84\x82\x87\x01\x01\x11\x15a\x06\x89W\x8c\x8d\xfd[\x80\x84\x86\x01\x8c\x85\x017\x82\x01\x8a\x01\x8c\x90R\x80\x8a\x01\x91\x90\x91R\x86RPP\x92\x85\x01\x92\x90\x85\x01\x90`\x01\x01a\x05\xf5V[P\x90\x98\x97PPPPPPPPV[`\x00` \x82\x84\x03\x12\x15a\x06\xd2W\x80\x81\xfd[a\x06\xdb\x82a\x05\x93V[\x93\x92PPPV[`\x00` \x82\x84\x03\x12\x15a\x06\xf3W\x80\x81\xfd[\x815g\xff\xff\xff\xff\xff\xff\xff\xff\x81\x11\x15a\x07\tW\x81\x82\xfd[a\x07\x15\x84\x82\x85\x01a\x05\xafV[\x94\x93PPPPV[`\x00\x80`@\x83\x85\x03\x12\x15a\x07/W\x80\x81\xfd[\x825\x80\x15\x15\x81\x14a\x07>W\x81\x82\xfd[\x91P` \x83\x015g\xff\xff\xff\xff\xff\xff\xff\xff\x81\x11\x15a\x07YW\x81\x82\xfd[a\x07e\x85\x82\x86\x01a\x05\xafV[\x91PP\x92P\x92\x90PV[`\x00` \x82\x84\x03\x12\x15a\x07\x80W\x80\x81\xfd[P5\x91\x90PV[`\x00\x82\x82Q\x80\x85R` \x80\x86\x01\x95P\x80\x81\x83\x02\x84\x01\x01\x81\x86\x01\x85[\x84\x81\x10\x15a\x07\xe6W\x85\x83\x03`\x1f\x19\x01\x89R\x81Q\x80Q\x15\x15\x84R\x84\x01Q`@\x85\x85\x01\x81\x90Ra\x07\xd2\x81\x86\x01\x83a\x07\xf3V[\x9a\x86\x01\x9a\x94PPP\x90\x83\x01\x90`\x01\x01a\x07\xa2V[P\x90\x97\x96PPPPPPPV[`\x00\x81Q\x80\x84Ra\x08\x0b\x81` \x86\x01` \x86\x01a\t&V[`\x1f\x01`\x1f\x19\x16\x92\x90\x92\x01` \x01\x92\x91PPV[`\x00\x82Qa\x081\x81\x84` \x87\x01a\t&V[\x91\x90\x91\x01\x92\x91PPV[`\x00` \x82Ra\x06\xdb` \x83\x01\x84a\x07\x87V[`\x00`@\x82\x01\x84\x83R` `@\x81\x85\x01R\x81\x85Q\x80\x84R``\x86\x01\x91P``\x83\x82\x02\x87\x01\x01\x93P\x82\x87\x01\x85[\x82\x81\x10\x15a\x08\xa8W`_\x19\x88\x87\x03\x01\x84Ra\x08\x96\x86\x83Qa\x07\xf3V[\x95P\x92\x84\x01\x92\x90\x84\x01\x90`\x01\x01a\x08zV[P\x93\x98\x97PPPPPPPPV[`\x00\x84\x82R\x83` \x83\x01R```@\x83\x01Ra\x08\xd5``\x83\x01\x84a\x07\x87V[\x95\x94PPPPPV[`@Q`\x1f\x82\x01`\x1f\x19\x16\x81\x01g\xff\xff\xff\xff\xff\xff\xff\xff\x81\x11\x82\x82\x10\x17\x15a\t\x07Wa\t\x07a\t\x87V[`@R\x91\x90PV[`\x00\x82\x82\x10\x15a\t!Wa\t!a\tqV[P\x03\x90V[`\x00[\x83\x81\x10\x15a\tAW\x81\x81\x01Q\x83\x82\x01R` \x01a\t)V[\x83\x81\x11\x15a\tPW`\x00\x84\x84\x01R[PPPPV[`\x00`\x00\x19\x82\x14\x15a\tjWa\tja\tqV[P`\x01\x01\x90V[cNH{q`\xe0\x1b`\x00R`\x11`\x04R`$`\x00\xfd[cNH{q`\xe0\x1b`\x00R`A`\x04R`$`\x00\xfd\xfe\xa2dipfsX"\x12 g\x87\xfa\xa4\xe9\x95"\xd9\x928\xbf\xcc\xae}\xb6c@m_\xb7m2\xf8S\x95\xe2\x07m73\xa7\xcddsolcC\x00\x08\x02\x003'
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/eth/oracles/abis/makerdao.py
0.492188
0.568595
makerdao.py
pypi
balancer_pool_abi = [ { "inputs": [], "payable": False, "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "src", "type": "address", }, { "indexed": True, "internalType": "address", "name": "dst", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amt", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": True, "inputs": [ { "indexed": True, "internalType": "bytes4", "name": "sig", "type": "bytes4", }, { "indexed": True, "internalType": "address", "name": "caller", "type": "address", }, { "indexed": False, "internalType": "bytes", "name": "data", "type": "bytes", }, ], "name": "LOG_CALL", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "caller", "type": "address", }, { "indexed": True, "internalType": "address", "name": "tokenOut", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "tokenAmountOut", "type": "uint256", }, ], "name": "LOG_EXIT", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "caller", "type": "address", }, { "indexed": True, "internalType": "address", "name": "tokenIn", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "tokenAmountIn", "type": "uint256", }, ], "name": "LOG_JOIN", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "caller", "type": "address", }, { "indexed": True, "internalType": "address", "name": "tokenIn", "type": "address", }, { "indexed": True, "internalType": "address", "name": "tokenOut", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "tokenAmountIn", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "tokenAmountOut", "type": "uint256", }, ], "name": "LOG_SWAP", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "src", "type": "address", }, { "indexed": True, "internalType": "address", "name": "dst", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amt", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "constant": True, "inputs": [], "name": "BONE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "BPOW_PRECISION", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "EXIT_FEE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "INIT_POOL_SUPPLY", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_BOUND_TOKENS", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_BPOW_BASE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_FEE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_IN_RATIO", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_OUT_RATIO", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_TOTAL_WEIGHT", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_WEIGHT", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MIN_BALANCE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MIN_BOUND_TOKENS", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MIN_BPOW_BASE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MIN_FEE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MIN_WEIGHT", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "address", "name": "src", "type": "address"}, {"internalType": "address", "name": "dst", "type": "address"}, ], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amt", "type": "uint256"}, ], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "whom", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "balance", "type": "uint256"}, {"internalType": "uint256", "name": "denorm", "type": "uint256"}, ], "name": "bind", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenBalanceOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcInGivenOut", "outputs": [ {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenBalanceOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcOutGivenIn", "outputs": [ {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightOut", "type": "uint256"}, {"internalType": "uint256", "name": "poolSupply", "type": "uint256"}, {"internalType": "uint256", "name": "totalWeight", "type": "uint256"}, {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcPoolInGivenSingleOut", "outputs": [ {"internalType": "uint256", "name": "poolAmountIn", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightIn", "type": "uint256"}, {"internalType": "uint256", "name": "poolSupply", "type": "uint256"}, {"internalType": "uint256", "name": "totalWeight", "type": "uint256"}, {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcPoolOutGivenSingleIn", "outputs": [ {"internalType": "uint256", "name": "poolAmountOut", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightIn", "type": "uint256"}, {"internalType": "uint256", "name": "poolSupply", "type": "uint256"}, {"internalType": "uint256", "name": "totalWeight", "type": "uint256"}, {"internalType": "uint256", "name": "poolAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcSingleInGivenPoolOut", "outputs": [ {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightOut", "type": "uint256"}, {"internalType": "uint256", "name": "poolSupply", "type": "uint256"}, {"internalType": "uint256", "name": "totalWeight", "type": "uint256"}, {"internalType": "uint256", "name": "poolAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcSingleOutGivenPoolIn", "outputs": [ {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenBalanceOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightOut", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcSpotPrice", "outputs": [ {"internalType": "uint256", "name": "spotPrice", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [], "name": "decimals", "outputs": [{"internalType": "uint8", "name": "", "type": "uint8"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amt", "type": "uint256"}, ], "name": "decreaseApproval", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "poolAmountIn", "type": "uint256"}, {"internalType": "uint256[]", "name": "minAmountsOut", "type": "uint256[]"}, ], "name": "exitPool", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenOut", "type": "address"}, {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "maxPoolAmountIn", "type": "uint256"}, ], "name": "exitswapExternAmountOut", "outputs": [ {"internalType": "uint256", "name": "poolAmountIn", "type": "uint256"} ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenOut", "type": "address"}, {"internalType": "uint256", "name": "poolAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "minAmountOut", "type": "uint256"}, ], "name": "exitswapPoolAmountIn", "outputs": [ {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"} ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [], "name": "finalize", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "getBalance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getColor", "outputs": [{"internalType": "bytes32", "name": "", "type": "bytes32"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getController", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getCurrentTokens", "outputs": [ {"internalType": "address[]", "name": "tokens", "type": "address[]"} ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "getDenormalizedWeight", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getFinalTokens", "outputs": [ {"internalType": "address[]", "name": "tokens", "type": "address[]"} ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "getNormalizedWeight", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getNumTokens", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "address", "name": "tokenOut", "type": "address"}, ], "name": "getSpotPrice", "outputs": [ {"internalType": "uint256", "name": "spotPrice", "type": "uint256"} ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "address", "name": "tokenOut", "type": "address"}, ], "name": "getSpotPriceSansFee", "outputs": [ {"internalType": "uint256", "name": "spotPrice", "type": "uint256"} ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getSwapFee", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getTotalDenormalizedWeight", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "gulp", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amt", "type": "uint256"}, ], "name": "increaseApproval", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "t", "type": "address"}], "name": "isBound", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "isFinalized", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "isPublicSwap", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "poolAmountOut", "type": "uint256"}, {"internalType": "uint256[]", "name": "maxAmountsIn", "type": "uint256[]"}, ], "name": "joinPool", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "minPoolAmountOut", "type": "uint256"}, ], "name": "joinswapExternAmountIn", "outputs": [ {"internalType": "uint256", "name": "poolAmountOut", "type": "uint256"} ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "uint256", "name": "poolAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "maxAmountIn", "type": "uint256"}, ], "name": "joinswapPoolAmountOut", "outputs": [ {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"} ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "name", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "balance", "type": "uint256"}, {"internalType": "uint256", "name": "denorm", "type": "uint256"}, ], "name": "rebind", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "address", "name": "manager", "type": "address"}], "name": "setController", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "bool", "name": "public_", "type": "bool"}], "name": "setPublicSwap", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "uint256", "name": "swapFee", "type": "uint256"}], "name": "setSwapFee", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"}, {"internalType": "address", "name": "tokenOut", "type": "address"}, {"internalType": "uint256", "name": "minAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "maxPrice", "type": "uint256"}, ], "name": "swapExactAmountIn", "outputs": [ {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "spotPriceAfter", "type": "uint256"}, ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "uint256", "name": "maxAmountIn", "type": "uint256"}, {"internalType": "address", "name": "tokenOut", "type": "address"}, {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "maxPrice", "type": "uint256"}, ], "name": "swapExactAmountOut", "outputs": [ {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "spotPriceAfter", "type": "uint256"}, ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "symbol", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amt", "type": "uint256"}, ], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "src", "type": "address"}, {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amt", "type": "uint256"}, ], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "unbind", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, ]
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/eth/oracles/abis/balancer_abis.py
0.493897
0.450299
balancer_abis.py
pypi
YVAULT_ABI = [ { "inputs": [ {"internalType": "address", "name": "_token", "type": "address"}, {"internalType": "address", "name": "_controller", "type": "address"}, ], "payable": False, "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": True, "internalType": "address", "name": "spender", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "to", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "constant": True, "inputs": [ {"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}, ], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "available", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "balance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "controller", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "decimals", "outputs": [{"internalType": "uint8", "name": "", "type": "uint8"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "subtractedValue", "type": "uint256"}, ], "name": "decreaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "uint256", "name": "_amount", "type": "uint256"}], "name": "deposit", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [], "name": "depositAll", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [], "name": "earn", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "getPricePerFullShare", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "governance", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "addedValue", "type": "uint256"}, ], "name": "increaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "max", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "min", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "name", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "_controller", "type": "address"} ], "name": "setController", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "_governance", "type": "address"} ], "name": "setGovernance", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "uint256", "name": "_min", "type": "uint256"}], "name": "setMin", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "string", "name": "_name", "type": "string"}], "name": "setName", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "string", "name": "_symbol", "type": "string"}], "name": "setSymbol", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "symbol", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "token", "outputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "sender", "type": "address"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "uint256", "name": "_shares", "type": "uint256"}], "name": "withdraw", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [], "name": "withdrawAll", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, ] YTOKEN_ABI = [ { "name": "Transfer", "inputs": [ {"name": "sender", "type": "address", "indexed": True}, {"name": "receiver", "type": "address", "indexed": True}, {"name": "value", "type": "uint256", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "Approval", "inputs": [ {"name": "owner", "type": "address", "indexed": True}, {"name": "spender", "type": "address", "indexed": True}, {"name": "value", "type": "uint256", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "StrategyAdded", "inputs": [ {"name": "strategy", "type": "address", "indexed": True}, {"name": "debtRatio", "type": "uint256", "indexed": False}, {"name": "minDebtPerHarvest", "type": "uint256", "indexed": False}, {"name": "maxDebtPerHarvest", "type": "uint256", "indexed": False}, {"name": "performanceFee", "type": "uint256", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "StrategyReported", "inputs": [ {"name": "strategy", "type": "address", "indexed": True}, {"name": "gain", "type": "uint256", "indexed": False}, {"name": "loss", "type": "uint256", "indexed": False}, {"name": "debtPaid", "type": "uint256", "indexed": False}, {"name": "totalGain", "type": "uint256", "indexed": False}, {"name": "totalLoss", "type": "uint256", "indexed": False}, {"name": "totalDebt", "type": "uint256", "indexed": False}, {"name": "debtAdded", "type": "uint256", "indexed": False}, {"name": "debtRatio", "type": "uint256", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "UpdateGovernance", "inputs": [{"name": "governance", "type": "address", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "UpdateManagement", "inputs": [{"name": "management", "type": "address", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "UpdateGuestList", "inputs": [{"name": "guestList", "type": "address", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "UpdateRewards", "inputs": [{"name": "rewards", "type": "address", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "UpdateDepositLimit", "inputs": [{"name": "depositLimit", "type": "uint256", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "UpdatePerformanceFee", "inputs": [{"name": "performanceFee", "type": "uint256", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "UpdateManagementFee", "inputs": [{"name": "managementFee", "type": "uint256", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "UpdateGuardian", "inputs": [{"name": "guardian", "type": "address", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "EmergencyShutdown", "inputs": [{"name": "active", "type": "bool", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "UpdateWithdrawalQueue", "inputs": [{"name": "queue", "type": "address[20]", "indexed": False}], "anonymous": False, "type": "event", }, { "name": "StrategyUpdateDebtRatio", "inputs": [ {"name": "strategy", "type": "address", "indexed": True}, {"name": "debtRatio", "type": "uint256", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "StrategyUpdateMinDebtPerHarvest", "inputs": [ {"name": "strategy", "type": "address", "indexed": True}, {"name": "minDebtPerHarvest", "type": "uint256", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "StrategyUpdateMaxDebtPerHarvest", "inputs": [ {"name": "strategy", "type": "address", "indexed": True}, {"name": "maxDebtPerHarvest", "type": "uint256", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "StrategyUpdatePerformanceFee", "inputs": [ {"name": "strategy", "type": "address", "indexed": True}, {"name": "performanceFee", "type": "uint256", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "StrategyMigrated", "inputs": [ {"name": "oldVersion", "type": "address", "indexed": True}, {"name": "newVersion", "type": "address", "indexed": True}, ], "anonymous": False, "type": "event", }, { "name": "StrategyRevoked", "inputs": [{"name": "strategy", "type": "address", "indexed": True}], "anonymous": False, "type": "event", }, { "name": "StrategyRemovedFromQueue", "inputs": [{"name": "strategy", "type": "address", "indexed": True}], "anonymous": False, "type": "event", }, { "name": "StrategyAddedToQueue", "inputs": [{"name": "strategy", "type": "address", "indexed": True}], "anonymous": False, "type": "event", }, { "stateMutability": "nonpayable", "type": "function", "name": "initialize", "inputs": [ {"name": "token", "type": "address"}, {"name": "governance", "type": "address"}, {"name": "rewards", "type": "address"}, {"name": "nameOverride", "type": "string"}, {"name": "symbolOverride", "type": "string"}, ], "outputs": [], }, { "stateMutability": "nonpayable", "type": "function", "name": "initialize", "inputs": [ {"name": "token", "type": "address"}, {"name": "governance", "type": "address"}, {"name": "rewards", "type": "address"}, {"name": "nameOverride", "type": "string"}, {"name": "symbolOverride", "type": "string"}, {"name": "guardian", "type": "address"}, ], "outputs": [], }, { "stateMutability": "pure", "type": "function", "name": "apiVersion", "inputs": [], "outputs": [{"name": "", "type": "string"}], "gas": 4546, }, { "stateMutability": "nonpayable", "type": "function", "name": "setName", "inputs": [{"name": "name", "type": "string"}], "outputs": [], "gas": 107044, }, { "stateMutability": "nonpayable", "type": "function", "name": "setSymbol", "inputs": [{"name": "symbol", "type": "string"}], "outputs": [], "gas": 71894, }, { "stateMutability": "nonpayable", "type": "function", "name": "setGovernance", "inputs": [{"name": "governance", "type": "address"}], "outputs": [], "gas": 36365, }, { "stateMutability": "nonpayable", "type": "function", "name": "acceptGovernance", "inputs": [], "outputs": [], "gas": 37637, }, { "stateMutability": "nonpayable", "type": "function", "name": "setManagement", "inputs": [{"name": "management", "type": "address"}], "outputs": [], "gas": 37775, }, { "stateMutability": "nonpayable", "type": "function", "name": "setGuestList", "inputs": [{"name": "guestList", "type": "address"}], "outputs": [], "gas": 37805, }, { "stateMutability": "nonpayable", "type": "function", "name": "setRewards", "inputs": [{"name": "rewards", "type": "address"}], "outputs": [], "gas": 37835, }, { "stateMutability": "nonpayable", "type": "function", "name": "setLockedProfitDegration", "inputs": [{"name": "degration", "type": "uint256"}], "outputs": [], "gas": 36519, }, { "stateMutability": "nonpayable", "type": "function", "name": "setDepositLimit", "inputs": [{"name": "limit", "type": "uint256"}], "outputs": [], "gas": 37795, }, { "stateMutability": "nonpayable", "type": "function", "name": "setPerformanceFee", "inputs": [{"name": "fee", "type": "uint256"}], "outputs": [], "gas": 37929, }, { "stateMutability": "nonpayable", "type": "function", "name": "setManagementFee", "inputs": [{"name": "fee", "type": "uint256"}], "outputs": [], "gas": 37959, }, { "stateMutability": "nonpayable", "type": "function", "name": "setGuardian", "inputs": [{"name": "guardian", "type": "address"}], "outputs": [], "gas": 39203, }, { "stateMutability": "nonpayable", "type": "function", "name": "setEmergencyShutdown", "inputs": [{"name": "active", "type": "bool"}], "outputs": [], "gas": 39274, }, { "stateMutability": "nonpayable", "type": "function", "name": "setWithdrawalQueue", "inputs": [{"name": "queue", "type": "address[20]"}], "outputs": [], "gas": 763950, }, { "stateMutability": "nonpayable", "type": "function", "name": "transfer", "inputs": [ {"name": "receiver", "type": "address"}, {"name": "amount", "type": "uint256"}, ], "outputs": [{"name": "", "type": "bool"}], "gas": 76768, }, { "stateMutability": "nonpayable", "type": "function", "name": "transferFrom", "inputs": [ {"name": "sender", "type": "address"}, {"name": "receiver", "type": "address"}, {"name": "amount", "type": "uint256"}, ], "outputs": [{"name": "", "type": "bool"}], "gas": 116531, }, { "stateMutability": "nonpayable", "type": "function", "name": "approve", "inputs": [ {"name": "spender", "type": "address"}, {"name": "amount", "type": "uint256"}, ], "outputs": [{"name": "", "type": "bool"}], "gas": 38271, }, { "stateMutability": "nonpayable", "type": "function", "name": "increaseAllowance", "inputs": [ {"name": "spender", "type": "address"}, {"name": "amount", "type": "uint256"}, ], "outputs": [{"name": "", "type": "bool"}], "gas": 40312, }, { "stateMutability": "nonpayable", "type": "function", "name": "decreaseAllowance", "inputs": [ {"name": "spender", "type": "address"}, {"name": "amount", "type": "uint256"}, ], "outputs": [{"name": "", "type": "bool"}], "gas": 40336, }, { "stateMutability": "nonpayable", "type": "function", "name": "permit", "inputs": [ {"name": "owner", "type": "address"}, {"name": "spender", "type": "address"}, {"name": "amount", "type": "uint256"}, {"name": "expiry", "type": "uint256"}, {"name": "signature", "type": "bytes"}, ], "outputs": [{"name": "", "type": "bool"}], "gas": 81264, }, { "stateMutability": "view", "type": "function", "name": "totalAssets", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 4098, }, { "stateMutability": "nonpayable", "type": "function", "name": "deposit", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "nonpayable", "type": "function", "name": "deposit", "inputs": [{"name": "_amount", "type": "uint256"}], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "nonpayable", "type": "function", "name": "deposit", "inputs": [ {"name": "_amount", "type": "uint256"}, {"name": "recipient", "type": "address"}, ], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "view", "type": "function", "name": "maxAvailableShares", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 383839, }, { "stateMutability": "nonpayable", "type": "function", "name": "withdraw", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "nonpayable", "type": "function", "name": "withdraw", "inputs": [{"name": "maxShares", "type": "uint256"}], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "nonpayable", "type": "function", "name": "withdraw", "inputs": [ {"name": "maxShares", "type": "uint256"}, {"name": "recipient", "type": "address"}, ], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "nonpayable", "type": "function", "name": "withdraw", "inputs": [ {"name": "maxShares", "type": "uint256"}, {"name": "recipient", "type": "address"}, {"name": "maxLoss", "type": "uint256"}, ], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "view", "type": "function", "name": "pricePerShare", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 18195, }, { "stateMutability": "nonpayable", "type": "function", "name": "addStrategy", "inputs": [ {"name": "strategy", "type": "address"}, {"name": "debtRatio", "type": "uint256"}, {"name": "minDebtPerHarvest", "type": "uint256"}, {"name": "maxDebtPerHarvest", "type": "uint256"}, {"name": "performanceFee", "type": "uint256"}, ], "outputs": [], "gas": 1485796, }, { "stateMutability": "nonpayable", "type": "function", "name": "updateStrategyDebtRatio", "inputs": [ {"name": "strategy", "type": "address"}, {"name": "debtRatio", "type": "uint256"}, ], "outputs": [], "gas": 115193, }, { "stateMutability": "nonpayable", "type": "function", "name": "updateStrategyMinDebtPerHarvest", "inputs": [ {"name": "strategy", "type": "address"}, {"name": "minDebtPerHarvest", "type": "uint256"}, ], "outputs": [], "gas": 42441, }, { "stateMutability": "nonpayable", "type": "function", "name": "updateStrategyMaxDebtPerHarvest", "inputs": [ {"name": "strategy", "type": "address"}, {"name": "maxDebtPerHarvest", "type": "uint256"}, ], "outputs": [], "gas": 42471, }, { "stateMutability": "nonpayable", "type": "function", "name": "updateStrategyPerformanceFee", "inputs": [ {"name": "strategy", "type": "address"}, {"name": "performanceFee", "type": "uint256"}, ], "outputs": [], "gas": 41251, }, { "stateMutability": "nonpayable", "type": "function", "name": "migrateStrategy", "inputs": [ {"name": "oldVersion", "type": "address"}, {"name": "newVersion", "type": "address"}, ], "outputs": [], "gas": 1141468, }, { "stateMutability": "nonpayable", "type": "function", "name": "revokeStrategy", "inputs": [], "outputs": [], }, { "stateMutability": "nonpayable", "type": "function", "name": "revokeStrategy", "inputs": [{"name": "strategy", "type": "address"}], "outputs": [], }, { "stateMutability": "nonpayable", "type": "function", "name": "addStrategyToQueue", "inputs": [{"name": "strategy", "type": "address"}], "outputs": [], "gas": 1199804, }, { "stateMutability": "nonpayable", "type": "function", "name": "removeStrategyFromQueue", "inputs": [{"name": "strategy", "type": "address"}], "outputs": [], "gas": 23088703, }, { "stateMutability": "view", "type": "function", "name": "debtOutstanding", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "view", "type": "function", "name": "debtOutstanding", "inputs": [{"name": "strategy", "type": "address"}], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "view", "type": "function", "name": "creditAvailable", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "view", "type": "function", "name": "creditAvailable", "inputs": [{"name": "strategy", "type": "address"}], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "view", "type": "function", "name": "availableDepositLimit", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 9551, }, { "stateMutability": "view", "type": "function", "name": "expectedReturn", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "view", "type": "function", "name": "expectedReturn", "inputs": [{"name": "strategy", "type": "address"}], "outputs": [{"name": "", "type": "uint256"}], }, { "stateMutability": "nonpayable", "type": "function", "name": "report", "inputs": [ {"name": "gain", "type": "uint256"}, {"name": "loss", "type": "uint256"}, {"name": "_debtPayment", "type": "uint256"}, ], "outputs": [{"name": "", "type": "uint256"}], "gas": 1015170, }, { "stateMutability": "nonpayable", "type": "function", "name": "sweep", "inputs": [{"name": "token", "type": "address"}], "outputs": [], }, { "stateMutability": "nonpayable", "type": "function", "name": "sweep", "inputs": [ {"name": "token", "type": "address"}, {"name": "amount", "type": "uint256"}, ], "outputs": [], }, { "stateMutability": "view", "type": "function", "name": "name", "inputs": [], "outputs": [{"name": "", "type": "string"}], "gas": 8750, }, { "stateMutability": "view", "type": "function", "name": "symbol", "inputs": [], "outputs": [{"name": "", "type": "string"}], "gas": 7803, }, { "stateMutability": "view", "type": "function", "name": "decimals", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2408, }, { "stateMutability": "view", "type": "function", "name": "precisionFactor", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2438, }, { "stateMutability": "view", "type": "function", "name": "balanceOf", "inputs": [{"name": "arg0", "type": "address"}], "outputs": [{"name": "", "type": "uint256"}], "gas": 2683, }, { "stateMutability": "view", "type": "function", "name": "allowance", "inputs": [ {"name": "arg0", "type": "address"}, {"name": "arg1", "type": "address"}, ], "outputs": [{"name": "", "type": "uint256"}], "gas": 2928, }, { "stateMutability": "view", "type": "function", "name": "totalSupply", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2528, }, { "stateMutability": "view", "type": "function", "name": "token", "inputs": [], "outputs": [{"name": "", "type": "address"}], "gas": 2558, }, { "stateMutability": "view", "type": "function", "name": "governance", "inputs": [], "outputs": [{"name": "", "type": "address"}], "gas": 2588, }, { "stateMutability": "view", "type": "function", "name": "management", "inputs": [], "outputs": [{"name": "", "type": "address"}], "gas": 2618, }, { "stateMutability": "view", "type": "function", "name": "guardian", "inputs": [], "outputs": [{"name": "", "type": "address"}], "gas": 2648, }, { "stateMutability": "view", "type": "function", "name": "guestList", "inputs": [], "outputs": [{"name": "", "type": "address"}], "gas": 2678, }, { "stateMutability": "view", "type": "function", "name": "strategies", "inputs": [{"name": "arg0", "type": "address"}], "outputs": [ {"name": "performanceFee", "type": "uint256"}, {"name": "activation", "type": "uint256"}, {"name": "debtRatio", "type": "uint256"}, {"name": "minDebtPerHarvest", "type": "uint256"}, {"name": "maxDebtPerHarvest", "type": "uint256"}, {"name": "lastReport", "type": "uint256"}, {"name": "totalDebt", "type": "uint256"}, {"name": "totalGain", "type": "uint256"}, {"name": "totalLoss", "type": "uint256"}, ], "gas": 11031, }, { "stateMutability": "view", "type": "function", "name": "withdrawalQueue", "inputs": [{"name": "arg0", "type": "uint256"}], "outputs": [{"name": "", "type": "address"}], "gas": 2847, }, { "stateMutability": "view", "type": "function", "name": "emergencyShutdown", "inputs": [], "outputs": [{"name": "", "type": "bool"}], "gas": 2768, }, { "stateMutability": "view", "type": "function", "name": "depositLimit", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2798, }, { "stateMutability": "view", "type": "function", "name": "debtRatio", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2828, }, { "stateMutability": "view", "type": "function", "name": "totalDebt", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2858, }, { "stateMutability": "view", "type": "function", "name": "lastReport", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2888, }, { "stateMutability": "view", "type": "function", "name": "activation", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2918, }, { "stateMutability": "view", "type": "function", "name": "lockedProfit", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2948, }, { "stateMutability": "view", "type": "function", "name": "lockedProfitDegration", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 2978, }, { "stateMutability": "view", "type": "function", "name": "rewards", "inputs": [], "outputs": [{"name": "", "type": "address"}], "gas": 3008, }, { "stateMutability": "view", "type": "function", "name": "managementFee", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 3038, }, { "stateMutability": "view", "type": "function", "name": "performanceFee", "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "gas": 3068, }, { "stateMutability": "view", "type": "function", "name": "nonces", "inputs": [{"name": "arg0", "type": "address"}], "outputs": [{"name": "", "type": "uint256"}], "gas": 3313, }, { "stateMutability": "view", "type": "function", "name": "DOMAIN_SEPARATOR", "inputs": [], "outputs": [{"name": "", "type": "bytes32"}], "gas": 3128, }, ]
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/eth/oracles/abis/yearn_abis.py
0.521959
0.48182
yearn_abis.py
pypi
import json import os import sys from typing import Any, Dict, Optional from eth_typing import ChecksumAddress from hexbytes import HexBytes from web3 import Web3 from web3.contract import Contract try: from functools import cache except ImportError: from functools import lru_cache cache = lru_cache(maxsize=None) def load_contract_interface(file_name): return _load_json_file(_abi_file_path(file_name)) def _abi_file_path(file): return os.path.abspath(os.path.join(os.path.dirname(__file__), file)) def _load_json_file(path): with open(path) as f: return json.load(f) current_module = sys.modules[__name__] contracts = { "safe_V1_3_0": "GnosisSafe_V1_3_0.json", "safe_V1_1_1": "GnosisSafe_V1_1_1.json", "safe_V1_0_0": "GnosisSafe_V1_0_0.json", "safe_V0_0_1": "GnosisSafe_V0_0_1.json", "compatibility_fallback_handler_V1_3_0": "CompatibilityFallbackHandler_V1_3_0.json", "erc20": "ERC20.json", "erc721": "ERC721.json", "erc1155": "ERC1155.json", "example_erc20": "ERC20TestToken.json", "delegate_constructor_proxy": "DelegateConstructorProxy.json", "multi_send": "MultiSend.json", "paying_proxy": "PayingProxy.json", "proxy_factory": "ProxyFactory_V1_3_0.json", "proxy_factory_V1_1_1": "ProxyFactory_V1_1_1.json", "proxy_factory_V1_0_0": "ProxyFactory_V1_0_0.json", "proxy": "Proxy_V1_1_1.json", "uniswap_exchange": "uniswap_exchange.json", "uniswap_factory": "uniswap_factory.json", "uniswap_v2_factory": "uniswap_v2_factory.json", "uniswap_v2_pair": "uniswap_v2_pair.json", "uniswap_v2_router": "uniswap_v2_router.json", # Router02 "kyber_network_proxy": "kyber_network_proxy.json", "cpk_factory": "CPKFactory.json", } def generate_contract_fn(contract: Dict[str, Any]): """ Dynamically generate functions to work with the contracts :param contract: :return: """ def fn(w3: Web3, address: Optional[ChecksumAddress] = None): return w3.eth.contract( address=address, abi=contract["abi"], bytecode=contract.get("bytecode") ) return fn # Anotate functions that will be generated later with `setattr` so typing does not complains def get_safe_contract(w3: Web3, address: Optional[str] = None) -> Contract: """ :param w3: :param address: :return: Latest available safe contract (v1.3.0) """ return get_safe_V1_3_0_contract(w3, address=address) def get_safe_V1_3_0_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_safe_V1_1_1_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_safe_V1_0_0_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_safe_V0_0_1_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_compatibility_fallback_handler_V1_3_0_contract( w3: Web3, address: Optional[str] = None ) -> Contract: pass def get_erc20_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_erc721_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_erc1155_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_example_erc20_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_delegate_constructor_proxy_contract( w3: Web3, address: Optional[str] = None ) -> Contract: pass def get_multi_send_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_paying_proxy_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_proxy_factory_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_proxy_factory_V1_1_1_contract( w3: Web3, address: Optional[str] = None ) -> Contract: pass def get_proxy_factory_V1_0_0_contract( w3: Web3, address: Optional[str] = None ) -> Contract: pass def get_proxy_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_uniswap_exchange_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_uniswap_factory_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_uniswap_v2_factory_contract( w3: Web3, address: Optional[str] = None ) -> Contract: pass def get_uniswap_v2_pair_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_uniswap_v2_router_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass def get_kyber_network_proxy_contract( w3: Web3, address: Optional[str] = None ) -> Contract: pass def get_cpk_factory_contract(w3: Web3, address: Optional[str] = None) -> Contract: pass @cache def get_proxy_1_3_0_deployed_bytecode() -> bytes: return HexBytes(load_contract_interface("Proxy_V1_3_0.json")["deployedBytecode"]) def get_proxy_1_1_1_mainnet_deployed_bytecode() -> bytes: """ Somehow it's different from the generated version compiling the contracts """ return HexBytes( "0x608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea265627a7a72315820d8a00dc4fe6bf675a9d7416fc2d00bb3433362aa8186b750f76c4027269667ff64736f6c634300050e0032" ) @cache def get_proxy_1_1_1_deployed_bytecode() -> bytes: return HexBytes(load_contract_interface("Proxy_V1_1_1.json")["deployedBytecode"]) @cache def get_proxy_1_0_0_deployed_bytecode() -> bytes: return HexBytes(load_contract_interface("Proxy_V1_0_0.json")["deployedBytecode"]) @cache def get_paying_proxy_deployed_bytecode() -> bytes: return HexBytes(load_contract_interface("PayingProxy.json")["deployedBytecode"]) for contract_name, json_contract_filename in contracts.items(): fn_name = "get_{}_contract".format(contract_name) contract_dict = load_contract_interface(json_contract_filename) if not contract_dict: raise ValueError(f"{contract_name} json cannot be empty") setattr(current_module, fn_name, generate_contract_fn(contract_dict))
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/eth/contracts/__init__.py
0.627267
0.156878
__init__.py
pypi
from enum import Enum from logging import getLogger from typing import List, Union from eth_account.signers.local import LocalAccount from hexbytes import HexBytes from web3 import Web3 from gnosis.eth import EthereumClient from gnosis.eth.contracts import get_multi_send_contract from gnosis.eth.ethereum_client import EthereumTxSent from gnosis.eth.typing import EthereumData logger = getLogger(__name__) class MultiSendOperation(Enum): CALL = 0 DELEGATE_CALL = 1 class MultiSendTx: """ Wrapper for a single MultiSendTx """ def __init__( self, operation: MultiSendOperation, to: str, value: int, data: EthereumData, old_encoding: bool = False, ): """ :param operation: MultisendOperation, CALL or DELEGATE_CALL :param to: Address :param value: Value in Wei :param data: data as hex string or bytes :param old_encoding: True if using old multisend ABI Encoded data, False otherwise """ self.operation = operation self.to = to self.value = value self.data = HexBytes(data) if data else b"" self.old_encoding = old_encoding def __eq__(self, other): if not isinstance(other, MultiSendTx): return NotImplemented return ( self.operation == other.operation and self.to == other.to and self.value == other.value and self.data == other.data ) def __len__(self): """ :return: Size on bytes of the tx """ return 21 + 32 * 2 + self.data_length def __repr__(self): data = self.data[:4].hex() + ("..." if len(self.data) > 4 else "") return ( f"MultisendTx operation={self.operation.name} to={self.to} value={self.value} " f"data={data}" ) @property def data_length(self) -> int: return len(self.data) @property def encoded_data(self): operation = HexBytes("{:0>2x}".format(self.operation.value)) # Operation 1 byte to = HexBytes("{:0>40x}".format(int(self.to, 16))) # Address 20 bytes value = HexBytes("{:0>64x}".format(self.value)) # Value 32 bytes data_length = HexBytes( "{:0>64x}".format(self.data_length) ) # Data length 32 bytes return operation + to + value + data_length + self.data @classmethod def from_bytes(cls, encoded_multisend_tx: Union[str, bytes]) -> "MultiSendTx": """ Decoded one MultiSend transaction. ABI must be used to get the `transactions` parameter and use that data for this function :param encoded_multisend_tx: :return: """ encoded_multisend_tx = HexBytes(encoded_multisend_tx) try: return cls._decode_multisend_data(encoded_multisend_tx) except ValueError: # Try using the old decoding method return cls._decode_multisend_old_transaction(encoded_multisend_tx) @classmethod def _decode_multisend_data(cls, encoded_multisend_tx: Union[str, bytes]): """ Decodes one Multisend transaction. If there's more data after `data` it's ignored. Fallbacks to the old multisend structure if this structure cannot be decoded. https://etherscan.io/address/0x8D29bE29923b68abfDD21e541b9374737B49cdAD#code Structure: - operation -> MultiSendOperation 1 byte - to -> ethereum address 20 bytes - value -> tx value 32 bytes - data_length -> 32 bytes - data -> `data_length` bytes :param encoded_multisend_tx: 1 multisend transaction encoded :return: Tx as a MultisendTx """ encoded_multisend_tx = HexBytes(encoded_multisend_tx) operation = MultiSendOperation(encoded_multisend_tx[0]) to = Web3.toChecksumAddress(encoded_multisend_tx[1 : 1 + 20]) value = int.from_bytes(encoded_multisend_tx[21 : 21 + 32], byteorder="big") data_length = int.from_bytes( encoded_multisend_tx[21 + 32 : 21 + 32 * 2], byteorder="big" ) data = encoded_multisend_tx[21 + 32 * 2 : 21 + 32 * 2 + data_length] len_data = len(data) if len_data != data_length: raise ValueError( f"Data length {data_length} is different from len(data) {len_data}" ) return cls(operation, to, value, data, old_encoding=False) @classmethod def _decode_multisend_old_transaction( cls, encoded_multisend_tx: Union[str, bytes] ) -> "MultiSendTx": """ Decodes one old multisend transaction. If there's more data after `data` it's ignored. The difference with the new MultiSend is that every value but `data` is padded to 32 bytes, wasting a lot of bytes. https://etherscan.io/address/0xE74d6AF1670FB6560dd61EE29eB57C7Bc027Ce4E#code Structure: - operation -> MultiSendOperation 32 byte - to -> ethereum address 32 bytes - value -> tx value 32 bytes - data_length -> 32 bytes - data -> `data_length` bytes :param encoded_multisend_tx: 1 multisend transaction encoded :return: Tx as a MultisendTx """ encoded_multisend_tx = HexBytes(encoded_multisend_tx) operation = MultiSendOperation( int.from_bytes(encoded_multisend_tx[:32], byteorder="big") ) to = Web3.toChecksumAddress(encoded_multisend_tx[32:64][-20:]) value = int.from_bytes(encoded_multisend_tx[64:96], byteorder="big") data_length = int.from_bytes(encoded_multisend_tx[128:160], byteorder="big") data = encoded_multisend_tx[160 : 160 + data_length] len_data = len(data) if len_data != data_length: raise ValueError( f"Data length {data_length} is different from len(data) {len_data}" ) return cls(operation, to, value, data, old_encoding=True) class MultiSend: dummy_w3 = Web3() def __init__(self, address: str, ethereum_client: EthereumClient): assert Web3.isChecksumAddress(address), ( "%s proxy factory address not valid" % address ) self.address = address self.ethereum_client = ethereum_client self.w3 = ethereum_client.w3 @classmethod def from_bytes(cls, encoded_multisend_txs: Union[str, bytes]) -> List[MultiSendTx]: """ Decodes one or more multisend transactions from `bytes transactions` (Abi decoded) :param encoded_multisend_txs: :return: List of MultiSendTxs """ if not encoded_multisend_txs: return [] encoded_multisend_txs = HexBytes(encoded_multisend_txs) multisend_tx = MultiSendTx.from_bytes(encoded_multisend_txs) multisend_tx_size = len(multisend_tx) assert ( multisend_tx_size > 0 ), "Multisend tx cannot be empty" # This should never happen, just in case if multisend_tx.old_encoding: next_data_position = ( (multisend_tx.data_length + 0x1F) // 0x20 * 0x20 ) + 0xA0 else: next_data_position = multisend_tx_size remaining_data = encoded_multisend_txs[next_data_position:] return [multisend_tx] + cls.from_bytes(remaining_data) @classmethod def from_transaction_data( cls, multisend_data: Union[str, bytes] ) -> List[MultiSendTx]: """ Decodes multisend transactions from transaction data (ABI encoded with selector) :return: """ try: _, data = get_multi_send_contract(cls.dummy_w3).decode_function_input( multisend_data ) return cls.from_bytes(data["transactions"]) except ValueError: return [] @staticmethod def deploy_contract( ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy proxy factory contract :param ethereum_client: :param deployer_account: Ethereum Account :return: deployed contract address """ contract = get_multi_send_contract(ethereum_client.w3) tx = contract.constructor().buildTransaction({"from": deployer_account.address}) tx_hash = ethereum_client.send_unsigned_transaction( tx, private_key=deployer_account.key ) tx_receipt = ethereum_client.get_transaction_receipt(tx_hash, timeout=120) assert tx_receipt assert tx_receipt["status"] contract_address = tx_receipt["contractAddress"] logger.info( "Deployed and initialized Proxy Factory Contract=%s by %s", contract_address, deployer_account.address, ) return EthereumTxSent(tx_hash, tx, contract_address) def get_contract(self): return get_multi_send_contract(self.ethereum_client.w3, self.address) def build_tx_data(self, multi_send_txs: List[MultiSendTx]) -> bytes: """ Txs don't need to be valid to get through :param multi_send_txs: :param sender: :return: """ multisend_contract = self.get_contract() encoded_multisend_data = b"".join([x.encoded_data for x in multi_send_txs]) return multisend_contract.functions.multiSend( encoded_multisend_data ).buildTransaction({"gas": 1, "gasPrice": 1})["data"]
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/safe/multi_send.py
0.932116
0.389082
multi_send.py
pypi
from abc import ABC, abstractmethod from enum import Enum from logging import getLogger from typing import List, Union from eth_abi import decode_single, encode_single from eth_abi.exceptions import DecodingError from eth_account.messages import defunct_hash_message from eth_typing import ChecksumAddress from eth_utils import to_checksum_address from hexbytes import HexBytes from web3.exceptions import BadFunctionCallOutput from gnosis.eth import EthereumClient from gnosis.eth.contracts import get_safe_contract, get_safe_V1_1_1_contract from gnosis.safe.signatures import ( get_signing_address, signature_split, signature_to_bytes, ) logger = getLogger(__name__) EthereumBytes = Union[bytes, str] class SafeSignatureException(Exception): pass class CannotCheckEIP1271ContractSignature(SafeSignatureException): pass class SafeSignatureType(Enum): CONTRACT_SIGNATURE = 0 APPROVED_HASH = 1 EOA = 2 ETH_SIGN = 3 @staticmethod def from_v(v: int): if v == 0: return SafeSignatureType.CONTRACT_SIGNATURE elif v == 1: return SafeSignatureType.APPROVED_HASH elif v > 30: return SafeSignatureType.ETH_SIGN else: return SafeSignatureType.EOA def uint_to_address(value: int) -> ChecksumAddress: """ Convert a Solidity `uint` value to a checksummed `address`, removing invalid padding bytes if present :return: Checksummed address """ encoded = encode_single("uint", value) # Remove padding bytes, as Solidity will ignore it but `eth_abi` will not encoded_without_padding_bytes = b"\x00" * 12 + encoded[-20:] return to_checksum_address(decode_single("address", encoded_without_padding_bytes)) class SafeSignature(ABC): def __init__(self, signature: EthereumBytes, safe_tx_hash: EthereumBytes): self.signature = HexBytes(signature) self.safe_tx_hash = HexBytes(safe_tx_hash) self.v, self.r, self.s = signature_split(self.signature) def __str__(self): return f"SafeSignature type={self.signature_type.name} owner={self.owner}" @classmethod def parse_signature( cls, signatures: EthereumBytes, safe_tx_hash: EthereumBytes, ignore_trailing: bool = True, ) -> List["SafeSignature"]: """ :param signatures: One or more signatures appended. EIP1271 data at the end is supported. :param safe_tx_hash: :param ignore_trailing: Ignore trailing data on the signature. Some libraries pad it and add some zeroes at the end :return: List of SafeSignatures decoded """ if not signatures: return [] elif isinstance(signatures, str): signatures = HexBytes(signatures) signature_size = 65 # For contract signatures there'll be some data at the end data_position = len( signatures ) # For contract signatures, to stop parsing at data position safe_signatures = [] for i in range(0, len(signatures), signature_size): if ( i >= data_position ): # If contract signature data position is reached, stop break signature = signatures[i : i + signature_size] if ignore_trailing and len(signature) < 65: # Trailing stuff break v, r, s = signature_split(signature) signature_type = SafeSignatureType.from_v(v) safe_signature: "SafeSignature" if signature_type == SafeSignatureType.CONTRACT_SIGNATURE: if s < data_position: data_position = s contract_signature_len = int.from_bytes( signatures[s : s + 32], "big" ) # Len size is 32 bytes contract_signature = signatures[ s + 32 : s + 32 + contract_signature_len ] # Skip array size (32 bytes) safe_signature = SafeSignatureContract( signature, safe_tx_hash, contract_signature ) elif signature_type == SafeSignatureType.APPROVED_HASH: safe_signature = SafeSignatureApprovedHash(signature, safe_tx_hash) elif signature_type == SafeSignatureType.EOA: safe_signature = SafeSignatureEOA(signature, safe_tx_hash) elif signature_type == SafeSignatureType.ETH_SIGN: safe_signature = SafeSignatureEthSign(signature, safe_tx_hash) safe_signatures.append(safe_signature) return safe_signatures def export_signature(self) -> HexBytes: """ Exports signature in a format that's valid individually. That's important for contract signatures, as it will fix the offset :return: """ return self.signature @property @abstractmethod def owner(self): """ :return: Decode owner from signature, without any further validation (signature can be not valid) """ raise NotImplementedError @abstractmethod def is_valid(self, ethereum_client: EthereumClient, safe_address: str) -> bool: """ :param ethereum_client: Required for Contract Signature and Approved Hash check :param safe_address: Required for Approved Hash check :return: `True` if signature is valid, `False` otherwise """ raise NotImplementedError @property @abstractmethod def signature_type(self) -> SafeSignatureType: raise NotImplementedError class SafeSignatureContract(SafeSignature): EIP1271_MAGIC_VALUE = HexBytes(0x20C13B0B) EIP1271_MAGIC_VALUE_UPDATED = HexBytes(0x1626BA7E) def __init__( self, signature: EthereumBytes, safe_tx_hash: EthereumBytes, contract_signature: EthereumBytes, ): super().__init__(signature, safe_tx_hash) self.contract_signature = HexBytes(contract_signature) @property def owner(self) -> ChecksumAddress: """ :return: Address of contract signing. No further checks to get the owner are needed, but it could be a non existing contract """ return uint_to_address(self.r) @property def signature_type(self) -> SafeSignatureType: return SafeSignatureType.CONTRACT_SIGNATURE def export_signature(self) -> HexBytes: """ Fix offset (s) and append `contract_signature` at the end of the signature :return: """ return HexBytes( signature_to_bytes(self.v, self.r, 65) + encode_single("bytes", self.contract_signature) ) def is_valid(self, ethereum_client: EthereumClient, *args) -> bool: safe_contract = get_safe_V1_1_1_contract(ethereum_client.w3, self.owner) # Newest versions of the Safe contract have `isValidSignature` on the compatibility fallback handler for block_identifier in ("pending", "latest"): try: return safe_contract.functions.isValidSignature( self.safe_tx_hash, self.contract_signature ).call(block_identifier=block_identifier) in ( self.EIP1271_MAGIC_VALUE, self.EIP1271_MAGIC_VALUE_UPDATED, ) except (ValueError, BadFunctionCallOutput, DecodingError): # Error using `pending` block identifier or contract does not exist logger.warning( "Cannot check EIP1271 signature from contract %s", self.owner ) return False class SafeSignatureApprovedHash(SafeSignature): @property def owner(self): return uint_to_address(self.r) @property def signature_type(self): return SafeSignatureType.APPROVED_HASH @classmethod def build_for_owner( cls, owner: str, safe_tx_hash: str ) -> "SafeSignatureApprovedHash": r = owner.lower().replace("0x", "").rjust(64, "0") s = "0" * 64 v = "01" return cls(HexBytes(r + s + v), safe_tx_hash) def is_valid(self, ethereum_client: EthereumClient, safe_address: str) -> bool: safe_contract = get_safe_contract(ethereum_client.w3, safe_address) exception: Exception for block_identifier in ("pending", "latest"): try: return ( safe_contract.functions.approvedHashes( self.owner, self.safe_tx_hash ).call(block_identifier=block_identifier) == 1 ) except BadFunctionCallOutput as e: # Error using `pending` block identifier exception = e raise exception # This should never happen class SafeSignatureEthSign(SafeSignature): @property def owner(self): # defunct_hash_message prepends `\x19Ethereum Signed Message:\n32` message_hash = defunct_hash_message(primitive=self.safe_tx_hash) return get_signing_address(message_hash, self.v - 4, self.r, self.s) @property def signature_type(self): return SafeSignatureType.ETH_SIGN def is_valid(self, *args) -> bool: return True class SafeSignatureEOA(SafeSignature): @property def owner(self): return get_signing_address(self.safe_tx_hash, self.v, self.r, self.s) @property def signature_type(self): return SafeSignatureType.EOA def is_valid(self, *args) -> bool: return True
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/safe/safe_signature.py
0.904543
0.232093
safe_signature.py
pypi
from typing import Any, Dict, List, NoReturn, Optional, Tuple, Type from eip712_structs import Address, Bytes, EIP712Struct, Uint, make_domain from eip712_structs.struct import StructTuple from eth_account import Account from hexbytes import HexBytes from packaging.version import Version from web3 import Web3 from web3.exceptions import BadFunctionCallOutput, ContractLogicError from web3.types import BlockIdentifier, TxParams, Wei from gnosis.eth import EthereumClient from gnosis.eth.constants import NULL_ADDRESS from gnosis.eth.contracts import get_safe_contract from ..eth.ethereum_client import TxSpeed from .exceptions import ( CouldNotFinishInitialization, CouldNotPayGasWithEther, CouldNotPayGasWithToken, HashHasNotBeenApproved, InvalidContractSignatureLocation, InvalidInternalTx, InvalidMultisigTx, InvalidOwnerProvided, InvalidSignaturesProvided, MethodCanOnlyBeCalledFromThisContract, ModuleManagerException, NotEnoughSafeTransactionGas, OnlyOwnersCanApproveAHash, OwnerManagerException, SafeTransactionFailedWhenGasPriceAndSafeTxGasEmpty, SignatureNotProvidedByOwner, SignaturesDataTooShort, ThresholdNeedsToBeDefined, ) from .safe_signature import SafeSignature from .signatures import signature_to_bytes try: from functools import cached_property except ImportError: from cached_property import cached_property class EIP712SafeTx(EIP712Struct): to = Address() value = Uint(256) data = Bytes() operation = Uint(8) safeTxGas = Uint(256) baseGas = Uint(256) # `dataGas` was renamed to `baseGas` in 1.0.0 gasPrice = Uint(256) gasToken = Address() refundReceiver = Address() nonce = Uint(256) class EIP712LegacySafeTx(EIP712Struct): to = Address() value = Uint(256) data = Bytes() operation = Uint(8) safeTxGas = Uint(256) dataGas = Uint(256) gasPrice = Uint(256) gasToken = Address() refundReceiver = Address() nonce = Uint(256) EIP712SafeTx.type_name = "SafeTx" EIP712LegacySafeTx.type_name = "SafeTx" class SafeTx: tx: TxParams # If executed, `tx` is set tx_hash: bytes # If executed, `tx_hash` is set def __init__( self, ethereum_client: EthereumClient, safe_address: str, to: Optional[str], value: int, data: bytes, operation: int, safe_tx_gas: int, base_gas: int, gas_price: int, gas_token: Optional[str], refund_receiver: Optional[str], signatures: Optional[bytes] = None, safe_nonce: Optional[int] = None, safe_version: str = None, chain_id: Optional[int] = None, ): """ :param ethereum_client: :param safe_address: :param to: :param value: :param data: :param operation: :param safe_tx_gas: :param base_gas: :param gas_price: :param gas_token: :param refund_receiver: :param signatures: :param safe_nonce: Current nonce of the Safe. If not provided, it will be retrieved from network :param safe_version: Safe version 1.0.0 renamed `baseGas` to `dataGas`. Safe version 1.3.0 added `chainId` to the `domainSeparator`. If not provided, it will be retrieved from network :param chain_id: Ethereum network chain_id is used in hash calculation for Safes >= 1.3.0. If not provided, it will be retrieved from the provided ethereum_client """ self.ethereum_client = ethereum_client self.safe_address = safe_address self.to = to or NULL_ADDRESS self.value = value self.data = HexBytes(data) if data else b"" self.operation = operation self.safe_tx_gas = safe_tx_gas self.base_gas = base_gas self.gas_price = gas_price self.gas_token = gas_token or NULL_ADDRESS self.refund_receiver = refund_receiver or NULL_ADDRESS self.signatures = signatures or b"" self._safe_nonce = safe_nonce self._safe_version = safe_version self._chain_id = chain_id def __str__(self): return ( f"SafeTx - safe={self.safe_address} - to={self.to} - value={self.value} - data={self.data.hex()} - " f"operation={self.operation} - safe-tx-gas={self.safe_tx_gas} - base-gas={self.base_gas} - " f"gas-price={self.gas_price} - gas-token={self.gas_token} - refund-receiver={self.refund_receiver} - " f"signers = {self.signers}" ) @property def w3(self): return self.ethereum_client.w3 @cached_property def contract(self): return get_safe_contract(self.w3, address=self.safe_address) @cached_property def chain_id(self) -> int: if self._chain_id is not None: return self._chain_id else: return self.ethereum_client.get_chain_id() @cached_property def safe_nonce(self) -> str: if self._safe_nonce is not None: return self._safe_nonce else: return self.contract.functions.nonce().call() @cached_property def safe_version(self) -> str: if self._safe_version is not None: return self._safe_version else: return self.contract.functions.VERSION().call() @property def _eip712_payload(self) -> StructTuple: data = self.data.hex() if self.data else "" safe_version = Version(self.safe_version) cls = EIP712SafeTx if safe_version >= Version("1.0.0") else EIP712LegacySafeTx message = cls( to=self.to, value=self.value, data=data, operation=self.operation, safeTxGas=self.safe_tx_gas, baseGas=self.base_gas, dataGas=self.base_gas, gasPrice=self.gas_price, gasToken=self.gas_token, refundReceiver=self.refund_receiver, nonce=self.safe_nonce, ) domain = make_domain( verifyingContract=self.safe_address, chainId=self.chain_id if safe_version >= Version("1.3.0") else None, ) return StructTuple(message, domain) @property def eip712_structured_data(self) -> Dict: message, domain = self._eip712_payload return message.to_message(domain) @property def safe_tx_hash(self) -> HexBytes: message, domain = self._eip712_payload signable_bytes = message.signable_bytes(domain) return HexBytes(Web3.keccak(signable_bytes)) @property def signers(self) -> List[str]: if not self.signatures: return [] else: return [ safe_signature.owner for safe_signature in SafeSignature.parse_signature( self.signatures, self.safe_tx_hash ) ] @property def sorted_signers(self): return sorted(self.signers, key=lambda x: int(x, 16)) @property def w3_tx(self): """ :return: Web3 contract tx prepared for `call`, `transact` or `buildTransaction` """ return self.contract.functions.execTransaction( self.to, self.value, self.data, self.operation, self.safe_tx_gas, self.base_gas, self.gas_price, self.gas_token, self.refund_receiver, self.signatures, ) def _raise_safe_vm_exception(self, message: str) -> NoReturn: error_with_exception: Dict[str, Type[InvalidMultisigTx]] = { # https://github.com/safe-global/safe-contracts/blob/v1.3.0/docs/error_codes.md "GS000": CouldNotFinishInitialization, "GS001": ThresholdNeedsToBeDefined, "Could not pay gas costs with ether": CouldNotPayGasWithEther, "GS011": CouldNotPayGasWithEther, "Could not pay gas costs with token": CouldNotPayGasWithToken, "GS012": CouldNotPayGasWithToken, "GS013": SafeTransactionFailedWhenGasPriceAndSafeTxGasEmpty, "Hash has not been approved": HashHasNotBeenApproved, "Hash not approved": HashHasNotBeenApproved, "GS025": HashHasNotBeenApproved, "Invalid contract signature location: data not complete": InvalidContractSignatureLocation, "GS023": InvalidContractSignatureLocation, "Invalid contract signature location: inside static part": InvalidContractSignatureLocation, "GS021": InvalidContractSignatureLocation, "Invalid contract signature location: length not present": InvalidContractSignatureLocation, "GS022": InvalidContractSignatureLocation, "Invalid contract signature provided": InvalidContractSignatureLocation, "GS024": InvalidContractSignatureLocation, "Invalid owner provided": InvalidOwnerProvided, "Invalid owner address provided": InvalidOwnerProvided, "GS026": InvalidOwnerProvided, "Invalid signatures provided": InvalidSignaturesProvided, "Not enough gas to execute safe transaction": NotEnoughSafeTransactionGas, "GS010": NotEnoughSafeTransactionGas, "Only owners can approve a hash": OnlyOwnersCanApproveAHash, "GS030": OnlyOwnersCanApproveAHash, "GS031": MethodCanOnlyBeCalledFromThisContract, "Signature not provided by owner": SignatureNotProvidedByOwner, "Signatures data too short": SignaturesDataTooShort, "GS020": SignaturesDataTooShort, # ModuleManager "GS100": ModuleManagerException, "Invalid module address provided": ModuleManagerException, "GS101": ModuleManagerException, "GS102": ModuleManagerException, "Invalid prevModule, module pair provided": ModuleManagerException, "GS103": ModuleManagerException, "Method can only be called from an enabled module": ModuleManagerException, "GS104": ModuleManagerException, "Module has already been added": ModuleManagerException, # OwnerManager "Address is already an owner": OwnerManagerException, "GS200": OwnerManagerException, # Owners have already been setup "GS201": OwnerManagerException, # Threshold cannot exceed owner count "GS202": OwnerManagerException, # Invalid owner address provided "GS203": OwnerManagerException, # Invalid ower address provided "GS204": OwnerManagerException, # Address is already an owner "GS205": OwnerManagerException, # Invalid prevOwner, owner pair provided "Invalid prevOwner, owner pair provided": OwnerManagerException, "New owner count needs to be larger than new threshold": OwnerManagerException, "Threshold cannot exceed owner count": OwnerManagerException, "Threshold needs to be greater than 0": OwnerManagerException, } for reason, custom_exception in error_with_exception.items(): if reason in message: raise custom_exception(message) raise InvalidMultisigTx(message) def call( self, tx_sender_address: Optional[str] = None, tx_gas: Optional[int] = None, block_identifier: Optional[BlockIdentifier] = "latest", ) -> int: """ :param tx_sender_address: :param tx_gas: Force a gas limit :param block_identifier: :return: `1` if everything ok """ parameters: Dict[str, Any] = { "from": tx_sender_address if tx_sender_address else self.safe_address } if tx_gas: parameters["gas"] = tx_gas try: success = self.w3_tx.call(parameters, block_identifier=block_identifier) if not success: raise InvalidInternalTx( "Success bit is %d, should be equal to 1" % success ) return success except (ContractLogicError, BadFunctionCallOutput, ValueError) as exc: # e.g. web3.exceptions.ContractLogicError: execution reverted: Invalid owner provided return self._raise_safe_vm_exception(str(exc)) except ValueError as exc: # Parity """ Parity throws a ValueError, e.g. {'code': -32015, 'message': 'VM execution error.', 'data': 'Reverted 0x08c379a0000000000000000000000000000000000000000000000000000000000000020000000000000000 000000000000000000000000000000000000000000000001b496e76616c6964207369676e6174757265732070726f7669 6465640000000000' } """ error_dict = exc.args[0] data = error_dict.get("data") if data and isinstance(data, str) and "Reverted " in data: # Parity result = HexBytes(data.replace("Reverted ", "")) return self._raise_safe_vm_exception(str(result)) else: raise exc def recommended_gas(self) -> Wei: """ :return: Recommended gas to use on the ethereum_tx """ return Wei(self.base_gas + self.safe_tx_gas + 75000) def execute( self, tx_sender_private_key: str, tx_gas: Optional[int] = None, tx_gas_price: Optional[int] = None, tx_nonce: Optional[int] = None, block_identifier: Optional[BlockIdentifier] = "latest", eip1559_speed: Optional[TxSpeed] = None, ) -> Tuple[HexBytes, TxParams]: """ Send multisig tx to the Safe :param tx_sender_private_key: Sender private key :param tx_gas: Gas for the external tx. If not, `(safe_tx_gas + base_gas) * 2` will be used :param tx_gas_price: Gas price of the external tx. If not, `gas_price` will be used :param tx_nonce: Force nonce for `tx_sender` :param block_identifier: `latest` or `pending` :param eip1559_speed: If provided, use EIP1559 transaction :return: Tuple(tx_hash, tx) :raises: InvalidMultisigTx: If user tx cannot go through the Safe """ sender_account = Account.from_key(tx_sender_private_key) if eip1559_speed and self.ethereum_client.is_eip1559_supported(): tx_parameters = self.ethereum_client.set_eip1559_fees( { "from": sender_account.address, }, tx_speed=eip1559_speed, ) else: tx_parameters = { "from": sender_account.address, "gasPrice": tx_gas_price or self.w3.eth.gas_price, } if tx_gas: tx_parameters["gas"] = tx_gas if tx_nonce is not None: tx_parameters["nonce"] = tx_nonce self.tx = self.w3_tx.buildTransaction(tx_parameters) self.tx["gas"] = Wei( tx_gas or (max(self.tx["gas"] + 75000, self.recommended_gas())) ) self.tx_hash = self.ethereum_client.send_unsigned_transaction( self.tx, private_key=sender_account.key, retry=False if tx_nonce is not None else True, block_identifier=block_identifier, ) # Set signatures empty after executing the tx. `Nonce` is increased even if it fails, # so signatures are not valid anymore self.signatures = b"" return self.tx_hash, self.tx def sign(self, private_key: str) -> bytes: """ {bytes32 r}{bytes32 s}{uint8 v} :param private_key: :return: Signature """ account = Account.from_key(private_key) signature_dict = account.signHash(self.safe_tx_hash) signature = signature_to_bytes( signature_dict["v"], signature_dict["r"], signature_dict["s"] ) # Insert signature sorted if account.address not in self.signers: new_owners = self.signers + [account.address] new_owner_pos = sorted(new_owners, key=lambda x: int(x, 16)).index( account.address ) self.signatures = ( self.signatures[: 65 * new_owner_pos] + signature + self.signatures[65 * new_owner_pos :] ) return signature def unsign(self, address: str) -> bool: for pos, signer in enumerate(self.signers): if signer == address: self.signatures = self.signatures.replace( self.signatures[pos * 65 : pos * 65 + 65], b"" ) return True return False
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/safe/safe_tx.py
0.909034
0.152064
safe_tx.py
pypi
import dataclasses import math from enum import Enum from logging import getLogger from typing import Callable, List, NamedTuple, Optional, Union from eth_account import Account from eth_account.signers.local import LocalAccount from eth_typing import ChecksumAddress from hexbytes import HexBytes from web3 import Web3 from web3.contract import Contract from web3.exceptions import BadFunctionCallOutput from web3.types import BlockIdentifier, Wei from gnosis.eth.constants import GAS_CALL_DATA_BYTE, NULL_ADDRESS, SENTINEL_ADDRESS from gnosis.eth.contracts import ( get_compatibility_fallback_handler_V1_3_0_contract, get_delegate_constructor_proxy_contract, get_safe_contract, get_safe_V0_0_1_contract, get_safe_V1_0_0_contract, get_safe_V1_1_1_contract, get_safe_V1_3_0_contract, ) from gnosis.eth.ethereum_client import EthereumClient, EthereumTxSent from gnosis.eth.utils import get_eth_address_with_key from gnosis.safe.proxy_factory import ProxyFactory from ..eth.typing import EthereumData from .exceptions import ( CannotEstimateGas, CannotRetrieveSafeInfoException, InvalidPaymentToken, ) from .safe_create2_tx import SafeCreate2Tx, SafeCreate2TxBuilder from .safe_creation_tx import InvalidERC20Token, SafeCreationTx from .safe_tx import SafeTx try: from functools import cache except ImportError: from functools import lru_cache cache = lru_cache(maxsize=None) logger = getLogger(__name__) class SafeCreationEstimate(NamedTuple): gas: int gas_price: int payment: int payment_token: Optional[str] class SafeOperation(Enum): CALL = 0 DELEGATE_CALL = 1 CREATE = 2 @dataclasses.dataclass class SafeInfo: address: ChecksumAddress fallback_handler: ChecksumAddress guard: ChecksumAddress master_copy: ChecksumAddress modules: List[ChecksumAddress] nonce: int owners: List[ChecksumAddress] threshold: int version: str class Safe: """ Class to manage a Gnosis Safe """ FALLBACK_HANDLER_STORAGE_SLOT = ( 0x6C9A6C4A39284E37ED1CF53D337577D14212A4870FB976A4366C693B939918D5 ) GUARD_STORAGE_SLOT = ( 0x4A204F620C8C5CCDCA3FD54D003BADD85BA500436A431F0CBDA4F558C93C34C8 ) def __init__(self, address: ChecksumAddress, ethereum_client: EthereumClient): """ :param address: Safe address :param ethereum_client: Initialized ethereum client """ assert Web3.isChecksumAddress(address), "%s is not a valid address" % address self.ethereum_client = ethereum_client self.w3 = self.ethereum_client.w3 self.address = address def __str__(self): return f"Safe={self.address}" @staticmethod def create( ethereum_client: EthereumClient, deployer_account: LocalAccount, master_copy_address: str, owners: List[str], threshold: int, fallback_handler: str = NULL_ADDRESS, proxy_factory_address: Optional[str] = None, payment_token: str = NULL_ADDRESS, payment: int = 0, payment_receiver: str = NULL_ADDRESS, ) -> EthereumTxSent: """ Deploy new Safe proxy pointing to the specified `master_copy` address and configured with the provided `owners` and `threshold`. By default, payment for the deployer of the tx will be `0`. If `proxy_factory_address` is set deployment will be done using the proxy factory instead of calling the `constructor` of a new `DelegatedProxy` Using `proxy_factory_address` is recommended, as it takes less gas. (Testing with `Ganache` and 1 owner 261534 without proxy vs 229022 with Proxy) """ assert owners, "At least one owner must be set" assert threshold >= len(owners), "Threshold=%d must be >= %d" % ( threshold, len(owners), ) initializer = ( get_safe_contract(ethereum_client.w3, NULL_ADDRESS) .functions.setup( owners, threshold, NULL_ADDRESS, # Contract address for optional delegate call b"", # Data payload for optional delegate call fallback_handler, # Handler for fallback calls to this contract, payment_token, payment, payment_receiver, ) .buildTransaction({"gas": Wei(1), "gasPrice": Wei(1)})["data"] ) if proxy_factory_address: proxy_factory = ProxyFactory(proxy_factory_address, ethereum_client) return proxy_factory.deploy_proxy_contract( deployer_account, master_copy_address, initializer=HexBytes(initializer) ) proxy_contract = get_delegate_constructor_proxy_contract(ethereum_client.w3) tx = proxy_contract.constructor( master_copy_address, initializer ).buildTransaction({"from": deployer_account.address}) tx["gas"] = tx["gas"] * 100000 tx_hash = ethereum_client.send_unsigned_transaction( tx, private_key=deployer_account.key ) tx_receipt = ethereum_client.get_transaction_receipt(tx_hash, timeout=60) assert tx_receipt assert tx_receipt["status"] contract_address = tx_receipt["contractAddress"] return EthereumTxSent(tx_hash, tx, contract_address) @staticmethod def _deploy_master_contract( ethereum_client: EthereumClient, deployer_account: LocalAccount, contract_fn: Callable[[Web3, Optional[str]], Contract], ) -> EthereumTxSent: """ Deploy master contract. Takes deployer_account (if unlocked in the node) or the deployer private key Safe with version > v1.1.1 doesn't need to be initialized as it already has a constructor :param ethereum_client: :param deployer_account: Ethereum account :param contract_fn: get contract function :return: deployed contract address """ safe_contract = contract_fn(ethereum_client.w3) constructor_tx = safe_contract.constructor().buildTransaction() tx_hash = ethereum_client.send_unsigned_transaction( constructor_tx, private_key=deployer_account.key ) tx_receipt = ethereum_client.get_transaction_receipt(tx_hash, timeout=60) assert tx_receipt assert tx_receipt["status"] ethereum_tx_sent = EthereumTxSent( tx_hash, constructor_tx, tx_receipt["contractAddress"] ) logger.info( "Deployed and initialized Safe Master Contract version=%s on address %s by %s", contract_fn(ethereum_client.w3, ethereum_tx_sent.contract_address) .functions.VERSION() .call(), ethereum_tx_sent.contract_address, deployer_account.address, ) return ethereum_tx_sent @classmethod def deploy_compatibility_fallback_handler( cls, ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy Compatibility Fallback handler v1.3.0 :param ethereum_client: :param deployer_account: Ethereum account :return: deployed contract address """ contract = get_compatibility_fallback_handler_V1_3_0_contract( ethereum_client.w3 ) constructor_tx = contract.constructor().buildTransaction() tx_hash = ethereum_client.send_unsigned_transaction( constructor_tx, private_key=deployer_account.key ) tx_receipt = ethereum_client.get_transaction_receipt(tx_hash, timeout=60) assert tx_receipt assert tx_receipt["status"] ethereum_tx_sent = EthereumTxSent( tx_hash, constructor_tx, tx_receipt["contractAddress"] ) logger.info( "Deployed and initialized Compatibility Fallback Handler version=%s on address %s by %s", "1.3.0", ethereum_tx_sent.contract_address, deployer_account.address, ) return ethereum_tx_sent @classmethod def deploy_master_contract_v1_3_0( cls, ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy master contract v1.3.0. Takes deployer_account (if unlocked in the node) or the deployer private key Safe with version > v1.1.1 doesn't need to be initialized as it already has a constructor :param ethereum_client: :param deployer_account: Ethereum account :return: deployed contract address """ return cls._deploy_master_contract( ethereum_client, deployer_account, get_safe_V1_3_0_contract ) @classmethod def deploy_master_contract_v1_1_1( cls, ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy master contract v1.1.1. Takes deployer_account (if unlocked in the node) or the deployer private key Safe with version > v1.1.1 doesn't need to be initialized as it already has a constructor :param ethereum_client: :param deployer_account: Ethereum account :return: deployed contract address """ return cls._deploy_master_contract( ethereum_client, deployer_account, get_safe_V1_1_1_contract ) @staticmethod def deploy_master_contract_v1_0_0( ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy master contract. Takes deployer_account (if unlocked in the node) or the deployer private key :param ethereum_client: :param deployer_account: Ethereum account :return: deployed contract address """ safe_contract = get_safe_V1_0_0_contract(ethereum_client.w3) constructor_data = safe_contract.constructor().buildTransaction({"gas": 0})[ "data" ] initializer_data = safe_contract.functions.setup( # We use 2 owners that nobody controls for the master copy [ "0x0000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000003", ], 2, # Threshold. Maximum security NULL_ADDRESS, # Address for optional DELEGATE CALL b"", # Data for optional DELEGATE CALL NULL_ADDRESS, # Payment token 0, # Payment NULL_ADDRESS, # Refund receiver ).buildTransaction({"to": NULL_ADDRESS})["data"] ethereum_tx_sent = ethereum_client.deploy_and_initialize_contract( deployer_account, constructor_data, HexBytes(initializer_data) ) logger.info( "Deployed and initialized Safe Master Contract=%s by %s", ethereum_tx_sent.contract_address, deployer_account.address, ) return ethereum_tx_sent @staticmethod def deploy_master_contract_v0_0_1( ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy master contract. Takes deployer_account (if unlocked in the node) or the deployer private key :param ethereum_client: :param deployer_account: Ethereum account :return: deployed contract address """ safe_contract = get_safe_V0_0_1_contract(ethereum_client.w3) constructor_data = safe_contract.constructor().buildTransaction({"gas": 0})[ "data" ] initializer_data = safe_contract.functions.setup( # We use 2 owners that nobody controls for the master copy [ "0x0000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000003", ], 2, # Threshold. Maximum security NULL_ADDRESS, # Address for optional DELEGATE CALL b"", # Data for optional DELEGATE CALL ).buildTransaction({"to": NULL_ADDRESS})["data"] ethereum_tx_sent = ethereum_client.deploy_and_initialize_contract( deployer_account, constructor_data, HexBytes(initializer_data) ) logger.info( "Deployed and initialized Old Safe Master Contract=%s by %s", ethereum_tx_sent.contract_address, deployer_account.address, ) return ethereum_tx_sent @staticmethod def estimate_safe_creation( ethereum_client: EthereumClient, old_master_copy_address: str, number_owners: int, gas_price: int, payment_token: Optional[str], payment_receiver: str = NULL_ADDRESS, payment_token_eth_value: float = 1.0, fixed_creation_cost: Optional[int] = None, ) -> SafeCreationEstimate: s = 15 owners = [get_eth_address_with_key()[0] for _ in range(number_owners)] threshold = number_owners safe_creation_tx = SafeCreationTx( w3=ethereum_client.w3, owners=owners, threshold=threshold, signature_s=s, master_copy=old_master_copy_address, gas_price=gas_price, funder=payment_receiver, payment_token=payment_token, payment_token_eth_value=payment_token_eth_value, fixed_creation_cost=fixed_creation_cost, ) return SafeCreationEstimate( safe_creation_tx.gas, safe_creation_tx.gas_price, safe_creation_tx.payment, safe_creation_tx.payment_token, ) @staticmethod def estimate_safe_creation_2( ethereum_client: EthereumClient, master_copy_address: str, proxy_factory_address: str, number_owners: int, gas_price: int, payment_token: Optional[str], payment_receiver: str = NULL_ADDRESS, fallback_handler: Optional[str] = None, payment_token_eth_value: float = 1.0, fixed_creation_cost: Optional[int] = None, ) -> SafeCreationEstimate: salt_nonce = 15 owners = [Account.create().address for _ in range(number_owners)] threshold = number_owners if not fallback_handler: fallback_handler = ( Account.create().address ) # Better estimate it, it's required for new Safes safe_creation_tx = SafeCreate2TxBuilder( w3=ethereum_client.w3, master_copy_address=master_copy_address, proxy_factory_address=proxy_factory_address, ).build( owners=owners, threshold=threshold, fallback_handler=fallback_handler, salt_nonce=salt_nonce, gas_price=gas_price, payment_receiver=payment_receiver, payment_token=payment_token, payment_token_eth_value=payment_token_eth_value, fixed_creation_cost=fixed_creation_cost, ) return SafeCreationEstimate( safe_creation_tx.gas, safe_creation_tx.gas_price, safe_creation_tx.payment, safe_creation_tx.payment_token, ) @staticmethod def build_safe_creation_tx( ethereum_client: EthereumClient, master_copy_old_address: str, s: int, owners: List[str], threshold: int, gas_price: int, payment_token: Optional[str], payment_receiver: str, payment_token_eth_value: float = 1.0, fixed_creation_cost: Optional[int] = None, ) -> SafeCreationTx: try: safe_creation_tx = SafeCreationTx( w3=ethereum_client.w3, owners=owners, threshold=threshold, signature_s=s, master_copy=master_copy_old_address, gas_price=gas_price, funder=payment_receiver, payment_token=payment_token, payment_token_eth_value=payment_token_eth_value, fixed_creation_cost=fixed_creation_cost, ) except InvalidERC20Token as exc: raise InvalidPaymentToken( "Invalid payment token %s" % payment_token ) from exc assert safe_creation_tx.tx_pyethereum.nonce == 0 return safe_creation_tx @staticmethod def build_safe_create2_tx( ethereum_client: EthereumClient, master_copy_address: str, proxy_factory_address: str, salt_nonce: int, owners: List[str], threshold: int, gas_price: int, payment_token: Optional[str], payment_receiver: Optional[str] = None, # If none, it will be `tx.origin` fallback_handler: Optional[str] = NULL_ADDRESS, payment_token_eth_value: float = 1.0, fixed_creation_cost: Optional[int] = None, ) -> SafeCreate2Tx: """ Prepare safe proxy deployment for being relayed. It calculates and sets the costs of deployment to be returned to the sender of the tx. If you are an advanced user you may prefer to use `create` function """ try: safe_creation_tx = SafeCreate2TxBuilder( w3=ethereum_client.w3, master_copy_address=master_copy_address, proxy_factory_address=proxy_factory_address, ).build( owners=owners, threshold=threshold, fallback_handler=fallback_handler, salt_nonce=salt_nonce, gas_price=gas_price, payment_receiver=payment_receiver, payment_token=payment_token, payment_token_eth_value=payment_token_eth_value, fixed_creation_cost=fixed_creation_cost, ) except InvalidERC20Token as exc: raise InvalidPaymentToken( "Invalid payment token %s" % payment_token ) from exc return safe_creation_tx def check_funds_for_tx_gas( self, safe_tx_gas: int, base_gas: int, gas_price: int, gas_token: str ) -> bool: """ Check safe has enough funds to pay for a tx :param safe_tx_gas: Safe tx gas :param base_gas: Data gas :param gas_price: Gas Price :param gas_token: Gas Token, to use token instead of ether for the gas :return: `True` if enough funds, `False` otherwise """ if gas_token == NULL_ADDRESS: balance = self.ethereum_client.get_balance(self.address) else: balance = self.ethereum_client.erc20.get_balance(self.address, gas_token) return balance >= (safe_tx_gas + base_gas) * gas_price def estimate_tx_base_gas( self, to: str, value: int, data: bytes, operation: int, gas_token: str, estimated_tx_gas: int, ) -> int: """ Calculate gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund...) :param to: :param value: :param data: :param operation: :param gas_token: :param estimated_tx_gas: gas calculated with `estimate_tx_gas` :return: """ data = data or b"" safe_contract = self.get_contract() threshold = self.retrieve_threshold() nonce = self.retrieve_nonce() # Every byte == 0 -> 4 Gas # Every byte != 0 -> 16 Gas (68 before Istanbul) # numbers < 256 (0x00(31*2)..ff) are 192 -> 31 * 4 + 1 * GAS_CALL_DATA_BYTE # numbers < 65535 (0x(30*2)..ffff) are 256 -> 30 * 4 + 2 * GAS_CALL_DATA_BYTE # Calculate gas for signatures # (array count (3 -> r, s, v) + ecrecover costs) * signature count # ecrecover for ecdsa ~= 4K gas, we use 6K ecrecover_gas = 6000 signature_gas = threshold * ( 1 * GAS_CALL_DATA_BYTE + 2 * 32 * GAS_CALL_DATA_BYTE + ecrecover_gas ) safe_tx_gas = estimated_tx_gas base_gas = 0 gas_price = 1 gas_token = gas_token or NULL_ADDRESS signatures = b"" refund_receiver = NULL_ADDRESS data = HexBytes( safe_contract.functions.execTransaction( to, value, data, operation, safe_tx_gas, base_gas, gas_price, gas_token, refund_receiver, signatures, ).buildTransaction({"gas": 1, "gasPrice": 1})["data"] ) # If nonce == 0, nonce storage has to be initialized if nonce == 0: nonce_gas = 20000 else: nonce_gas = 5000 # Keccak costs for the hash of the safe tx hash_generation_gas = 1500 base_gas = ( signature_gas + self.ethereum_client.estimate_data_gas(data) + nonce_gas + hash_generation_gas ) # Add additional gas costs if base_gas > 65536: base_gas += 64 else: base_gas += 128 base_gas += 32000 # Base tx costs, transfer costs... return base_gas def estimate_tx_gas_with_safe( self, to: str, value: int, data: bytes, operation: int, gas_limit: Optional[int] = None, block_identifier: Optional[BlockIdentifier] = "latest", ) -> int: """ Estimate tx gas using safe `requiredTxGas` method :return: int: Estimated gas :raises: CannotEstimateGas: If gas cannot be estimated :raises: ValueError: Cannot decode received data """ safe_address = self.address data = data or b"" def parse_revert_data(result: bytes) -> int: # 4 bytes - error method id # 32 bytes - position # 32 bytes - length # Last 32 bytes - value of revert (if everything went right) gas_estimation_offset = 4 + 32 + 32 gas_estimation = result[gas_estimation_offset:] # Estimated gas must be 32 bytes if len(gas_estimation) != 32: gas_limit_text = ( f"with gas limit={gas_limit} " if gas_limit is not None else "without gas limit set " ) logger.warning( "Safe=%s Problem estimating gas, returned value %sis %s for tx=%s", safe_address, gas_limit_text, result.hex(), tx, ) raise CannotEstimateGas("Received %s for tx=%s" % (result.hex(), tx)) return int(gas_estimation.hex(), 16) tx = ( self.get_contract() .functions.requiredTxGas(to, value, data, operation) .buildTransaction( { "from": safe_address, "gas": 0, # Don't call estimate "gasPrice": 0, # Don't get gas price } ) ) tx_params = { "from": safe_address, "to": safe_address, "data": tx["data"], } if gas_limit: tx_params["gas"] = hex(gas_limit) query = { "jsonrpc": "2.0", "method": "eth_call", "params": [tx_params, block_identifier], "id": 1, } response = self.ethereum_client.http_session.post( self.ethereum_client.ethereum_node_url, json=query, timeout=30 ) if response.ok: response_data = response.json() error_data: Optional[str] = None if "error" in response_data and "data" in response_data["error"]: error_data = response_data["error"]["data"] elif "result" in response_data: # Ganache-cli error_data = response_data["result"] if error_data: if "0x" in error_data: return parse_revert_data( HexBytes(error_data[error_data.find("0x") :]) ) raise CannotEstimateGas( f"Received {response.status_code} - {response.content} from ethereum node" ) def estimate_tx_gas_with_web3(self, to: str, value: int, data: EthereumData) -> int: """ :param to: :param value: :param data: :return: Estimation using web3 `estimate_gas` """ try: return self.ethereum_client.estimate_gas( to, from_=self.address, value=value, data=data ) except ValueError as exc: raise CannotEstimateGas( f"Cannot estimate gas with `eth_estimateGas`: {exc}" ) from exc def estimate_tx_gas_by_trying( self, to: str, value: int, data: Union[bytes, str], operation: int ): """ Try to get an estimation with Safe's `requiredTxGas`. If estimation if successful, try to set a gas limit and estimate again. If gas estimation is ok, same gas estimation should be returned, if it's less than required estimation will not be completed, so estimation was not accurate and gas limit needs to be increased. :param to: :param value: :param data: :param operation: :return: Estimated gas calling `requiredTxGas` setting a gas limit and checking if `eth_call` is successful :raises: CannotEstimateGas """ if not data: data = b"" elif isinstance(data, str): data = HexBytes(data) gas_estimated = self.estimate_tx_gas_with_safe(to, value, data, operation) block_gas_limit: Optional[int] = None base_gas: Optional[int] = self.ethereum_client.estimate_data_gas(data) for i in range( 1, 30 ): # Make sure tx can be executed, fixing for example 63/64th problem try: self.estimate_tx_gas_with_safe( to, value, data, operation, gas_limit=gas_estimated + base_gas + 32000, ) return gas_estimated except CannotEstimateGas: logger.warning( "Safe=%s - Found 63/64 problem gas-estimated=%d to=%s data=%s", self.address, gas_estimated, to, data.hex(), ) block_gas_limit = ( block_gas_limit or self.w3.eth.get_block("latest", full_transactions=False)[ "gasLimit" ] ) gas_estimated = math.floor((1 + i * 0.03) * gas_estimated) if gas_estimated >= block_gas_limit: return block_gas_limit return gas_estimated def estimate_tx_gas(self, to: str, value: int, data: bytes, operation: int) -> int: """ Estimate tx gas. Use `requiredTxGas` on the Safe contract and fallbacks to `eth_estimateGas` if that method fails. Note: `eth_estimateGas` cannot estimate delegate calls :param to: :param value: :param data: :param operation: :return: Estimated gas for Safe inner tx :raises: CannotEstimateGas """ # Costs to route through the proxy and nested calls PROXY_GAS = 1000 # https://github.com/ethereum/solidity/blob/dfe3193c7382c80f1814247a162663a97c3f5e67/libsolidity/codegen/ExpressionCompiler.cpp#L1764 # This was `false` before solc 0.4.21 -> `m_context.evmVersion().canOverchargeGasForCall()` # So gas needed by caller will be around 35k OLD_CALL_GAS = 35000 # Web3 `estimate_gas` estimates less gas WEB3_ESTIMATION_OFFSET = 20000 ADDITIONAL_GAS = PROXY_GAS + OLD_CALL_GAS try: return ( self.estimate_tx_gas_by_trying(to, value, data, operation) + ADDITIONAL_GAS ) except CannotEstimateGas: return ( self.estimate_tx_gas_with_web3(to, value, data) + ADDITIONAL_GAS + WEB3_ESTIMATION_OFFSET ) def estimate_tx_operational_gas(self, data_bytes_length: int): """ DEPRECATED. `estimate_tx_base_gas` already includes this. Estimates the gas for the verification of the signatures and other safe related tasks before and after executing a transaction. Calculation will be the sum of: - Base cost of 15000 gas - 100 of gas per word of `data_bytes` - Validate the signatures 5000 * threshold (ecrecover for ecdsa ~= 4K gas) :param data_bytes_length: Length of the data (in bytes, so `len(HexBytes('0x12'))` would be `1` :return: gas costs per signature * threshold of Safe """ threshold = self.retrieve_threshold() return 15000 + data_bytes_length // 32 * 100 + 5000 * threshold @cache def get_contract(self) -> Contract: v_1_3_0_contract = get_safe_V1_3_0_contract(self.w3, address=self.address) version = v_1_3_0_contract.functions.VERSION().call() if version == "1.3.0": return v_1_3_0_contract else: return get_safe_V1_1_1_contract(self.w3, address=self.address) def retrieve_all_info( self, block_identifier: Optional[BlockIdentifier] = "latest" ) -> SafeInfo: """ Get all Safe info in the same batch call. :param block_identifier: :return: :raises: CannotRetrieveSafeInfoException """ try: contract = self.get_contract() master_copy = self.retrieve_master_copy_address() fallback_handler = self.retrieve_fallback_handler() guard = self.retrieve_guard() results = self.ethereum_client.batch_call( [ contract.functions.getModulesPaginated( SENTINEL_ADDRESS, 20 ), # Does not exist in version < 1.1.1 contract.functions.nonce(), contract.functions.getOwners(), contract.functions.getThreshold(), contract.functions.VERSION(), ], from_address=self.address, block_identifier=block_identifier, raise_exception=False, ) modules_response, nonce, owners, threshold, version = results if modules_response: modules, next_module = modules_response if ( not modules_response or next_module != SENTINEL_ADDRESS ): # < 1.1.1 or still more elements in the list modules = self.retrieve_modules() return SafeInfo( self.address, fallback_handler, guard, master_copy, modules, nonce, owners, threshold, version, ) except (ValueError, BadFunctionCallOutput) as e: raise CannotRetrieveSafeInfoException(self.address) from e def retrieve_code(self) -> HexBytes: return self.w3.eth.get_code(self.address) def retrieve_fallback_handler( self, block_identifier: Optional[BlockIdentifier] = "latest" ) -> ChecksumAddress: address = self.ethereum_client.w3.eth.get_storage_at( self.address, self.FALLBACK_HANDLER_STORAGE_SLOT, block_identifier=block_identifier, )[-20:] if len(address) == 20: return Web3.toChecksumAddress(address) else: return NULL_ADDRESS def retrieve_guard( self, block_identifier: Optional[BlockIdentifier] = "latest" ) -> ChecksumAddress: address = self.ethereum_client.w3.eth.get_storage_at( self.address, self.GUARD_STORAGE_SLOT, block_identifier=block_identifier )[-20:] if len(address) == 20: return Web3.toChecksumAddress(address) else: return NULL_ADDRESS def retrieve_master_copy_address( self, block_identifier: Optional[BlockIdentifier] = "latest" ) -> ChecksumAddress: bytes_address = self.w3.eth.get_storage_at( self.address, "0x00", block_identifier=block_identifier )[-20:] int_address = int.from_bytes(bytes_address, byteorder="big") return Web3.toChecksumAddress("{:#042x}".format(int_address)) def retrieve_modules( self, pagination: Optional[int] = 50, block_identifier: Optional[BlockIdentifier] = "latest", ) -> List[str]: """ :param pagination: Number of modules to get per request :param block_identifier: :return: List of module addresses """ try: # Contracts with Safe version < 1.1.0 were not paginated contract = get_safe_V1_0_0_contract( self.ethereum_client.w3, address=self.address ) return contract.functions.getModules().call( block_identifier=block_identifier ) except BadFunctionCallOutput: pass contract = self.get_contract() address = SENTINEL_ADDRESS all_modules: List[str] = [] while True: (modules, address) = contract.functions.getModulesPaginated( address, pagination ).call(block_identifier=block_identifier) all_modules.extend(modules) if address == SENTINEL_ADDRESS: break else: all_modules.append(address) return all_modules def retrieve_is_hash_approved( self, owner: str, safe_hash: bytes, block_identifier: Optional[BlockIdentifier] = "latest", ) -> bool: return ( self.get_contract() .functions.approvedHashes(owner, safe_hash) .call(block_identifier=block_identifier) == 1 ) def retrieve_is_message_signed( self, message_hash: bytes, block_identifier: Optional[BlockIdentifier] = "latest", ) -> bool: return ( self.get_contract() .functions.signedMessages(message_hash) .call(block_identifier=block_identifier) ) def retrieve_is_owner( self, owner: str, block_identifier: Optional[BlockIdentifier] = "latest" ) -> bool: return ( self.get_contract() .functions.isOwner(owner) .call(block_identifier=block_identifier) ) def retrieve_nonce( self, block_identifier: Optional[BlockIdentifier] = "latest" ) -> int: return ( self.get_contract() .functions.nonce() .call(block_identifier=block_identifier) ) def retrieve_owners( self, block_identifier: Optional[BlockIdentifier] = "latest" ) -> List[str]: return ( self.get_contract() .functions.getOwners() .call(block_identifier=block_identifier) ) def retrieve_threshold( self, block_identifier: Optional[BlockIdentifier] = "latest" ) -> int: return ( self.get_contract() .functions.getThreshold() .call(block_identifier=block_identifier) ) def retrieve_version( self, block_identifier: Optional[BlockIdentifier] = "latest" ) -> str: return ( self.get_contract() .functions.VERSION() .call(block_identifier=block_identifier) ) def build_multisig_tx( self, to: str, value: int, data: bytes, operation: int = SafeOperation.CALL.value, safe_tx_gas: int = 0, base_gas: int = 0, gas_price: int = 0, gas_token: str = NULL_ADDRESS, refund_receiver: str = NULL_ADDRESS, signatures: bytes = b"", safe_nonce: Optional[int] = None, safe_version: Optional[str] = None, ) -> SafeTx: """ Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction. The fees are always transfered, even if the user transaction fails :param to: Destination address of Safe transaction :param value: Ether value of Safe transaction :param data: Data payload of Safe transaction :param operation: Operation type of Safe transaction :param safe_tx_gas: Gas that should be used for the Safe transaction :param base_gas: Gas costs for that are independent of the transaction execution (e.g. base transaction fee, signature check, payment of the refund) :param gas_price: Gas price that should be used for the payment calculation :param gas_token: Token address (or `0x000..000` if ETH) that is used for the payment :param refund_receiver: Address of receiver of gas payment (or `0x000..000` if tx.origin). :param signatures: Packed signature data ({bytes32 r}{bytes32 s}{uint8 v}) :param safe_nonce: Nonce of the safe (to calculate hash) :param safe_version: Safe version (to calculate hash) :return: """ if safe_nonce is None: safe_nonce = self.retrieve_nonce() safe_version = safe_version or self.retrieve_version() return SafeTx( self.ethereum_client, self.address, to, value, data, operation, safe_tx_gas, base_gas, gas_price, gas_token, refund_receiver, signatures=signatures, safe_nonce=safe_nonce, safe_version=safe_version, ) def send_multisig_tx( self, to: str, value: int, data: bytes, operation: int, safe_tx_gas: int, base_gas: int, gas_price: int, gas_token: str, refund_receiver: str, signatures: bytes, tx_sender_private_key: str, tx_gas=None, tx_gas_price=None, block_identifier: Optional[BlockIdentifier] = "latest", ) -> EthereumTxSent: """ Build and send Safe tx :param to: :param value: :param data: :param operation: :param safe_tx_gas: :param base_gas: :param gas_price: :param gas_token: :param refund_receiver: :param signatures: :param tx_sender_private_key: :param tx_gas: Gas for the external tx. If not, `(safe_tx_gas + data_gas) * 2` will be used :param tx_gas_price: Gas price of the external tx. If not, `gas_price` will be used :param block_identifier: :return: Tuple(tx_hash, tx) :raises: InvalidMultisigTx: If user tx cannot go through the Safe """ safe_tx = self.build_multisig_tx( to, value, data, operation, safe_tx_gas, base_gas, gas_price, gas_token, refund_receiver, signatures, ) tx_sender_address = Account.from_key(tx_sender_private_key).address safe_tx.call( tx_sender_address=tx_sender_address, block_identifier=block_identifier ) tx_hash, tx = safe_tx.execute( tx_sender_private_key=tx_sender_private_key, tx_gas=tx_gas, tx_gas_price=tx_gas_price, block_identifier=block_identifier, ) return EthereumTxSent(tx_hash, tx, None)
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/safe/safe.py
0.878887
0.176334
safe.py
pypi
from logging import getLogger from typing import Optional from eth_account.signers.local import LocalAccount from eth_typing import ChecksumAddress from web3 import Web3 from web3.contract import Contract from gnosis.eth import EthereumClient from gnosis.eth.contracts import ( get_paying_proxy_deployed_bytecode, get_proxy_1_0_0_deployed_bytecode, get_proxy_1_1_1_deployed_bytecode, get_proxy_1_1_1_mainnet_deployed_bytecode, get_proxy_1_3_0_deployed_bytecode, get_proxy_factory_contract, get_proxy_factory_V1_0_0_contract, get_proxy_factory_V1_1_1_contract, ) from gnosis.eth.ethereum_client import EthereumTxSent from gnosis.eth.utils import compare_byte_code try: from functools import cache except ImportError: from functools import lru_cache cache = lru_cache(maxsize=None) logger = getLogger(__name__) class ProxyFactory: def __init__(self, address: ChecksumAddress, ethereum_client: EthereumClient): assert Web3.isChecksumAddress(address), ( "%s proxy factory address not valid" % address ) self.address = address self.ethereum_client = ethereum_client self.w3 = ethereum_client.w3 @staticmethod def _deploy_proxy_factory_contract( ethereum_client: EthereumClient, deployer_account: LocalAccount, contract: Contract, ) -> EthereumTxSent: tx = contract.constructor().buildTransaction({"from": deployer_account.address}) tx_hash = ethereum_client.send_unsigned_transaction( tx, private_key=deployer_account.key ) tx_receipt = ethereum_client.get_transaction_receipt(tx_hash, timeout=120) assert tx_receipt assert tx_receipt["status"] contract_address = tx_receipt["contractAddress"] logger.info( "Deployed and initialized Proxy Factory Contract=%s by %s", contract_address, deployer_account.address, ) return EthereumTxSent(tx_hash, tx, contract_address) @classmethod def deploy_proxy_factory_contract( cls, ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy proxy factory contract last version (v1.3.0) :param ethereum_client: :param deployer_account: Ethereum Account :return: deployed contract address """ proxy_factory_contract = get_proxy_factory_contract(ethereum_client.w3) return cls._deploy_proxy_factory_contract( ethereum_client, deployer_account, proxy_factory_contract ) @classmethod def deploy_proxy_factory_contract_v1_1_1( cls, ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy proxy factory contract v1.1.1 :param ethereum_client: :param deployer_account: Ethereum Account :return: deployed contract address """ proxy_factory_contract = get_proxy_factory_V1_1_1_contract(ethereum_client.w3) return cls._deploy_proxy_factory_contract( ethereum_client, deployer_account, proxy_factory_contract ) @classmethod def deploy_proxy_factory_contract_v1_0_0( cls, ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy proxy factory contract v1.0.0 :param ethereum_client: :param deployer_account: Ethereum Account :return: deployed contract address """ proxy_factory_contract = get_proxy_factory_V1_0_0_contract(ethereum_client.w3) return cls._deploy_proxy_factory_contract( ethereum_client, deployer_account, proxy_factory_contract ) def check_proxy_code(self, address: ChecksumAddress) -> bool: """ Check if proxy is valid :param address: Ethereum address to check :return: True if proxy is valid, False otherwise """ deployed_proxy_code = self.w3.eth.get_code(address) proxy_code_fns = ( get_proxy_1_3_0_deployed_bytecode, get_proxy_1_1_1_deployed_bytecode, get_proxy_1_1_1_mainnet_deployed_bytecode, get_proxy_1_0_0_deployed_bytecode, get_paying_proxy_deployed_bytecode, self.get_proxy_runtime_code, ) for proxy_code_fn in proxy_code_fns: if compare_byte_code(deployed_proxy_code, proxy_code_fn()): return True return False def deploy_proxy_contract( self, deployer_account: LocalAccount, master_copy: ChecksumAddress, initializer: bytes = b"", gas: Optional[int] = None, gas_price: Optional[int] = None, ) -> EthereumTxSent: """ Deploy proxy contract via ProxyFactory using `createProxy` function :param deployer_account: Ethereum account :param master_copy: Address the proxy will point at :param initializer: Initializer :param gas: Gas :param gas_price: Gas Price :return: EthereumTxSent """ proxy_factory_contract = self.get_contract() create_proxy_fn = proxy_factory_contract.functions.createProxy( master_copy, initializer ) tx_parameters = {"from": deployer_account.address} contract_address = create_proxy_fn.call(tx_parameters) if gas_price is not None: tx_parameters["gasPrice"] = gas_price if gas is not None: tx_parameters["gas"] = gas tx = create_proxy_fn.buildTransaction(tx_parameters) # Auto estimation of gas does not work. We use a little more gas just in case tx["gas"] = tx["gas"] + 50000 tx_hash = self.ethereum_client.send_unsigned_transaction( tx, private_key=deployer_account.key ) return EthereumTxSent(tx_hash, tx, contract_address) def deploy_proxy_contract_with_nonce( self, deployer_account: LocalAccount, master_copy: ChecksumAddress, initializer: bytes, salt_nonce: int, gas: Optional[int] = None, gas_price: Optional[int] = None, nonce: Optional[int] = None, ) -> EthereumTxSent: """ Deploy proxy contract via Proxy Factory using `createProxyWithNonce` (create2) :param deployer_account: Ethereum account :param master_copy: Address the proxy will point at :param initializer: Data for safe creation :param salt_nonce: Uint256 for `create2` salt :param gas: Gas :param gas_price: Gas Price :param nonce: Nonce :return: Tuple(tx-hash, tx, deployed contract address) """ proxy_factory_contract = self.get_contract() create_proxy_fn = proxy_factory_contract.functions.createProxyWithNonce( master_copy, initializer, salt_nonce ) tx_parameters = {"from": deployer_account.address} contract_address = create_proxy_fn.call(tx_parameters) if gas_price is not None: tx_parameters["gasPrice"] = gas_price if gas is not None: tx_parameters["gas"] = gas if nonce is not None: tx_parameters["nonce"] = nonce tx = create_proxy_fn.buildTransaction(tx_parameters) # Auto estimation of gas does not work. We use a little more gas just in case tx["gas"] = tx["gas"] + 50000 tx_hash = self.ethereum_client.send_unsigned_transaction( tx, private_key=deployer_account.key ) return EthereumTxSent(tx_hash, tx, contract_address) def get_contract(self, address: Optional[ChecksumAddress] = None): address = address or self.address return get_proxy_factory_contract(self.ethereum_client.w3, address) @cache def get_proxy_runtime_code(self, address: Optional[ChecksumAddress] = None): """ Get runtime code for current proxy factory """ address = address or self.address return self.get_contract(address=address).functions.proxyRuntimeCode().call()
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/safe/proxy_factory.py
0.912629
0.16492
proxy_factory.py
pypi
from rest_framework import serializers from rest_framework.exceptions import ValidationError from gnosis.eth.constants import ( SIGNATURE_R_MAX_VALUE, SIGNATURE_R_MIN_VALUE, SIGNATURE_S_MAX_VALUE, SIGNATURE_S_MIN_VALUE, SIGNATURE_V_MAX_VALUE, SIGNATURE_V_MIN_VALUE, ) from gnosis.eth.django.serializers import EthereumAddressField, HexadecimalField from .safe import SafeOperation class SafeSignatureSerializer(serializers.Serializer): """ When using safe signatures `v` can have more values """ v = serializers.IntegerField(min_value=0) r = serializers.IntegerField(min_value=0) s = serializers.IntegerField(min_value=0) def validate_v(self, v): if v == 0: # Contract signature return v elif v == 1: # Approved hash return v elif v > 30 and self.check_v(v - 4): # Support eth_sign return v elif self.check_v(v): return v else: raise serializers.ValidationError( "v should be 0, 1 or be in %d-%d" % (SIGNATURE_V_MIN_VALUE, SIGNATURE_V_MAX_VALUE) ) def validate(self, data): super().validate(data) v = data["v"] r = data["r"] s = data["s"] if v not in [0, 1]: # Disable checks for `r` and `s` if v is 0 or 1 if not self.check_r(r): raise serializers.ValidationError("r not valid") elif not self.check_s(s): raise serializers.ValidationError("s not valid") return data def check_v(self, v): return SIGNATURE_V_MIN_VALUE <= v <= SIGNATURE_V_MAX_VALUE def check_r(self, r): return SIGNATURE_R_MIN_VALUE <= r <= SIGNATURE_R_MAX_VALUE def check_s(self, s): return SIGNATURE_S_MIN_VALUE <= s <= SIGNATURE_S_MAX_VALUE class SafeMultisigEstimateTxSerializer(serializers.Serializer): safe = EthereumAddressField() to = EthereumAddressField() value = serializers.IntegerField(min_value=0) data = HexadecimalField(default=None, allow_null=True, allow_blank=True) operation = serializers.IntegerField(min_value=0) gas_token = EthereumAddressField( default=None, allow_null=True, allow_zero_address=True ) def validate_operation(self, value): try: return SafeOperation(value).value except ValueError: raise ValidationError("Unknown operation") def validate(self, data): super().validate(data) if not data["to"] and not data["data"]: raise ValidationError("`data` and `to` cannot both be null") if not data["to"] and not data["data"]: raise ValidationError("`data` and `to` cannot both be null") if data["operation"] == SafeOperation.CREATE.value: raise ValidationError( "Operation CREATE not supported. Please use Gnosis Safe CreateLib" ) # if data['to']: # raise ValidationError('Operation is Create, but `to` was provided') # elif not data['data']: # raise ValidationError('Operation is Create, but not `data` was provided') return data class SafeMultisigTxSerializer(SafeMultisigEstimateTxSerializer): """ DEPRECATED, use `SafeMultisigTxSerializerV1` instead """ safe_tx_gas = serializers.IntegerField(min_value=0) data_gas = serializers.IntegerField(min_value=0) gas_price = serializers.IntegerField(min_value=0) refund_receiver = EthereumAddressField( default=None, allow_null=True, allow_zero_address=True ) nonce = serializers.IntegerField(min_value=0) class SafeMultisigTxSerializerV1(SafeMultisigEstimateTxSerializer): """ Version 1.0.0 of the Safe changes `data_gas` to `base_gas` """ safe_tx_gas = serializers.IntegerField(min_value=0) base_gas = serializers.IntegerField(min_value=0) gas_price = serializers.IntegerField(min_value=0) refund_receiver = EthereumAddressField( default=None, allow_null=True, allow_zero_address=True ) nonce = serializers.IntegerField(min_value=0)
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/safe/serializers.py
0.78838
0.331039
serializers.py
pypi
import math import os from logging import getLogger from typing import Any, Dict, List, Optional, Tuple import rlp from eth.constants import SECPK1_N from eth.vm.forks.frontier.transactions import FrontierTransaction from eth_keys.exceptions import BadSignature from eth_utils import to_canonical_address, to_checksum_address from hexbytes import HexBytes from web3 import Web3 from web3.contract import ContractConstructor from gnosis.eth.constants import GAS_CALL_DATA_BYTE, NULL_ADDRESS from gnosis.eth.contracts import ( get_erc20_contract, get_paying_proxy_contract, get_safe_V0_0_1_contract, ) from gnosis.eth.utils import mk_contract_address logger = getLogger(__name__) class InvalidERC20Token(Exception): pass class SafeCreationTx: def __init__( self, w3: Web3, owners: List[str], threshold: int, signature_s: int, master_copy: str, gas_price: int, funder: Optional[str], payment_token: Optional[str] = None, payment_token_eth_value: float = 1.0, fixed_creation_cost: Optional[int] = None, ): """ Prepare Safe creation :param w3: Web3 instance :param owners: Owners of the Safe :param threshold: Minimum number of users required to operate the Safe :param signature_s: Random s value for ecdsa signature :param master_copy: Safe master copy address :param gas_price: Gas Price :param funder: Address to refund when the Safe is created. Address(0) if no need to refund :param payment_token: Payment token instead of paying the funder with ether. If None Ether will be used :param payment_token_eth_value: Value of payment token per 1 Ether :param fixed_creation_cost: Fixed creation cost of Safe (Wei) """ assert 0 < threshold <= len(owners) funder = funder or NULL_ADDRESS payment_token = payment_token or NULL_ADDRESS assert Web3.isChecksumAddress(master_copy) assert Web3.isChecksumAddress(funder) assert Web3.isChecksumAddress(payment_token) self.w3 = w3 self.owners = owners self.threshold = threshold self.s = signature_s self.master_copy = master_copy self.gas_price = gas_price self.funder = funder self.payment_token = payment_token self.payment_token_eth_value = payment_token_eth_value self.fixed_creation_cost = fixed_creation_cost # Get bytes for `setup(address[] calldata _owners, uint256 _threshold, address to, bytes calldata data)` # This initializer will be passed to the proxy and will be called right after proxy is deployed safe_setup_data: bytes = self._get_initial_setup_safe_data(owners, threshold) # Calculate gas based on experience of previous deployments of the safe calculated_gas: int = self._calculate_gas( owners, safe_setup_data, payment_token ) # Estimate gas using web3 estimated_gas: int = self._estimate_gas( master_copy, safe_setup_data, funder, payment_token ) self.gas = max(calculated_gas, estimated_gas) # Payment will be safe deploy cost + transfer fees for sending ether to the deployer self.payment = self._calculate_refund_payment( self.gas, gas_price, fixed_creation_cost, payment_token_eth_value ) self.tx_dict: Dict[str, Any] = self._build_proxy_contract_creation_tx( master_copy=master_copy, initializer=safe_setup_data, funder=funder, payment_token=payment_token, payment=self.payment, gas=self.gas, gas_price=gas_price, ) self.tx_pyethereum: FrontierTransaction = ( self._build_contract_creation_tx_with_valid_signature(self.tx_dict, self.s) ) self.tx_raw = rlp.encode(self.tx_pyethereum) self.tx_hash = self.tx_pyethereum.hash self.deployer_address = to_checksum_address(self.tx_pyethereum.sender) self.safe_address = mk_contract_address(self.tx_pyethereum.sender, 0) self.v = self.tx_pyethereum.v self.r = self.tx_pyethereum.r self.safe_setup_data = safe_setup_data assert mk_contract_address(self.deployer_address, nonce=0) == self.safe_address @property def payment_ether(self): return self.gas * self.gas_price @staticmethod def find_valid_random_signature(s: int) -> Tuple[int, int]: """ Find v and r valid values for a given s :param s: random value :return: v, r """ for _ in range(10000): r = int(os.urandom(31).hex(), 16) v = (r % 2) + 27 if r < SECPK1_N: tx = FrontierTransaction(0, 1, 21000, b"", 0, b"", v=v, r=r, s=s) try: tx.sender return v, r except (BadSignature, ValueError): logger.debug("Cannot find signature with v=%d r=%d s=%d", v, r, s) raise ValueError("Valid signature not found with s=%d", s) @staticmethod def _calculate_gas( owners: List[str], safe_setup_data: bytes, payment_token: str ) -> int: """ Calculate gas manually, based on tests of previosly deployed safes :param owners: Safe owners :param safe_setup_data: Data for proxy setup :param payment_token: If payment token, we will need more gas to transfer and maybe storage if first time :return: total gas needed for deployment """ # TODO Do gas calculation estimating the call instead this magic base_gas = 60580 # Transaction standard gas # If we already have the token, we don't have to pay for storage, so it will be just 5K instead of 20K. # The other 1K is for overhead of making the call if payment_token != NULL_ADDRESS: payment_token_gas = 55000 else: payment_token_gas = 0 data_gas = GAS_CALL_DATA_BYTE * len(safe_setup_data) # Data gas gas_per_owner = 18020 # Magic number calculated by testing and averaging owners return ( base_gas + data_gas + payment_token_gas + 270000 + len(owners) * gas_per_owner ) @staticmethod def _calculate_refund_payment( gas: int, gas_price: int, fixed_creation_cost: Optional[int], payment_token_eth_value: float, ) -> int: if fixed_creation_cost is None: # Payment will be safe deploy cost + transfer fees for sending ether to the deployer base_payment: int = (gas + 23000) * gas_price # Calculate payment for tokens using the conversion (if used) return math.ceil(base_payment / payment_token_eth_value) else: return fixed_creation_cost def _build_proxy_contract_creation_constructor( self, master_copy: str, initializer: bytes, funder: str, payment_token: str, payment: int, ) -> ContractConstructor: """ :param master_copy: Master Copy of Gnosis Safe already deployed :param initializer: Data initializer to send to GnosisSafe setup method :param funder: Address that should get the payment (if payment set) :param payment_token: Address if a token is used. If not set, 0x0 will be ether :param payment: Payment :return: Transaction dictionary """ if not funder or funder == NULL_ADDRESS: funder = NULL_ADDRESS payment = 0 return get_paying_proxy_contract(self.w3).constructor( master_copy, initializer, funder, payment_token, payment ) def _build_proxy_contract_creation_tx( self, master_copy: str, initializer: bytes, funder: str, payment_token: str, payment: int, gas: int, gas_price: int, nonce: int = 0, ): """ :param master_copy: Master Copy of Gnosis Safe already deployed :param initializer: Data initializer to send to GnosisSafe setup method :param funder: Address that should get the payment (if payment set) :param payment_token: Address if a token is used. If not set, 0x0 will be ether :param payment: Payment :return: Transaction dictionary """ return self._build_proxy_contract_creation_constructor( master_copy, initializer, funder, payment_token, payment ).buildTransaction( { "gas": gas, "gasPrice": gas_price, "nonce": nonce, } ) def _build_contract_creation_tx_with_valid_signature( self, tx_dict: Dict[str, Any], s: int ) -> FrontierTransaction: """ Use pyethereum `Transaction` to generate valid tx using a random signature :param tx_dict: Web3 tx dictionary :param s: Signature s value :return: PyEthereum creation tx for the proxy contract """ zero_address = HexBytes("0x" + "0" * 40) f_address = HexBytes("0x" + "f" * 40) nonce = tx_dict["nonce"] gas_price = tx_dict["gasPrice"] gas = tx_dict["gas"] to = tx_dict.get("to", b"") # Contract creation should always have `to` empty value = tx_dict["value"] data = tx_dict["data"] for _ in range(100): try: v, r = self.find_valid_random_signature(s) contract_creation_tx = FrontierTransaction( nonce, gas_price, gas, to, value, HexBytes(data), v=v, r=r, s=s ) sender_address = contract_creation_tx.sender contract_address: bytes = to_canonical_address( mk_contract_address(sender_address, nonce) ) if sender_address in (zero_address, f_address) or contract_address in ( zero_address, f_address, ): raise ValueError("Invalid transaction") return contract_creation_tx except BadSignature: pass raise ValueError("Valid signature not found with s=%d", s) def _estimate_gas( self, master_copy: str, initializer: bytes, funder: str, payment_token: str ) -> int: """ Gas estimation done using web3 and calling the node Payment cannot be estimated, as no ether is in the address. So we add some gas later. :param master_copy: Master Copy of Gnosis Safe already deployed :param initializer: Data initializer to send to GnosisSafe setup method :param funder: Address that should get the payment (if payment set) :param payment_token: Address if a token is used. If not set, 0x0 will be ether :return: Total gas estimation """ # Estimate the contract deployment. We cannot estimate the refunding, as the safe address has not any fund gas: int = self._build_proxy_contract_creation_constructor( master_copy, initializer, funder, payment_token, 0 ).estimateGas() # We estimate the refund as a new tx if payment_token == NULL_ADDRESS: # Same cost to send 1 ether than 1000 gas += self.w3.eth.estimate_gas({"to": funder, "value": 1}) else: # Top should be around 52000 when storage is needed (funder no previous owner of token), # we use value 1 as we are simulating an internal call, and in that calls you don't pay for the data. # If it was a new tx sending 5000 tokens would be more expensive than sending 1 because of data costs try: gas += ( get_erc20_contract(self.w3, payment_token) .functions.transfer(funder, 1) .estimateGas({"from": payment_token}) ) except ValueError as exc: if "transfer amount exceeds balance" in str(exc): return 70000 raise InvalidERC20Token from exc return gas def _get_initial_setup_safe_data(self, owners: List[str], threshold: int) -> bytes: return ( get_safe_V0_0_1_contract(self.w3, self.master_copy) .functions.setup( owners, threshold, NULL_ADDRESS, # Contract address for optional delegate call b"", # Data payload for optional delegate call ) .buildTransaction( { "gas": 1, "gasPrice": 1, } )["data"] )
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/safe/safe_creation_tx.py
0.79858
0.390302
safe_creation_tx.py
pypi
from typing import List, Tuple, Union from eth_keys import keys from eth_keys.exceptions import BadSignature from hexbytes import HexBytes from gnosis.eth.constants import NULL_ADDRESS def signature_split( signatures: Union[bytes, str], pos: int = 0 ) -> Tuple[int, int, int]: """ :param signatures: signatures in form of {bytes32 r}{bytes32 s}{uint8 v} :param pos: position of the signature :return: Tuple with v, r, s """ signatures = HexBytes(signatures) signature_pos = 65 * pos if len(signatures[signature_pos : signature_pos + 65]) < 65: raise ValueError(f"Signature must be at least 65 bytes {signatures.hex()}") r = int.from_bytes(signatures[signature_pos : 32 + signature_pos], "big") s = int.from_bytes(signatures[32 + signature_pos : 64 + signature_pos], "big") v = signatures[64 + signature_pos] return v, r, s def signature_to_bytes(v: int, r: int, s: int) -> bytes: """ Convert ecdsa signature to bytes :param v: :param r: :param s: :return: signature in form of {bytes32 r}{bytes32 s}{uint8 v} """ byte_order = "big" return ( r.to_bytes(32, byteorder=byte_order) + s.to_bytes(32, byteorder=byte_order) + v.to_bytes(1, byteorder=byte_order) ) def signatures_to_bytes(signatures: List[Tuple[int, int, int]]) -> bytes: """ Convert signatures to bytes :param signatures: list of tuples(v, r, s) :return: 65 bytes per signature """ return b"".join([signature_to_bytes(v, r, s) for v, r, s in signatures]) def get_signing_address(signed_hash: Union[bytes, str], v: int, r: int, s: int) -> str: """ :return: checksummed ethereum address, for example `0x568c93675A8dEb121700A6FAdDdfE7DFAb66Ae4A` :rtype: str or `NULL_ADDRESS` if signature is not valid """ try: public_key = keys.ecdsa_recover(signed_hash, keys.Signature(vrs=(v - 27, r, s))) return public_key.to_checksum_address() except BadSignature: return NULL_ADDRESS
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/safe/signatures.py
0.923049
0.493958
signatures.py
pypi
from typing import Any, Dict, List, Optional, Union, cast import requests from eip712_structs import make_domain from eth_account import Account from eth_account.messages import encode_defunct from eth_typing import AnyAddress, ChecksumAddress, HexStr from hexbytes import HexBytes from web3 import Web3 from gnosis.eth import EthereumNetwork, EthereumNetworkNotSupported from .order import Order, OrderKind try: from typing import TypedDict # pylint: disable=no-name-in-module except ImportError: from typing_extensions import TypedDict try: from functools import cache except ImportError: from functools import lru_cache cache = lru_cache(maxsize=None) class TradeResponse(TypedDict): blockNumber: int logIndex: int orderUid: HexStr buyAmount: str # Stringified int sellAmount: str # Stringified int sellAmountBeforeFees: str # Stringified int owner: AnyAddress # Not checksummed buyToken: AnyAddress sellToken: AnyAddress txHash: HexStr class AmountResponse(TypedDict): amount: str token: AnyAddress class ErrorResponse(TypedDict): error_type: str description: str class GnosisProtocolAPI: """ Client for GnosisProtocol API. More info: https://docs.cowswap.exchange/ """ settlement_contract_addresses = { EthereumNetwork.MAINNET: "0x9008D19f58AAbD9eD0D60971565AA8510560ab41", EthereumNetwork.RINKEBY: "0x9008D19f58AAbD9eD0D60971565AA8510560ab41", EthereumNetwork.XDAI: "0x9008D19f58AAbD9eD0D60971565AA8510560ab41", } api_base_urls = { EthereumNetwork.MAINNET: "https://api.cow.fi/mainnet/api/v1/", EthereumNetwork.RINKEBY: "https://api.cow.fi/rinkeby/api/v1/", EthereumNetwork.XDAI: "https://api.cow.fi/xdai/api/v1/", } def __init__(self, ethereum_network: EthereumNetwork): self.network = ethereum_network if self.network not in self.api_base_urls: raise EthereumNetworkNotSupported( f"{self.network.name} network not supported by Gnosis Protocol" ) self.domain_separator = self.build_domain_separator(self.network) self.base_url = self.api_base_urls[self.network] @classmethod def build_domain_separator(cls, ethereum_network: EthereumNetwork): return make_domain( name="Gnosis Protocol", version="v2", chainId=str(ethereum_network.value), verifyingContract=cls.settlement_contract_addresses[ethereum_network], ) def get_fee(self, order: Order) -> int: if order["kind"] == "sell": amount = order["sellAmount"] else: amount = order["buyAmount"] url = ( self.base_url + f'fee/?sellToken={order["sellToken"]}&buyToken={order["buyToken"]}' f'&amount={amount}&kind={order["kind"]}' ) result = requests.get(url).json() if "amount" in result: return int(result["amount"]) else: return 0 def place_order( self, order: Order, private_key: HexStr ) -> Union[HexStr, ErrorResponse]: """ Place order. If `feeAmount=0` in Order it will be calculated calling `get_fee(order)` :return: UUID for the order as an hex hash """ assert ( order["buyAmount"] and order["sellAmount"] ), "Order buyAmount and sellAmount cannot be empty" url = self.base_url + "orders/" order["feeAmount"] = order["feeAmount"] or self.get_fee(order) signable_bytes = order.signable_bytes(domain=self.domain_separator) signable_hash = Web3.keccak(signable_bytes) message = encode_defunct(primitive=signable_hash) signed_message = Account.from_key(private_key).sign_message(message) data_json = { "sellToken": order["sellToken"].lower(), "buyToken": order["buyToken"].lower(), "sellAmount": str(order["sellAmount"]), "buyAmount": str(order["buyAmount"]), "validTo": order["validTo"], "appData": HexBytes(order["appData"]).hex() if isinstance(order["appData"], bytes) else order["appData"], "feeAmount": str(order["feeAmount"]), "kind": order["kind"], "partiallyFillable": order["partiallyFillable"], "signature": signed_message.signature.hex(), "signingScheme": "ethsign", "from": Account.from_key(private_key).address, } r = requests.post(url, json=data_json) if r.ok: return HexStr(r.json()) else: return ErrorResponse(r.json()) def get_orders( self, owner: ChecksumAddress, offset: int = 0, limit=10 ) -> List[Dict[str, Any]]: """ :param owner: :param offset: Defaults to 0 :param limit: Defaults to 10. Maximum is 1000, minimum is 1 :return: Orders of one user paginated. The orders are ordered by their creation date descending (newest orders first). To enumerate all orders start with offset 0 and keep increasing the offset by the total number of returned results. When a response contains less than the limit the last page has been reached. """ url = self.base_url + f"account/{owner}/orders" r = requests.get(url) if r.ok: return cast(List[Dict[str, Any]], r.json()) else: return ErrorResponse(r.json()) def get_trades( self, order_ui: Optional[HexStr] = None, owner: Optional[ChecksumAddress] = None ) -> List[TradeResponse]: assert bool(order_ui) ^ bool( owner ), "order_ui or owner must be provided, but not both" url = self.base_url + "trades/?" if order_ui: url += f"orderUid={order_ui}" elif owner: url += f"owner={owner}" r = requests.get(url) if r.ok: return cast(List[TradeResponse], r.json()) else: return ErrorResponse(r.json()) def get_estimated_amount( self, base_token: ChecksumAddress, quote_token: ChecksumAddress, kind: OrderKind, amount: int, ) -> Union[AmountResponse, ErrorResponse]: """ The estimated amount in quote token for either buying or selling amount of baseToken. """ url = self.base_url + f"markets/{base_token}-{quote_token}/{kind.name}/{amount}" r = requests.get(url) if r.ok: return AmountResponse(r.json()) else: return ErrorResponse(r.json())
/safe_eth_py_log-4.0.1-py3-none-any.whl/gnosis/protocol/gnosis_protocol_api.py
0.847321
0.227813
gnosis_protocol_api.py
pypi
from enum import Enum, unique class EthereumNetworkNotSupported(Exception): pass @unique class EthereumNetwork(Enum): """ Use https://chainlist.org/ as a reference """ UNKNOWN = -1 OLYMPIC = 0 MAINNET = 1 EXPANSE_NETWORK = 2 ROPSTEN = 3 RINKEBY = 4 GOERLI = 5 ETHEREUM_CLASSIC_TESTNET_KOTTI = 6 THAICHAIN = 7 UBIQ = 8 UBIQ_NETWORK_TESTNET = 9 OPTIMISM = 10 METADIUM_MAINNET = 11 METADIUM_TESTNET = 12 DIODE_TESTNET_STAGING = 13 FLARE_MAINNET = 14 DIODE_PRENET = 15 FLARE_TESTNET_COSTON = 16 THAICHAIN_2_0_THAIFI = 17 THUNDERCORE_TESTNET = 18 SONGBIRD_CANARY_NETWORK = 19 ELASTOS_SMART_CHAIN = 20 ELASTOS_SMART_CHAIN_TESTNET = 21 ELA_DID_SIDECHAIN_MAINNET = 22 ELA_DID_SIDECHAIN_TESTNET = 23 KARDIACHAIN_MAINNET = 24 CRONOS_MAINNET_BETA = 25 GENESIS_L1_TESTNET = 26 SHIBACHAIN = 27 BOBA_NETWORK_RINKEBY_TESTNET = 28 GENESIS_L1 = 29 RSK_MAINNET = 30 RSK_TESTNET = 31 GOODDATA_TESTNET = 32 GOODDATA_MAINNET = 33 DITHEREUM_TESTNET = 34 TBWG_CHAIN = 35 DXCHAIN_MAINNET = 36 SEEDCOIN_NETWORK = 37 VALORBIT = 38 UNICORN_ULTRA_TESTNET = 39 TELOS_EVM_MAINNET = 40 TELOS_EVM_TESTNET = 41 KOVAN = 42 DARWINIA_PANGOLIN_TESTNET = 43 DARWINIA_CRAB_NETWORK = 44 DARWINIA_PANGORO_TESTNET = 45 DARWINIA_NETWORK = 46 ENNOTHEM_MAINNET_PROTEROZOIC = 48 ENNOTHEM_TESTNET_PIONEER = 49 XINFIN_XDC_NETWORK = 50 XDC_APOTHEM_NETWORK = 51 COINEX_SMART_CHAIN_MAINNET = 52 COINEX_SMART_CHAIN_TESTNET = 53 OPENPIECE_MAINNET = 54 ZYX_MAINNET = 55 BINANCE_SMART_CHAIN_MAINNET = 56 SYSCOIN_MAINNET = 57 ONTOLOGY_MAINNET = 58 EOS_MAINNET = 59 GOCHAIN = 60 ETHEREUM_CLASSIC_MAINNET = 61 ETHEREUM_CLASSIC_TESTNET_MORDEN = 62 ETHEREUM_CLASSIC_TESTNET_MORDOR = 63 ELLAISM = 64 OKEXCHAIN_TESTNET = 65 OKXCHAIN_MAINNET = 66 DBCHAIN_TESTNET = 67 SOTERONE_MAINNET = 68 OPTIMISM_KOVAN = 69 HOO_SMART_CHAIN = 70 CONFLUX_ESPACE_TESTNET = 71 DXCHAIN_TESTNET = 72 FNCY = 73 IDCHAIN_MAINNET = 74 DECIMAL_SMART_CHAIN_MAINNET = 75 MIX = 76 POA_NETWORK_SOKOL = 77 PRIMUSCHAIN_MAINNET = 78 ZENITH_MAINNET = 79 GENECHAIN = 80 ZENITH_TESTNET_VILNIUS = 81 METER_MAINNET = 82 METER_TESTNET = 83 GATECHAIN_TESTNET = 85 GATECHAIN_MAINNET = 86 NOVA_NETWORK = 87 TOMOCHAIN = 88 TOMOCHAIN_TESTNET = 89 GARIZON_STAGE0 = 90 GARIZON_STAGE1 = 91 GARIZON_STAGE2 = 92 GARIZON_STAGE3 = 93 CRYPTOKYLIN_TESTNET = 95 NEXT_SMART_CHAIN = 96 BINANCE_SMART_CHAIN_TESTNET = 97 POA_NETWORK_CORE = 99 GNOSIS = 100 ETHERINC = 101 WEB3GAMES_TESTNET = 102 KAIBA_LIGHTNING_CHAIN_TESTNET = 104 WEB3GAMES_DEVNET = 105 VELAS_EVM_MAINNET = 106 NEBULA_TESTNET = 107 THUNDERCORE_MAINNET = 108 PROTON_TESTNET = 110 ETHERLITE_CHAIN = 111 DEHVO = 113 FLARE_TESTNET_COSTON2 = 114 DEBANK_TESTNET = 115 DEBANK_MAINNET = 116 FUSE_MAINNET = 122 FUSE_SPARKNET = 123 DECENTRALIZED_WEB_MAINNET = 124 OYCHAIN_TESTNET = 125 OYCHAIN_MAINNET = 126 FACTORY_127_MAINNET = 127 HUOBI_ECO_CHAIN_MAINNET = 128 ALYX_CHAIN_TESTNET = 135 POLYGON = 137 OPENPIECE_TESTNET = 141 DAX_CHAIN = 142 PHI_NETWORK_V2 = 144 ARMONIA_EVA_CHAIN_MAINNET = 160 ARMONIA_EVA_CHAIN_TESTNET = 161 LIGHTSTREAMS_TESTNET = 162 LIGHTSTREAMS_MAINNET = 163 AIOZ_NETWORK = 168 HOO_SMART_CHAIN_TESTNET = 170 LATAM_BLOCKCHAIN_RESIL_TESTNET = 172 AME_CHAIN_MAINNET = 180 SEELE_MAINNET = 186 BMC_MAINNET = 188 BMC_TESTNET = 189 CRYPTO_EMERGENCY = 193 BITTORRENT_CHAIN_MAINNET = 199 ARBITRUM_ON_XDAI = 200 MOAC_TESTNET = 201 FREIGHT_TRUST_NETWORK = 211 MAP_MAKALU = 212 SIRIUSNET_V2 = 217 SOTERONE_MAINNET_OLD = 218 PERMISSION = 222 LACHAIN_MAINNET = 225 LACHAIN_TESTNET = 226 ENERGY_WEB_CHAIN = 246 OASYS_MAINNET = 248 FANTOM_OPERA = 250 HUOBI_ECO_CHAIN_TESTNET = 256 SETHEUM = 258 SUR_BLOCKCHAIN_NETWORK = 262 HIGH_PERFORMANCE_BLOCKCHAIN = 269 ZKSYNC_ALPHA_TESTNET = 280 BOBA_NETWORK = 288 OPTIMISM_ON_GNOSIS = 300 BOBAOPERA = 301 OMAX_MAINNET = 311 FILECOIN_MAINNET = 314 KCC_MAINNET = 321 KCC_TESTNET = 322 ZKSYNC_V2 = 324 WEB3Q_MAINNET = 333 DFK_CHAIN_TEST = 335 SHIDEN = 336 CRONOS_TESTNET = 338 THETA_MAINNET = 361 THETA_SAPPHIRE_TESTNET = 363 THETA_AMBER_TESTNET = 364 THETA_TESTNET = 365 PULSECHAIN_MAINNET = 369 LISINSKI = 385 HYPERONCHAIN_TESTNET = 400 SX_NETWORK_MAINNET = 416 OPTIMISM_GOERLI_TESTNET = 420 ZEETH_CHAIN = 427 RUPAYA = 499 CAMINO_C_CHAIN = 500 COLUMBUS_TEST_NETWORK = 501 DOUBLE_A_CHAIN_MAINNET = 512 DOUBLE_A_CHAIN_TESTNET = 513 GEAR_ZERO_NETWORK_MAINNET = 516 XT_SMART_CHAIN_MAINNET = 520 FIRECHAIN_MAINNET = 529 F_XCORE_MAINNET_NETWORK = 530 CANDLE = 534 VELA1_CHAIN_MAINNET = 555 TAO_NETWORK = 558 DOGECHAIN_TESTNET = 568 METIS_STARDUST_TESTNET = 588 ASTAR = 592 ACALA_MANDALA_TESTNET = 595 KARURA_NETWORK_TESTNET = 596 ACALA_NETWORK_TESTNET = 597 METIS_GOERLI_TESTNET = 599 MESHNYAN_TESTNET = 600 SX_NETWORK_TESTNET = 647 PIXIE_CHAIN_TESTNET = 666 KARURA_NETWORK = 686 STAR_SOCIAL_TESTNET = 700 BLOCKCHAIN_STATION_MAINNET = 707 BLOCKCHAIN_STATION_TESTNET = 708 LYCAN_CHAIN = 721 VENTION_SMART_CHAIN_TESTNET = 741 QL1 = 766 OPENCHAIN_TESTNET = 776 CHEAPETH = 777 ACALA_NETWORK = 787 AEROCHAIN_TESTNET = 788 LUCID_BLOCKCHAIN = 800 HAIC = 803 PORTAL_FANTASY_CHAIN_TEST = 808 QITMEER = 813 CALLISTO_MAINNET = 820 CALLISTO_TESTNET_DEPRECATED = 821 TARAXA_MAINNET = 841 TARAXA_TESTNET = 842 ZEETH_CHAIN_DEV = 859 FANTASIA_CHAIN_MAINNET = 868 DEXIT_NETWORK = 877 AMBROS_CHAIN_MAINNET = 880 WANCHAIN = 888 GARIZON_TESTNET_STAGE0 = 900 GARIZON_TESTNET_STAGE1 = 901 GARIZON_TESTNET_STAGE2 = 902 GARIZON_TESTNET_STAGE3 = 903 PORTAL_FANTASY_CHAIN = 909 RINIA_TESTNET = 917 PULSECHAIN_TESTNET = 940 PULSECHAIN_TESTNET_V2B = 941 PULSECHAIN_TESTNET_V3 = 942 MUNODE_TESTNET = 956 OORT_MAINNET = 970 OORT_HUYGENS = 971 OORT_ASCRAEUS = 972 NEPAL_BLOCKCHAIN_NETWORK = 977 TOP_MAINNET_EVM = 980 MEMO_SMART_CHAIN_MAINNET = 985 TOP_MAINNET = 989 LUCKY_NETWORK = 998 WANCHAIN_TESTNET = 999 GTON_MAINNET = 1000 KLAYTN_TESTNET_BAOBAB = 1001 T_EKTA = 1004 NEWTON_TESTNET = 1007 EURUS_MAINNET = 1008 EVRICE_NETWORK = 1010 NEWTON = 1012 SAKURA = 1022 CLOVER_TESTNET = 1023 CLV_PARACHAIN = 1024 BITTORRENT_CHAIN_TESTNET = 1028 CONFLUX_ESPACE = 1030 PROXY_NETWORK_TESTNET = 1031 BRONOS_TESTNET = 1038 BRONOS_MAINNET = 1039 METIS_ANDROMEDA_MAINNET = 1088 MOAC_MAINNET = 1099 POLYGON_ZKEVM = 1101 WEMIX3_0_MAINNET = 1111 WEMIX3_0_TESTNET = 1112 CORE_BLOCKCHAIN_MAINNET = 1116 DEFICHAIN_EVM_NETWORK_MAINNET = 1130 DEFICHAIN_EVM_NETWORK_TESTNET = 1131 MATHCHAIN = 1139 MATHCHAIN_TESTNET = 1140 SMART_HOST_TEKNOLOJI_TESTNET = 1177 IORA_CHAIN = 1197 EVANESCO_TESTNET = 1201 WORLD_TRADE_TECHNICAL_CHAIN_MAINNET = 1202 POPCATEUM_MAINNET = 1213 ENTERCHAIN_MAINNET = 1214 EXZO_NETWORK_MAINNET = 1229 ULTRON_TESTNET = 1230 ULTRON_MAINNET = 1231 STEP_NETWORK = 1234 OM_PLATFORM_MAINNET = 1246 CIC_CHAIN_TESTNET = 1252 HALO_MAINNET = 1280 MOONBEAM = 1284 MOONRIVER = 1285 MOONROCK_OLD = 1286 MOONBASE_ALPHA = 1287 MOONROCK = 1288 BOBABEAM = 1294 BOBABASE_TESTNET = 1297 DOS_FUJI_SUBNET = 1311 ALYX_MAINNET = 1314 AITD_MAINNET = 1319 AITD_TESTNET = 1320 GANACHE = 1337 CIC_CHAIN_MAINNET = 1353 POLYGON_ZKEVM_TESTNET = 1402 CTEX_SCAN_BLOCKCHAIN = 1455 SHERPAX_MAINNET = 1506 SHERPAX_TESTNET = 1507 BEAGLE_MESSAGING_CHAIN = 1515 CATECOIN_CHAIN_MAINNET = 1618 ATHEIOS = 1620 BTACHAIN = 1657 LUDAN_MAINNET = 1688 ANYTYPE_EVM_CHAIN = 1701 TBSI_MAINNET = 1707 TBSI_TESTNET = 1708 KERLEANO = 1804 RABBIT_ANALOG_TESTNET_CHAIN = 1807 CUBE_CHAIN_MAINNET = 1818 CUBE_CHAIN_TESTNET = 1819 TESLAFUNDS = 1856 GITSHOCK_CARTENZ_TESTNET = 1881 BON_NETWORK = 1898 ONUS_CHAIN_TESTNET = 1945 D_CHAIN_MAINNET = 1951 ATELIER = 1971 ONUS_CHAIN_MAINNET = 1975 EURUS_TESTNET = 1984 ETHERGEM = 1987 EKTA = 1994 EDEXA_TESTNET = 1995 DOGECHAIN_MAINNET = 2000 MILKOMEDA_C1_MAINNET = 2001 MILKOMEDA_A1_MAINNET = 2002 CLOUDWALK_TESTNET = 2008 CLOUDWALK_MAINNET = 2009 MAINNETZ_MAINNET = 2016 PUBLICMINT_DEVNET = 2018 PUBLICMINT_TESTNET = 2019 PUBLICMINT_MAINNET = 2020 EDGEWARE_MAINNET = 2021 BERESHEET_TESTNET = 2022 TAYCAN_TESTNET = 2023 RANGERS_PROTOCOL_MAINNET = 2025 ORIGINTRAIL_PARACHAIN = 2043 QUOKKACOIN_MAINNET = 2077 ECOBALL_MAINNET = 2100 ECOBALL_TESTNET_ESPUMA = 2101 EXOSAMA_NETWORK = 2109 METAPLAYERONE_MAINNET = 2122 BOSAGORA_MAINNET = 2151 FINDORA_MAINNET = 2152 FINDORA_TESTNET = 2153 FINDORA_FORGE = 2154 BITCOIN_EVM = 2203 EVANESCO_MAINNET = 2213 KAVA_EVM_TESTNET = 2221 KAVA_EVM = 2222 VCHAIN_MAINNET = 2223 BOMB_CHAIN = 2300 ALTCOINCHAIN = 2330 BOMB_CHAIN_TESTNET = 2399 TCG_VERSE_MAINNET = 2400 XODEX = 2415 KORTHO_MAINNET = 2559 TECHPAY_MAINNET = 2569 POCRNET = 2606 REDLIGHT_CHAIN_MAINNET = 2611 EZCHAIN_C_CHAIN_MAINNET = 2612 EZCHAIN_C_CHAIN_TESTNET = 2613 BOBA_NETWORK_GOERLI_TESTNET = 2888 BITYUAN_MAINNET = 2999 CENNZNET_RATA = 3000 CENNZNET_NIKAU = 3001 ORLANDO_CHAIN = 3031 FILECOIN_HYPERSPACE_TESTNET = 3141 DEBOUNCE_SUBNET_TESTNET = 3306 ZCORE_TESTNET = 3331 WEB3Q_TESTNET = 3333 WEB3Q_GALILEO = 3334 PARIBU_NET_MAINNET = 3400 PARIBU_NET_TESTNET = 3500 JFIN_CHAIN = 3501 PANDOPROJECT_MAINNET = 3601 PANDOPROJECT_TESTNET = 3602 METACODECHAIN = 3666 BITTEX_MAINNET = 3690 EMPIRE_NETWORK = 3693 CROSSBELL = 3737 DRAC_NETWORK = 3912 DYNO_MAINNET = 3966 DYNO_TESTNET = 3967 YUANCHAIN_MAINNET = 3999 FANTOM_TESTNET = 4002 BOBAOPERA_TESTNET = 4051 AIOZ_NETWORK_TESTNET = 4102 PHI_NETWORK_V1 = 4181 BOBAFUJI_TESTNET = 4328 HTMLCOIN_MAINNET = 4444 IOTEX_NETWORK_MAINNET = 4689 IOTEX_NETWORK_TESTNET = 4690 VENIDIUM_TESTNET = 4918 VENIDIUM_MAINNET = 4919 MANTLE = 5000 MANTLE_TESTNET = 5001 TLCHAIN_NETWORK_MAINNET = 5177 ERASWAP_MAINNET = 5197 HUMANODE_MAINNET = 5234 FIRECHAIN_MAINNET_OLD = 5290 UZMI_NETWORK_MAINNET = 5315 NAHMII_MAINNET = 5551 NAHMII_TESTNET = 5553 CHAIN_VERSE_MAINNET = 5555 SYSCOIN_TANENBAUM_TESTNET = 5700 ONTOLOGY_TESTNET = 5851 WEGOCHAIN_RUBIDIUM_MAINNET = 5869 TRES_TESTNET = 6065 TRES_MAINNET = 6066 PIXIE_CHAIN_MAINNET = 6626 GOLD_SMART_CHAIN_MAINNET = 6789 TOMB_CHAIN_MAINNET = 6969 POLYSMARTCHAIN = 6999 ZETACHAIN_MAINNET = 7000 ZETACHAIN_ATHENS_TESTNET = 7001 ELLA_THE_HEART = 7027 PLANQ_MAINNET = 7070 SHYFT_MAINNET = 7341 CANTO = 7700 # RISE_OF_THE_WARBOTS_TESTNET = 7777 HAZLOR_TESTNET = 7878 TELEPORT = 8000 TELEPORT_TESTNET = 8001 MDGL_TESTNET = 8029 SHARDEUM_LIBERTY_1_X = 8080 SHARDEUM_LIBERTY_2_X = 8081 STREAMUX_BLOCKCHAIN = 8098 QITMEER_NETWORK_TESTNET = 8131 BEONE_CHAIN_TESTNET = 8181 KLAYTN_MAINNET_CYPRESS = 8217 BLOCKTON_BLOCKCHAIN = 8272 KORTHOTEST = 8285 TOKI_NETWORK = 8654 TOKI_TESTNET = 8655 TOOL_GLOBAL_MAINNET = 8723 TOOL_GLOBAL_TESTNET = 8724 ALPH_NETWORK = 8738 TMY_CHAIN = 8768 UNIQUE = 8880 QUARTZ_BY_UNIQUE = 8881 OPAL_TESTNET_BY_UNIQUE = 8882 SAPPHIRE_BY_UNIQUE = 8883 XANACHAIN = 8888 VYVO_SMART_CHAIN = 8889 MAMMOTH_MAINNET = 8898 JIBCHAIN_L1 = 8899 GIANT_MAMMOTH_MAINNET = 8989 BLOXBERG = 8995 EVMOS_TESTNET = 9000 EVMOS = 9001 BERYLBIT_MAINNET = 9012 GENESIS_COIN = 9100 RINIA_TESTNET_OLD = 9170 RANGERS_PROTOCOL_TESTNET_ROBIN = 9527 QEASYWEB3_TESTNET = 9528 OORT_MAINNETDEV = 9700 BOBA_BNB_TESTNET = 9728 MAINNETZ_TESTNET = 9768 MYOWN_TESTNET = 9999 SMART_BITCOIN_CASH = 10000 SMART_BITCOIN_CASH_TESTNET = 10001 GON_CHAIN = 10024 SJATSH = 10086 BLOCKCHAIN_GENESIS_MAINNET = 10101 CHIADO_TESTNET = 10200 _0XTADE = 10248 NUMBERS_MAINNET = 10507 NUMBERS_TESTNET = 10508 CRYPTOCOINPAY = 10823 QUADRANS_BLOCKCHAIN = 10946 QUADRANS_BLOCKCHAIN_TESTNET = 10947 ASTRA = 11110 WAGMI = 11111 ASTRA_TESTNET = 11115 HAQQ_NETWORK = 11235 SHYFT_TESTNET = 11437 SARDIS_TESTNET = 11612 SANR_CHAIN = 11888 SINGULARITY_ZERO_TESTNET = 12051 SINGULARITY_ZERO_MAINNET = 12052 STEP_TESTNET = 12345 SPS = 13000 CREDIT_SMARTCHAIN_MAINNET = 13308 PHOENIX_MAINNET = 13381 SUSONO = 13812 SPS_TESTNET = 14000 TRUST_EVM_TESTNET = 15555 METADOT_MAINNET = 16000 METADOT_TESTNET = 16001 IVAR_CHAIN_TESTNET = 16888 FRONTIER_OF_DREAMS_TESTNET = 18000 PROOF_OF_MEMES = 18159 HOME_VERSE_MAINNET = 19011 BTCIX_NETWORK = 19845 CALLISTO_TESTNET = 20729 P12_CHAIN = 20736 CENNZNET_AZALEA = 21337 OMCHAIN_MAINNET = 21816 TAYCAN = 22023 MAP_MAINNET = 22776 OPSIDE_TESTNET = 23118 OASIS_SAPPHIRE = 23294 OASIS_SAPPHIRE_TESTNET = 23295 WEBCHAIN = 24484 MINTME_COM_COIN = 24734 HAMMER_CHAIN_MAINNET = 25888 BITKUB_CHAIN_TESTNET = 25925 HERTZ_NETWORK_MAINNET = 26600 OASISCHAIN_MAINNET = 26863 OPTIMISM_BEDROCK_GOERLI_ALPHA_TESTNET = 28528 PIECE_TESTNET = 30067 ETHERSOCIAL_NETWORK = 31102 CLOUDTX_MAINNET = 31223 CLOUDTX_TESTNET = 31224 GOCHAIN_TESTNET = 31337 FILECOIN_WALLABY_TESTNET = 31415 BITGERT_MAINNET = 32520 FUSION_MAINNET = 32659 AVES_MAINNET = 33333 J2O_TARO = 35011 Q_MAINNET = 35441 Q_TESTNET = 35443 ENERGI_MAINNET = 39797 OHO_MAINNET = 39815 OPULENT_X_BETA = 41500 PEGGLECOIN = 42069 ARBITRUM_ONE = 42161 ARBITRUM_NOVA = 42170 CELO_MAINNET = 42220 OASIS_EMERALD_TESTNET = 42261 OASIS_EMERALD = 42262 ATHEREUM = 43110 AVALANCHE_FUJI_TESTNET = 43113 AVALANCHE_C_CHAIN = 43114 BOBA_AVAX = 43288 CELO_ALFAJORES_TESTNET = 44787 AUTOBAHN_NETWORK = 45000 FUSION_TESTNET = 46688 REI_NETWORK = 47805 FLORIPA = 49049 BIFROST_TESTNET1 = 49088 ENERGI_TESTNET = 49797 LIVEPLEX_ORACLEEVM = 50001 GTON_TESTNET = 50021 SARDIS_MAINNET = 51712 DFK_CHAIN = 53935 HAQQ_CHAIN_TESTNET = 54211 REI_CHAIN_MAINNET = 55555 REI_CHAIN_TESTNET = 55556 BOBA_BNB_MAINNET = 56288 THINKIUM_TESTNET_CHAIN_0 = 60000 THINKIUM_TESTNET_CHAIN_1 = 60001 THINKIUM_TESTNET_CHAIN_2 = 60002 THINKIUM_TESTNET_CHAIN_103 = 60103 ETICA_MAINNET = 61803 DOKEN_SUPER_CHAIN_MAINNET = 61916 CELO_BAKLAVA_TESTNET = 62320 MULTIVAC_MAINNET = 62621 ECREDITS_MAINNET = 63000 ECREDITS_TESTNET = 63001 SIRIUSNET = 67390 CONDRIEU = 69420 THINKIUM_MAINNET_CHAIN_0 = 70000 THINKIUM_MAINNET_CHAIN_1 = 70001 THINKIUM_MAINNET_CHAIN_2 = 70002 THINKIUM_MAINNET_CHAIN_103 = 70103 POLYJUICE_TESTNET = 71393 GODWOKEN_TESTNET_V1 = 71401 GODWOKEN_MAINNET = 71402 ENERGY_WEB_VOLTA_TESTNET = 73799 MIXIN_VIRTUAL_MACHINE = 73927 RESINCOIN_MAINNET = 75000 VENTION_SMART_CHAIN_MAINNET = 77612 FIRENZE_TEST_NETWORK = 78110 GOLD_SMART_CHAIN_TESTNET = 79879 MUMBAI = 80001 BASE_GOERLI_TESTNET = 84531 IVAR_CHAIN_MAINNET = 88888 BEVERLY_HILLS = 90210 LAMBDA_TESTNET = 92001 BOBA_BNB_MAINNET_OLD = 97288 UB_SMART_CHAIN_TESTNET = 99998 UB_SMART_CHAIN = 99999 QUARKCHAIN_MAINNET_ROOT = 100000 QUARKCHAIN_MAINNET_SHARD_0 = 100001 QUARKCHAIN_MAINNET_SHARD_1 = 100002 QUARKCHAIN_MAINNET_SHARD_2 = 100003 QUARKCHAIN_MAINNET_SHARD_3 = 100004 QUARKCHAIN_MAINNET_SHARD_4 = 100005 QUARKCHAIN_MAINNET_SHARD_5 = 100006 QUARKCHAIN_MAINNET_SHARD_6 = 100007 QUARKCHAIN_MAINNET_SHARD_7 = 100008 DEPRECATED_CHIADO_TESTNET = 100100 SOVERUN_TESTNET = 101010 CRYSTALEUM = 103090 BROCHAIN_MAINNET = 108801 QUARKCHAIN_DEVNET_ROOT = 110000 QUARKCHAIN_DEVNET_SHARD_0 = 110001 QUARKCHAIN_DEVNET_SHARD_1 = 110002 QUARKCHAIN_DEVNET_SHARD_2 = 110003 QUARKCHAIN_DEVNET_SHARD_3 = 110004 QUARKCHAIN_DEVNET_SHARD_4 = 110005 QUARKCHAIN_DEVNET_SHARD_5 = 110006 QUARKCHAIN_DEVNET_SHARD_6 = 110007 QUARKCHAIN_DEVNET_SHARD_7 = 110008 ETND_CHAIN_MAINNETS = 131419 CONDOR_TEST_NETWORK = 188881 MILKOMEDA_C1_TESTNET = 200101 MILKOMEDA_A1_TESTNET = 200202 AKROMA = 200625 ALAYA_MAINNET = 201018 ALAYA_DEV_TESTNET = 201030 MYTHICAL_CHAIN = 201804 DECIMAL_SMART_CHAIN_TESTNET = 202020 JELLIE = 202624 PLATON_MAINNET = 210425 MAS_MAINNET = 220315 HAYMO_TESTNET = 234666 ARTIS_SIGMA1 = 246529 ARTIS_TESTNET_TAU1 = 246785 CMP_MAINNET = 256256 GEAR_ZERO_NETWORK_TESTNET = 266256 SOCIAL_SMART_CHAIN_MAINNET = 281121 FILECOIN_CALIBRATION_TESTNET = 314159 POLIS_TESTNET = 333888 POLIS_MAINNET = 333999 METAL_C_CHAIN = 381931 METAL_TAHOE_C_CHAIN = 381932 KEKCHAIN = 420420 KEKCHAIN_KEKTEST = 420666 ARBITRUM_RINKEBY = 421611 ARBITRUM_GOERLI = 421613 DEXALOT_SUBNET_TESTNET = 432201 DEXALOT_SUBNET = 432204 WEELINK_TESTNET = 444900 OPENCHAIN_MAINNET = 474142 CMP_TESTNET = 512512 ETHEREUM_FAIR = 513100 SCROLL = 534352 SCROLL_GOERLI_TESTNET = 534353 SCROLL_PRE_ALPHA_TESTNET = 534354 BEAR_NETWORK_CHAIN_MAINNET = 641230 VISION_VPIONEER_TEST_CHAIN = 666666 OCTASPACE = 800001 _4GOODNETWORK = 846000 VISION_MAINNET = 888888 POSICHAIN_MAINNET_SHARD_0 = 900000 POSICHAIN_TESTNET_SHARD_0 = 910000 POSICHAIN_DEVNET_SHARD_0 = 920000 POSICHAIN_DEVNET_SHARD_1 = 920001 FNCY_TESTNET = 923018 ELUVIO_CONTENT_FABRIC = 955305 ETHO_PROTOCOL = 1313114 XEROM = 1313500 KINTSUGI = 1337702 KILN = 1337802 ZHEJIANG = 1337803 PLIAN_MAINNET_MAIN = 2099156 PLATON_DEV_TESTNET_DEPRECATED = 2203181 PLATON_DEV_TESTNET2 = 2206132 FILECOIN_BUTTERFLY_TESTNET = 3141592 IMVERSED_MAINNET = 5555555 IMVERSED_TESTNET = 5555558 OPENVESSEL = 7355310 QL1_TESTNET = 7668378 MUSICOIN = 7762959 PLIAN_MAINNET_SUBCHAIN_1 = 8007736 PLIAN_TESTNET_SUBCHAIN_1 = 10067275 SOVERUN_MAINNET = 10101010 SEPOLIA = 11155111 PEPCHAIN_CHURCHILL = 13371337 ANDUSCHAIN_MAINNET = 14288640 PLIAN_TESTNET_MAIN = 16658437 IOLITE = 18289463 SMARTMESH_MAINNET = 20180430 QUARKBLOCKCHAIN = 20181205 EXCELON_MAINNET = 22052002 EXCOINCIAL_CHAIN_VOLTA_TESTNET = 27082017 EXCOINCIAL_CHAIN_MAINNET = 27082022 AUXILIUM_NETWORK_MAINNET = 28945486 FLACHAIN_MAINNET = 29032022 FILECOIN_LOCAL_TESTNET = 31415926 JOYS_DIGITAL_MAINNET = 35855456 MAISTESTSUBNET = 43214913 AQUACHAIN = 61717561 JOYS_DIGITAL_TESTNET = 99415706 GATHER_MAINNET_NETWORK = 192837465 NEON_EVM_DEVNET = 245022926 NEON_EVM_MAINNET = 245022934 NEON_EVM_TESTNET = 245022940 ONELEDGER_MAINNET = 311752642 CALYPSO_NFT_HUB_SKALE_TESTNET = 344106930 GATHER_TESTNET_NETWORK = 356256156 GATHER_DEVNET_NETWORK = 486217935 NEBULA_STAGING = 503129905 IPOS_NETWORK = 1122334455 AURORA_MAINNET = 1313161554 AURORA_TESTNET = 1313161555 AURORA_BETANET = 1313161556 NEBULA_MAINNET = 1482601649 CALYPSO_NFT_HUB_SKALE = 1564830818 HARMONY_MAINNET_SHARD_0 = 1666600000 HARMONY_MAINNET_SHARD_1 = 1666600001 HARMONY_MAINNET_SHARD_2 = 1666600002 HARMONY_MAINNET_SHARD_3 = 1666600003 HARMONY_TESTNET_SHARD_0 = 1666700000 HARMONY_TESTNET_SHARD_1 = 1666700001 HARMONY_TESTNET_SHARD_2 = 1666700002 HARMONY_TESTNET_SHARD_3 = 1666700003 HARMONY_DEVNET_SHARD_0 = 1666900000 DATAHOPPER = 2021121117 EUROPA_SKALE_CHAIN = 2046399126 PIRL = 3125659152 ONELEDGER_TESTNET_FRANKENSTEIN = 4216137055 PALM_TESTNET = 11297108099 PALM = 11297108109 NTITY_MAINNET = 197710212030 HARADEV_TESTNET = 197710212031 ZENIQ = 383414847825 PDC_MAINNET = 666301171999 MOLEREUM_NETWORK = 6022140761023 TKX_MAINNET = 7777 TKX_ALPHA = 17778 TKX_BANGSUE = 17777 @classmethod def _missing_(cls, value): return cls.UNKNOWN
/safe_eth_py_suraneti-5.4.3-py3-none-any.whl/gnosis/eth/ethereum_network.py
0.403097
0.374733
ethereum_network.py
pypi
import warnings from secrets import token_bytes from typing import Tuple, Union import eth_abi from eth._utils.address import generate_contract_address from eth_keys import keys from eth_typing import AnyAddress, ChecksumAddress, HexStr from eth_utils import to_normalized_address from hexbytes import HexBytes from sha3 import keccak_256 def fast_keccak(value: bytes) -> bytes: """ Calculates ethereum keccak256 using fast library `pysha3` :param value: :return: Keccak256 used by ethereum as `bytes` """ return keccak_256(value).digest() def fast_keccak_hex(value: bytes) -> HexStr: """ Same as `fast_keccak`, but it's a little more optimal calling `hexdigest()` than calling `digest()` and then `hex()` :param value: :return: Keccak256 used by ethereum as an hex string (not 0x prefixed) """ return HexStr(keccak_256(value).hexdigest()) def _build_checksum_address( norm_address: HexStr, address_hash: HexStr ) -> ChecksumAddress: """ https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md :param norm_address: address in lowercase (not 0x prefixed) :param address_hash: keccak256 of `norm_address` (not 0x prefixed) :return: """ return ChecksumAddress( "0x" + ( "".join( ( norm_address[i].upper() if int(address_hash[i], 16) > 7 else norm_address[i] ) for i in range(0, 40) ) ) ) def fast_to_checksum_address(value: Union[AnyAddress, str, bytes]) -> ChecksumAddress: """ Converts to checksum_address. Uses more optimal `pysha3` instead of `eth_utils` for keccak256 calculation :param value: :return: """ norm_address = to_normalized_address(value)[2:] address_hash = fast_keccak_hex(norm_address.encode()) return _build_checksum_address(norm_address, address_hash) def fast_bytes_to_checksum_address(value: bytes) -> ChecksumAddress: """ Converts to checksum_address. Uses more optimal `pysha3` instead of `eth_utils` for keccak256 calculation. As input is already in bytes, some checks and conversions can be skipped, providing a speedup of ~50% :param value: :return: """ if len(value) != 20: raise ValueError( "Cannot convert %s to a checksum address, 20 bytes were expected" ) norm_address = bytes(value).hex() address_hash = fast_keccak_hex(norm_address.encode()) return _build_checksum_address(norm_address, address_hash) def fast_is_checksum_address(value: Union[AnyAddress, str, bytes]) -> bool: """ Fast version to check if an address is a checksum_address :param value: :return: `True` if checksummed, `False` otherwise """ if not isinstance(value, str) or len(value) != 42 or not value.startswith("0x"): return False try: return fast_to_checksum_address(value) == value except ValueError: return False def get_eth_address_with_key() -> Tuple[str, bytes]: private_key = keys.PrivateKey(token_bytes(32)) address = private_key.public_key.to_checksum_address() return address, private_key.to_bytes() def get_eth_address_with_invalid_checksum() -> str: address, _ = get_eth_address_with_key() return "0x" + "".join( [c.lower() if c.isupper() else c.upper() for c in address[2:]] ) def decode_string_or_bytes32(data: bytes) -> str: try: return eth_abi.decode(["string"], data)[0] except OverflowError: name = eth_abi.decode(["bytes32"], data)[0] end_position = name.find(b"\x00") if end_position == -1: return name.decode() else: return name[:end_position].decode() def remove_swarm_metadata(code: bytes) -> bytes: """ Remove swarm metadata from Solidity bytecode :param code: :return: Code without metadata """ swarm = b"\xa1\x65bzzr0" position = code.rfind(swarm) if position == -1: raise ValueError("Swarm metadata not found in code %s" % code.hex()) return code[:position] def compare_byte_code(code_1: bytes, code_2: bytes) -> bool: """ Compare code, removing swarm metadata if necessary :param code_1: :param code_2: :return: True if same code, False otherwise """ if code_1 == code_2: return True else: codes = [] for code in (code_1, code_2): try: codes.append(remove_swarm_metadata(code)) except ValueError: codes.append(code) return codes[0] == codes[1] def mk_contract_address(address: Union[str, bytes], nonce: int) -> ChecksumAddress: """ Generate expected contract address when using EVM CREATE :param address: :param nonce: :return: """ return fast_to_checksum_address(generate_contract_address(HexBytes(address), nonce)) def mk_contract_address_2( from_: Union[str, bytes], salt: Union[str, bytes], init_code: Union[str, bytes] ) -> ChecksumAddress: """ Generate expected contract address when using EVM CREATE2. :param from_: The address which is creating this new address (need to be 20 bytes) :param salt: A salt (32 bytes) :param init_code: A init code of the contract being created :return: Address of the new contract """ from_ = HexBytes(from_) salt = HexBytes(salt) init_code = HexBytes(init_code) assert len(from_) == 20, f"Address {from_.hex()} is not valid. Must be 20 bytes" assert len(salt) == 32, f"Salt {salt.hex()} is not valid. Must be 32 bytes" assert len(init_code) > 0, f"Init code {init_code.hex()} is not valid" init_code_hash = fast_keccak(init_code) contract_address = fast_keccak(HexBytes("ff") + from_ + salt + init_code_hash) return fast_bytes_to_checksum_address(contract_address[12:]) def generate_address_2( from_: Union[str, bytes], salt: Union[str, bytes], init_code: Union[str, bytes] ) -> ChecksumAddress: """ .. deprecated:: use mk_contract_address_2 :param from_: :param salt: :param init_code: :return: """ warnings.warn( "`generate_address_2` is deprecated, use `mk_contract_address_2`", DeprecationWarning, ) return mk_contract_address_2(from_, salt, init_code)
/safe_eth_py_suraneti-5.4.3-py3-none-any.whl/gnosis/eth/utils.py
0.907281
0.559892
utils.py
pypi
import logging from dataclasses import dataclass from typing import Any, List, Optional, Sequence, Tuple import eth_abi from eth_abi.exceptions import DecodingError from eth_account.signers.local import LocalAccount from eth_typing import BlockIdentifier, BlockNumber, ChecksumAddress from hexbytes import HexBytes from web3 import Web3 from web3._utils.abi import map_abi_data from web3._utils.normalizers import BASE_RETURN_NORMALIZERS from web3.contract.contract import ContractFunction from web3.exceptions import ContractLogicError from . import EthereumClient, EthereumNetwork, EthereumNetworkNotSupported from .abis.multicall import multicall_v3_abi, multicall_v3_bytecode from .ethereum_client import EthereumTxSent from .exceptions import BatchCallFunctionFailed logger = logging.getLogger(__name__) @dataclass class MulticallResult: success: bool return_data: Optional[bytes] @dataclass class MulticallDecodedResult: success: bool return_data_decoded: Optional[Any] class Multicall: # https://github.com/mds1/multicall#deployments ADDRESSES = { EthereumNetwork.MAINNET: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.GOERLI: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.SEPOLIA: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.OPTIMISM: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.OPTIMISM_GOERLI_TESTNET: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.ARBITRUM_ONE: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.ARBITRUM_NOVA: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.ARBITRUM_GOERLI: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.POLYGON: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.MUMBAI: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.POLYGON_ZKEVM: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.POLYGON_ZKEVM_TESTNET: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.GNOSIS: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.AVALANCHE_C_CHAIN: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.AVALANCHE_FUJI_TESTNET: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.FANTOM_TESTNET: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.FANTOM_OPERA: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.BINANCE_SMART_CHAIN_MAINNET: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.BINANCE_SMART_CHAIN_TESTNET: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.KOVAN: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.RINKEBY: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.KCC_MAINNET: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.KCC_TESTNET: "0x665683D9bd41C09cF38c3956c926D9924F1ADa97", EthereumNetwork.ROPSTEN: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.CELO_MAINNET: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.CELO_ALFAJORES_TESTNET: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.AURORA_MAINNET: "0xcA11bde05977b3631167028862bE2a173976CA11", EthereumNetwork.BASE_GOERLI_TESTNET: "0xcA11bde05977b3631167028862bE2a173976CA11", } def __init__( self, ethereum_client: EthereumClient, multicall_contract_address: Optional[ChecksumAddress] = None, ): self.ethereum_client = ethereum_client self.w3 = ethereum_client.w3 ethereum_network = ethereum_client.get_network() address = multicall_contract_address or self.ADDRESSES.get(ethereum_network) if not address: # Try with Multicall V3 deterministic address address = self.ADDRESSES.get(EthereumNetwork.MAINNET) if not ethereum_client.is_contract(address): raise EthereumNetworkNotSupported( "Multicall contract not available for %s", ethereum_network.name ) self.contract = self.get_contract(self.w3, address) def get_contract(self, w3: Web3, address: Optional[ChecksumAddress] = None): return w3.eth.contract( address, abi=multicall_v3_abi, bytecode=multicall_v3_bytecode ) @classmethod def deploy_contract( cls, ethereum_client: EthereumClient, deployer_account: LocalAccount ) -> EthereumTxSent: """ Deploy contract :param ethereum_client: :param deployer_account: Ethereum Account :return: deployed contract address """ contract = cls.get_contract(cls, ethereum_client.w3) tx = contract.constructor().build_transaction( {"from": deployer_account.address} ) tx_hash = ethereum_client.send_unsigned_transaction( tx, private_key=deployer_account.key ) tx_receipt = ethereum_client.get_transaction_receipt(tx_hash, timeout=120) assert tx_receipt and tx_receipt["status"] contract_address = tx_receipt["contractAddress"] logger.info( "Deployed Multicall V2 Contract %s by %s", contract_address, deployer_account.address, ) # Add address to addresses dictionary cls.ADDRESSES[ethereum_client.get_network()] = contract_address return EthereumTxSent(tx_hash, tx, contract_address) @staticmethod def _build_payload( contract_functions: Sequence[ContractFunction], ) -> Tuple[List[Tuple[ChecksumAddress, bytes]], List[List[Any]]]: targets_with_data = [] output_types = [] for contract_function in contract_functions: targets_with_data.append( ( contract_function.address, HexBytes(contract_function._encode_transaction_data()), ) ) output_types.append( [output["type"] for output in contract_function.abi["outputs"]] ) return targets_with_data, output_types def _build_payload_same_function( self, contract_function: ContractFunction, contract_addresses: Sequence[ChecksumAddress], ) -> Tuple[List[Tuple[ChecksumAddress, bytes]], List[List[Any]]]: targets_with_data = [] output_types = [] tx_data = HexBytes(contract_function._encode_transaction_data()) for contract_address in contract_addresses: targets_with_data.append((contract_address, tx_data)) output_types.append( [output["type"] for output in contract_function.abi["outputs"]] ) return targets_with_data, output_types def _decode_data(self, output_type: Sequence[str], data: bytes) -> Optional[Any]: """ :param output_type: :param data: :return: :raises: DecodingError """ if data: try: decoded_values = eth_abi.decode(output_type, data) normalized_data = map_abi_data( BASE_RETURN_NORMALIZERS, output_type, decoded_values ) if len(normalized_data) == 1: return normalized_data[0] else: return normalized_data except DecodingError: logger.warning( "Cannot decode %s using output-type %s", data, output_type ) return data def _aggregate( self, targets_with_data: Sequence[Tuple[ChecksumAddress, bytes]], block_identifier: Optional[BlockIdentifier] = "latest", ) -> Tuple[BlockNumber, List[Optional[Any]]]: """ :param targets_with_data: List of target `addresses` and `data` to be called in each Contract :param block_identifier: :return: :raises: BatchCallFunctionFailed """ aggregate_parameter = [ {"target": target, "callData": data} for target, data in targets_with_data ] try: return self.contract.functions.aggregate(aggregate_parameter).call( block_identifier=block_identifier ) except (ContractLogicError, OverflowError): raise BatchCallFunctionFailed def aggregate( self, contract_functions: Sequence[ContractFunction], block_identifier: Optional[BlockIdentifier] = "latest", ) -> Tuple[BlockNumber, List[Optional[Any]]]: """ Calls ``aggregate`` on MakerDAO's Multicall contract. If a function called raises an error execution is stopped :param contract_functions: :param block_identifier: :return: A tuple with the ``blockNumber`` and a list with the decoded return values :raises: BatchCallFunctionFailed """ targets_with_data, output_types = self._build_payload(contract_functions) block_number, results = self._aggregate( targets_with_data, block_identifier=block_identifier ) decoded_results = [ self._decode_data(output_type, data) for output_type, data in zip(output_types, results) ] return block_number, decoded_results def _try_aggregate( self, targets_with_data: Sequence[Tuple[ChecksumAddress, bytes]], require_success: bool = False, block_identifier: Optional[BlockIdentifier] = "latest", ) -> List[MulticallResult]: """ Calls ``try_aggregate`` on MakerDAO's Multicall contract. :param targets_with_data: :param require_success: If ``True``, an exception in any of the functions will stop the execution. Also, an invalid decoded value will stop the execution :param block_identifier: :return: A list with the decoded return values """ aggregate_parameter = [ {"target": target, "callData": data} for target, data in targets_with_data ] try: result = self.contract.functions.tryAggregate( require_success, aggregate_parameter ).call(block_identifier=block_identifier) if require_success and b"" in (data for _, data in result): # `b''` values are decoding errors/missing contracts/missing functions raise BatchCallFunctionFailed return [ MulticallResult(success, data if data else None) for success, data in result ] except (ContractLogicError, OverflowError, ValueError): raise BatchCallFunctionFailed def try_aggregate( self, contract_functions: Sequence[ContractFunction], require_success: bool = False, block_identifier: Optional[BlockIdentifier] = "latest", ) -> List[MulticallDecodedResult]: """ Calls ``try_aggregate`` on MakerDAO's Multicall contract. :param contract_functions: :param require_success: If ``True``, an exception in any of the functions will stop the execution :param block_identifier: :return: A list with the decoded return values """ targets_with_data, output_types = self._build_payload(contract_functions) results = self._try_aggregate( targets_with_data, require_success=require_success, block_identifier=block_identifier, ) return [ MulticallDecodedResult( multicall_result.success, self._decode_data(output_type, multicall_result.return_data) if multicall_result.success else multicall_result.return_data, ) for output_type, multicall_result in zip(output_types, results) ] def try_aggregate_same_function( self, contract_function: ContractFunction, contract_addresses: Sequence[ChecksumAddress], require_success: bool = False, block_identifier: Optional[BlockIdentifier] = "latest", ) -> List[MulticallDecodedResult]: """ Calls ``try_aggregate`` on MakerDAO's Multicall contract. Reuse same function with multiple contract addresses. It's more optimal due to instantiating ``ContractFunction`` objects is very demanding :param contract_function: :param contract_addresses: :param require_success: If ``True``, an exception in any of the functions will stop the execution :param block_identifier: :return: A list with the decoded return values """ targets_with_data, output_types = self._build_payload_same_function( contract_function, contract_addresses ) results = self._try_aggregate( targets_with_data, require_success=require_success, block_identifier=block_identifier, ) return [ MulticallDecodedResult( multicall_result.success, self._decode_data(output_type, multicall_result.return_data) if multicall_result.success else multicall_result.return_data, ) for output_type, multicall_result in zip(output_types, results) ]
/safe_eth_py_suraneti-5.4.3-py3-none-any.whl/gnosis/eth/multicall.py
0.855957
0.229978
multicall.py
pypi
import json import time from typing import Any, Dict, Optional from urllib.parse import urljoin import requests from .. import EthereumNetwork from .contract_metadata import ContractMetadata class EtherscanClientException(Exception): pass class EtherscanClientConfigurationProblem(Exception): pass class EtherscanRateLimitError(EtherscanClientException): pass class EtherscanClient: NETWORK_WITH_URL = { EthereumNetwork.MAINNET: "https://etherscan.io", EthereumNetwork.RINKEBY: "https://rinkeby.etherscan.io", EthereumNetwork.ROPSTEN: "https://ropsten.etherscan.io", EthereumNetwork.GOERLI: "https://goerli.etherscan.io", EthereumNetwork.KOVAN: "https://kovan.etherscan.io", EthereumNetwork.BINANCE_SMART_CHAIN_MAINNET: "https://bscscan.com", EthereumNetwork.POLYGON: "https://polygonscan.com", EthereumNetwork.POLYGON_ZKEVM: "https://zkevm.polygonscan.com", EthereumNetwork.OPTIMISM: "https://optimistic.etherscan.io", EthereumNetwork.ARBITRUM_ONE: "https://arbiscan.io", EthereumNetwork.ARBITRUM_NOVA: "https://nova.arbiscan.io", EthereumNetwork.ARBITRUM_GOERLI: "https://goerli.arbiscan.io", EthereumNetwork.AVALANCHE_C_CHAIN: "https://snowtrace.io", EthereumNetwork.MOONBEAM: "https://moonscan.io", EthereumNetwork.MOONRIVER: "https://moonriver.moonscan.io", EthereumNetwork.MOONBASE_ALPHA: "https://moonbase.moonscan.io", EthereumNetwork.CRONOS_MAINNET_BETA: "https://cronoscan.com", EthereumNetwork.CRONOS_TESTNET: "https://testnet.cronoscan.com", EthereumNetwork.CELO_MAINNET: "https://celoscan.io", EthereumNetwork.BASE_GOERLI_TESTNET: "https://goerli.basescan.org", EthereumNetwork.NEON_EVM_DEVNET: "https://neonscan.org", EthereumNetwork.SEPOLIA: "https://sepolia.etherscan.io", } NETWORK_WITH_API_URL = { EthereumNetwork.MAINNET: "https://api.etherscan.io", EthereumNetwork.RINKEBY: "https://api-rinkeby.etherscan.io", EthereumNetwork.ROPSTEN: "https://api-ropsten.etherscan.io", EthereumNetwork.GOERLI: "https://api-goerli.etherscan.io", EthereumNetwork.KOVAN: "https://api-kovan.etherscan.io", EthereumNetwork.BINANCE_SMART_CHAIN_MAINNET: "https://api.bscscan.com", EthereumNetwork.POLYGON: "https://api.polygonscan.com", EthereumNetwork.POLYGON_ZKEVM: "https://api-zkevm.polygonscan.com", EthereumNetwork.OPTIMISM: "https://api-optimistic.etherscan.io", EthereumNetwork.ARBITRUM_ONE: "https://api.arbiscan.io", EthereumNetwork.ARBITRUM_NOVA: "https://api-nova.arbiscan.io", EthereumNetwork.ARBITRUM_GOERLI: "https://api-goerli.arbiscan.io", EthereumNetwork.AVALANCHE_C_CHAIN: "https://api.snowtrace.io", EthereumNetwork.MOONBEAM: "https://api-moonbeam.moonscan.io", EthereumNetwork.MOONRIVER: "https://api-moonriver.moonscan.io", EthereumNetwork.MOONBASE_ALPHA: "https://api-moonbase.moonscan.io", EthereumNetwork.CRONOS_MAINNET_BETA: "https://api.cronoscan.com", EthereumNetwork.CRONOS_TESTNET: "https://api-testnet.cronoscan.com", EthereumNetwork.CELO_MAINNET: "https://api.celoscan.io", EthereumNetwork.BASE_GOERLI_TESTNET: "https://api-goerli.basescan.org", EthereumNetwork.NEON_EVM_DEVNET: "https://devnet-api.neonscan.org", EthereumNetwork.SEPOLIA: "https://api-sepolia.etherscan.io", } HTTP_HEADERS = { "User-Agent": "curl/7.77.0", } def __init__(self, network: EthereumNetwork, api_key: Optional[str] = None): self.network = network self.api_key = api_key self.base_url = self.NETWORK_WITH_URL.get(network) self.base_api_url = self.NETWORK_WITH_API_URL.get(network) if self.base_api_url is None: raise EtherscanClientConfigurationProblem( f"Network {network.name} - {network.value} not supported" ) self.http_session = requests.Session() self.http_session.headers = self.HTTP_HEADERS def build_url(self, path: str): url = urljoin(self.base_api_url, path) if self.api_key: url += f"&apikey={self.api_key}" return url def _do_request(self, url: str) -> Optional[Dict[str, Any]]: response = self.http_session.get(url) if response.ok: response_json = response.json() result = response_json["result"] if "Max rate limit reached" in result: # Max rate limit reached, please use API Key for higher rate limit raise EtherscanRateLimitError if response_json["status"] == "1": return result def _retry_request(self, url: str, retry: bool = True) -> Optional[Dict[str, Any]]: for _ in range(3): try: return self._do_request(url) except EtherscanRateLimitError as exc: if not retry: raise exc else: time.sleep(5) def get_contract_metadata( self, contract_address: str, retry: bool = True ) -> Optional[ContractMetadata]: contract_source_code = self.get_contract_source_code( contract_address, retry=retry ) if contract_source_code: contract_name = contract_source_code["ContractName"] contract_abi = contract_source_code["ABI"] if contract_abi: return ContractMetadata(contract_name, contract_abi, False) def get_contract_source_code(self, contract_address: str, retry: bool = True): """ Get source code for a contract. Source code query also returns: - ContractName: "", - CompilerVersion: "", - OptimizationUsed: "", - Runs: "", - ConstructorArguments: "" - EVMVersion: "Default", - Library: "", - LicenseType: "", - Proxy: "0", - Implementation: "", - SwarmSource: "" :param contract_address: :param retry: if ``True``, try again if there's Rate Limit Error :return: """ url = self.build_url( f"api?module=contract&action=getsourcecode&address={contract_address}" ) result = self._retry_request(url, retry=retry) # Returns a list if result: result = result[0] abi_str = result["ABI"] result["ABI"] = json.loads(abi_str) if abi_str.startswith("[") else None return result def get_contract_abi(self, contract_address: str, retry: bool = True): url = self.build_url( f"api?module=contract&action=getabi&address={contract_address}" ) result = self._retry_request(url, retry=retry) if result: return json.loads(result)
/safe_eth_py_suraneti-5.4.3-py3-none-any.whl/gnosis/eth/clients/etherscan_client.py
0.762159
0.364042
etherscan_client.py
pypi
from typing import Any, Dict, List, Optional from urllib.parse import urljoin import requests from .. import EthereumNetwork from ..utils import fast_is_checksum_address from .contract_metadata import ContractMetadata class Sourcify: """ Get contract metadata from Sourcify. Matches can be full or partial: - Full: Both the source files as well as the meta data files were an exact match between the deployed bytecode and the published files. - Partial: Source code compiles to the same bytecode and thus the contract behaves in the same way, but the source code can be different: Variables can have misleading names, comments can be different and especially the NatSpec comments could have been modified. """ def __init__( self, network: EthereumNetwork = EthereumNetwork.MAINNET, base_url: str = "https://repo.sourcify.dev/", ): self.network = network self.base_url = base_url self.http_session = requests.session() def _get_abi_from_metadata(self, metadata: Dict[str, Any]) -> List[Dict[str, Any]]: return metadata["output"]["abi"] def _get_name_from_metadata(self, metadata: Dict[str, Any]) -> Optional[str]: values = list(metadata["settings"].get("compilationTarget", {}).values()) if values: return values[0] def _do_request(self, url: str) -> Optional[Dict[str, Any]]: response = self.http_session.get(url, timeout=10) if not response.ok: return None return response.json() def get_contract_metadata( self, contract_address: str ) -> Optional[ContractMetadata]: assert fast_is_checksum_address( contract_address ), "Expecting a checksummed address" for match_type in ("full_match", "partial_match"): url = urljoin( self.base_url, f"/contracts/{match_type}/{self.network.value}/{contract_address}/metadata.json", ) metadata = self._do_request(url) if metadata: abi = self._get_abi_from_metadata(metadata) name = self._get_name_from_metadata(metadata) return ContractMetadata(name, abi, match_type == "partial_match") return None
/safe_eth_py_suraneti-5.4.3-py3-none-any.whl/gnosis/eth/clients/sourcify.py
0.899345
0.365966
sourcify.py
pypi
import json from typing import Any, Dict, Optional from urllib.parse import urljoin import requests from eth_typing import ChecksumAddress from .. import EthereumNetwork from .contract_metadata import ContractMetadata class BlockscoutClientException(Exception): pass class BlockScoutConfigurationProblem(BlockscoutClientException): pass class BlockscoutClient: NETWORK_WITH_URL = { EthereumNetwork.GNOSIS: "https://blockscout.com/poa/xdai/", EthereumNetwork.POLYGON: "https://polygon-explorer-mainnet.chainstacklabs.com/", EthereumNetwork.MUMBAI: "https://polygon-explorer-mumbai.chainstacklabs.com/", EthereumNetwork.ENERGY_WEB_CHAIN: "https://explorer.energyweb.org/", EthereumNetwork.ENERGY_WEB_VOLTA_TESTNET: "https://volta-explorer.energyweb.org/", EthereumNetwork.POLIS_MAINNET: "https://explorer.polis.tech", EthereumNetwork.BOBABEAM: "https://blockexplorer.bobabeam.boba.network/", EthereumNetwork.BOBA_NETWORK_RINKEBY_TESTNET: "https://blockexplorer.rinkeby.boba.network/", EthereumNetwork.BOBA_NETWORK: "https://blockexplorer.boba.network/", EthereumNetwork.GATHER_DEVNET_NETWORK: "https://devnet-explorer.gather.network/", EthereumNetwork.GATHER_TESTNET_NETWORK: "https://testnet-explorer.gather.network/", EthereumNetwork.GATHER_MAINNET_NETWORK: "https://explorer.gather.network/", EthereumNetwork.METIS_STARDUST_TESTNET: "https://stardust-explorer.metis.io/", EthereumNetwork.METIS_GOERLI_TESTNET: "https://goerli.explorer.metisdevops.link/", EthereumNetwork.METIS_ANDROMEDA_MAINNET: "https://andromeda-explorer.metis.io/", EthereumNetwork.FUSE_MAINNET: "https://explorer.fuse.io/", EthereumNetwork.VELAS_EVM_MAINNET: "https://evmexplorer.velas.com/", EthereumNetwork.REI_NETWORK: "https://scan.rei.network/", EthereumNetwork.REI_CHAIN_TESTNET: "https://scan-test.rei.network/", EthereumNetwork.METER_MAINNET: "https://scan.meter.io/", EthereumNetwork.METER_TESTNET: "https://scan-warringstakes.meter.io/", EthereumNetwork.GODWOKEN_TESTNET_V1: "https://v1.betanet.gwscan.com/", EthereumNetwork.GODWOKEN_MAINNET: "https://v1.gwscan.com/", EthereumNetwork.VENIDIUM_TESTNET: "https://evm-testnet.venidiumexplorer.com/", EthereumNetwork.VENIDIUM_MAINNET: "https://evm.venidiumexplorer.com/", EthereumNetwork.KLAYTN_TESTNET_BAOBAB: "https://baobab.scope.klaytn.com/", EthereumNetwork.KLAYTN_MAINNET_CYPRESS: "https://scope.klaytn.com/", EthereumNetwork.ACALA_NETWORK: "https://blockscout.acala.network/", EthereumNetwork.KARURA_NETWORK_TESTNET: "https://blockscout.karura.network/", EthereumNetwork.ACALA_NETWORK_TESTNET: "https://blockscout.mandala.acala.network/", EthereumNetwork.ASTAR: "https://blockscout.com/astar/", EthereumNetwork.EVMOS: "https://evm.evmos.org", EthereumNetwork.EVMOS_TESTNET: "https://evm.evmos.dev", EthereumNetwork.RABBIT_ANALOG_TESTNET_CHAIN: "https://rabbit.analogscan.com", EthereumNetwork.KCC_MAINNET: "https://scan.kcc.io/", EthereumNetwork.KCC_TESTNET: "https://scan-testnet.kcc.network/", EthereumNetwork.ARBITRUM_ONE: "https://explorer.arbitrum.io", EthereumNetwork.ARBITRUM_NOVA: "https://nova-explorer.arbitrum.io", EthereumNetwork.ARBITRUM_GOERLI: "https://goerli-rollup-explorer.arbitrum.io", EthereumNetwork.CROSSBELL: "https://scan.crossbell.io", EthereumNetwork.ETHEREUM_CLASSIC_MAINNET: "https://blockscout.com/etc/mainnet/", EthereumNetwork.ETHEREUM_CLASSIC_TESTNET_MORDOR: "https://blockscout.com/etc/mordor/", } def __init__(self, network: EthereumNetwork): self.network = network self.base_url = self.NETWORK_WITH_URL.get(network) if self.base_url is None: raise BlockScoutConfigurationProblem( f"Network {network.name} - {network.value} not supported" ) self.grahpql_url = self.base_url + "/graphiql" self.http_session = requests.Session() def build_url(self, path: str): return urljoin(self.base_url, path) def _do_request(self, url: str, query: str) -> Optional[Dict[str, Any]]: response = self.http_session.post(url, json={"query": query}, timeout=10) if not response.ok: return None return response.json() def get_contract_metadata( self, address: ChecksumAddress ) -> Optional[ContractMetadata]: query = '{address(hash: "%s") { hash, smartContract {name, abi} }}' % address result = self._do_request(self.grahpql_url, query) if ( result and "error" not in result and result.get("data", {}).get("address", {}) and result["data"]["address"]["smartContract"] ): smart_contract = result["data"]["address"]["smartContract"] return ContractMetadata( smart_contract["name"], json.loads(smart_contract["abi"]), False )
/safe_eth_py_suraneti-5.4.3-py3-none-any.whl/gnosis/eth/clients/blockscout_client.py
0.736021
0.380011
blockscout_client.py
pypi
import binascii from typing import Optional, Union from django.core import exceptions from django.db import models from django.utils.translation import gettext_lazy as _ from eth_typing import ChecksumAddress from eth_utils import to_normalized_address from hexbytes import HexBytes from ..utils import fast_bytes_to_checksum_address, fast_to_checksum_address from .forms import EthereumAddressFieldForm, HexFieldForm, Keccak256FieldForm from .validators import validate_checksumed_address try: from django.db import DefaultConnectionProxy connection = DefaultConnectionProxy() except ImportError: from django.db import connections connection = connections["default"] class EthereumAddressField(models.CharField): default_validators = [validate_checksumed_address] description = "DEPRECATED. Use `EthereumAddressV2Field`. Ethereum address (EIP55)" default_error_messages = { "invalid": _('"%(value)s" value must be an EIP55 checksummed address.'), } def __init__(self, *args, **kwargs): kwargs["max_length"] = 42 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs def from_db_value(self, value, expression, connection): return self.to_python(value) def to_python(self, value): value = super().to_python(value) if value: try: return fast_to_checksum_address(value) except ValueError: raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) else: return value def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) class EthereumAddressV2Field(models.Field): default_validators = [validate_checksumed_address] description = "Ethereum address (EIP55)" default_error_messages = { "invalid": _('"%(value)s" value must be an EIP55 checksummed address.'), } def get_internal_type(self): return "BinaryField" def from_db_value( self, value: memoryview, expression, connection ) -> Optional[ChecksumAddress]: if value: return fast_bytes_to_checksum_address(value) def get_prep_value(self, value: ChecksumAddress) -> Optional[bytes]: if value: try: return HexBytes(to_normalized_address(value)) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def to_python(self, value) -> Optional[ChecksumAddress]: if value is not None: try: return fast_to_checksum_address(value) except ValueError: raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def formfield(self, **kwargs): defaults = { "form_class": EthereumAddressFieldForm, "max_length": 2 + 40, } defaults.update(kwargs) return super().formfield(**defaults) class Uint256Field(models.DecimalField): """ Field to store ethereum uint256 values. Uses Decimal db type without decimals to store in the database, but retrieve as `int` instead of `Decimal` (https://docs.python.org/3/library/decimal.html) """ description = _("Ethereum uint256 number") def __init__(self, *args, **kwargs): kwargs["max_digits"] = 79 # 2 ** 256 is 78 digits kwargs["decimal_places"] = 0 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_digits"] del kwargs["decimal_places"] return name, path, args, kwargs def from_db_value(self, value, expression, connection): if value is None: return value return int(value) class HexField(models.CharField): """ Field to store hex values (without 0x). Returns hex with 0x prefix. On Database side a CharField is used. """ description = "Stores a hex value into a CharField. DEPRECATED, use a BinaryField" def from_db_value(self, value, expression, connection): return self.to_python(value) def to_python(self, value): return value if value is None else HexBytes(value).hex() def get_prep_value(self, value): if value is None: return value elif isinstance(value, HexBytes): return value.hex()[ 2: ] # HexBytes.hex() retrieves hexadecimal with '0x', remove it elif isinstance(value, bytes): return value.hex() # bytes.hex() retrieves hexadecimal without '0x' else: # str return HexBytes(value).hex()[2:] def formfield(self, **kwargs): # We need max_lenght + 2 on forms because of `0x` defaults = {"max_length": self.max_length + 2} # TODO: Handle multiple backends with different feature flags. if self.null and not connection.features.interprets_empty_strings_as_nulls: defaults["empty_value"] = None defaults.update(kwargs) return super().formfield(**defaults) def clean(self, value, model_instance): value = self.to_python(value) self.validate(value, model_instance) # Validation didn't work because of `0x` self.run_validators(value[2:]) return value class HexV2Field(models.BinaryField): def formfield(self, **kwargs): defaults = { "form_class": HexFieldForm, } defaults.update(kwargs) return super().formfield(**defaults) class Sha3HashField(HexField): description = "DEPRECATED. Use `Keccak256Field`" def __init__(self, *args, **kwargs): kwargs["max_length"] = 64 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs class Keccak256Field(models.BinaryField): description = "Keccak256 hash stored as binary" default_error_messages = { "invalid": _('"%(value)s" hash must be a 32 bytes hexadecimal.'), "length": _('"%(value)s" hash must have exactly 32 bytes.'), } def _to_bytes(self, value) -> Optional[bytes]: if value is None: return else: try: result = HexBytes(value) if len(result) != 32: raise exceptions.ValidationError( self.error_messages["length"], code="length", params={"value": value}, ) return result except (ValueError, binascii.Error): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def from_db_value( self, value: memoryview, expression, connection ) -> Optional[bytes]: if value: return HexBytes(value.tobytes()).hex() def get_prep_value(self, value: Union[bytes, str]) -> Optional[bytes]: if value: return self._to_bytes(value) def value_to_string(self, obj): return str(self.value_from_object(obj)) def to_python(self, value) -> Optional[str]: if value is not None: try: return self._to_bytes(value) except (ValueError, binascii.Error): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def formfield(self, **kwargs): defaults = { "form_class": Keccak256FieldForm, "max_length": 2 + 64, } defaults.update(kwargs) return super().formfield(**defaults)
/safe_eth_py_suraneti-5.4.3-py3-none-any.whl/gnosis/eth/django/models.py
0.826362
0.198239
models.py
pypi
import binascii from typing import Any, Optional from django import forms from django.core import exceptions from django.core.exceptions import ValidationError from django.utils.translation import gettext as _ from hexbytes import HexBytes from gnosis.eth.utils import fast_is_checksum_address class EthereumAddressFieldForm(forms.CharField): default_error_messages = { "invalid": _("Enter a valid checksummed Ethereum Address."), } def prepare_value(self, value): return value def to_python(self, value): value = super().to_python(value) if value in self.empty_values: return None elif not fast_is_checksum_address(value): raise ValidationError(self.error_messages["invalid"], code="invalid") return value class HexFieldForm(forms.CharField): default_error_messages = { "invalid": _("Enter a valid hexadecimal."), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.empty_value = None def prepare_value(self, value: memoryview) -> str: if value: return "0x" + bytes(value).hex() else: return "" def to_python(self, value: Optional[Any]) -> Optional[HexBytes]: if value in self.empty_values: return self.empty_value try: if isinstance(value, str): value = value.strip() return HexBytes(value) except (binascii.Error, TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) class Keccak256FieldForm(HexFieldForm): default_error_messages = { "invalid": _('"%(value)s" is not a valid keccak256 hash.'), "length": _('"%(value)s" keccak256 hash should be 32 bytes.'), } def prepare_value(self, value: str) -> str: # Keccak field already returns a hex str return value def to_python(self, value: Optional[Any]) -> HexBytes: value: Optional[HexBytes] = super().to_python(value) if value and len(value) != 32: raise ValidationError( self.error_messages["length"], code="length", params={"value": value.hex()}, ) return value
/safe_eth_py_suraneti-5.4.3-py3-none-any.whl/gnosis/eth/django/forms.py
0.856107
0.237443
forms.py
pypi
import functools import logging from functools import cached_property from typing import Optional from eth_abi.exceptions import DecodingError from eth_typing import ChecksumAddress from web3.contract import Contract from web3.exceptions import Web3Exception from .. import EthereumClient, EthereumNetwork from ..constants import NULL_ADDRESS from ..contracts import get_erc20_contract from .abis.uniswap_v3 import ( uniswap_v3_factory_abi, uniswap_v3_pool_abi, uniswap_v3_router_abi, ) from .exceptions import CannotGetPriceFromOracle from .oracles import PriceOracle from .utils import get_decimals logger = logging.getLogger(__name__) class UniswapV3Oracle(PriceOracle): # https://docs.uniswap.org/protocol/reference/deployments DEFAULT_ROUTER_ADDRESS = "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45" ROUTER_ADDRESSES = { # SwapRouter02 EthereumNetwork.MAINNET: DEFAULT_ROUTER_ADDRESS, EthereumNetwork.CELO_MAINNET: "0x5615CDAb10dc425a742d643d949a7F474C01abc4", } # Cache to optimize calculation: https://docs.uniswap.org/sdk/guides/fetching-prices#understanding-sqrtprice PRICE_CONVERSION_CONSTANT = 2**192 def __init__( self, ethereum_client: EthereumClient, uniswap_v3_router_address: Optional[ChecksumAddress] = None, ): """ :param ethereum_client: :param uniswap_v3_router_address: Provide a custom `SwapRouter02` address """ self.ethereum_client = ethereum_client self.w3 = ethereum_client.w3 self.router_address = uniswap_v3_router_address or self.ROUTER_ADDRESSES.get( self.ethereum_client.get_network(), self.DEFAULT_ROUTER_ADDRESS ) self.factory = self.get_factory() @classmethod def is_available( cls, ethereum_client: EthereumClient, uniswap_v3_router_address: Optional[ChecksumAddress] = None, ) -> bool: """ :param ethereum_client: :param uniswap_v3_router_address: Provide a custom `SwapRouter02` address :return: `True` if Uniswap V3 is available for the EthereumClient provided, `False` otherwise """ router_address = uniswap_v3_router_address or cls.ROUTER_ADDRESSES.get( ethereum_client.get_network(), cls.DEFAULT_ROUTER_ADDRESS ) return ethereum_client.is_contract(router_address) def get_factory(self) -> Contract: """ Factory contract creates the pools for token pairs :return: Uniswap V3 Factory Contract """ try: factory_address = self.router.functions.factory().call() except Web3Exception: raise ValueError( f"Uniswap V3 Router Contract {self.router_address} does not exist" ) return self.w3.eth.contract(factory_address, abi=uniswap_v3_factory_abi) @cached_property def router(self) -> Contract: """ Router knows about the `Uniswap Factory` and `Wrapped Eth` addresses for the network :return: Uniswap V3 Router Contract """ return self.w3.eth.contract(self.router_address, abi=uniswap_v3_router_abi) @cached_property def weth_address(self) -> ChecksumAddress: """ :return: Wrapped ether checksummed address """ return self.router.functions.WETH9().call() @functools.lru_cache(maxsize=512) def get_pool_address( self, token_address: str, token_address_2: str, fee: Optional[int] = 3000 ) -> Optional[ChecksumAddress]: """ Get pool address for tokens with a given fee (by default, 0.3) :param token_address: :param token_address_2: :param fee: Uniswap V3 uses 0.3 as the default fee :return: Pool address """ pool_address = self.factory.functions.getPool( token_address, token_address_2, fee ).call() if pool_address == NULL_ADDRESS: return None return pool_address def get_price( self, token_address: str, token_address_2: Optional[str] = None ) -> float: """ :param token_address: :param token_address_2: :return: price for `token_address` related to `token_address_2`. If `token_address_2` is not provided, `Wrapped Eth` address will be used """ token_address_2 = token_address_2 or self.weth_address if token_address == token_address_2: return 1.0 reversed = token_address.lower() > token_address_2.lower() # Make it cache friendly as order does not matter args = ( (token_address_2, token_address) if reversed else (token_address, token_address_2) ) pool_address = self.get_pool_address(*args) if not pool_address: raise CannotGetPriceFromOracle( f"Uniswap V3 pool does not exist for {token_address} and {token_address_2}" ) # Decimals needs to be adjusted token_decimals = get_decimals(token_address, self.ethereum_client) token_2_decimals = get_decimals(token_address_2, self.ethereum_client) pool_contract = self.w3.eth.contract(pool_address, abi=uniswap_v3_pool_abi) try: ( token_balance, token_2_balance, (sqrt_price_x96, _, _, _, _, _, _), ) = self.ethereum_client.batch_call( [ get_erc20_contract( self.ethereum_client.w3, token_address ).functions.balanceOf(pool_address), get_erc20_contract( self.ethereum_client.w3, token_address_2 ).functions.balanceOf(pool_address), pool_contract.functions.slot0(), ] ) if (token_balance / 10**token_decimals) < 2 or ( token_2_balance / 10**token_2_decimals ) < 2: message = ( f"Not enough liquidity on uniswap v3 for pair token_1={token_address} " f"token_2={token_address_2}, at least 2 units of each token are required" ) logger.debug(message) raise CannotGetPriceFromOracle(message) except ( Web3Exception, DecodingError, ValueError, ) as e: message = ( f"Cannot get uniswap v3 price for pair token_1={token_address} " f"token_2={token_address_2}" ) logger.debug(message) raise CannotGetPriceFromOracle(message) from e # https://docs.uniswap.org/sdk/guides/fetching-prices if not reversed: # Multiplying by itself is way faster than exponential price = (sqrt_price_x96 * sqrt_price_x96) / self.PRICE_CONVERSION_CONSTANT else: price = self.PRICE_CONVERSION_CONSTANT / (sqrt_price_x96 * sqrt_price_x96) return price * 10 ** (token_decimals - token_2_decimals)
/safe_eth_py_suraneti-5.4.3-py3-none-any.whl/gnosis/eth/oracles/uniswap_v3.py
0.879652
0.163813
uniswap_v3.py
pypi
mooniswap_abi = [ { "inputs": [ {"internalType": "contract IERC20", "name": "_token0", "type": "address"}, {"internalType": "contract IERC20", "name": "_token1", "type": "address"}, {"internalType": "string", "name": "name", "type": "string"}, {"internalType": "string", "name": "symbol", "type": "string"}, { "internalType": "contract IMooniswapFactoryGovernance", "name": "_mooniswapFactoryGovernance", "type": "address", }, ], "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": True, "internalType": "address", "name": "spender", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "user", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "decayPeriod", "type": "uint256", }, { "indexed": False, "internalType": "bool", "name": "isDefault", "type": "bool", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, ], "name": "DecayPeriodVoteUpdate", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "receiver", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "share", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "token0Amount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "token1Amount", "type": "uint256", }, ], "name": "Deposited", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "string", "name": "reason", "type": "string", } ], "name": "Error", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "user", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "fee", "type": "uint256", }, { "indexed": False, "internalType": "bool", "name": "isDefault", "type": "bool", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, ], "name": "FeeVoteUpdate", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "previousOwner", "type": "address", }, { "indexed": True, "internalType": "address", "name": "newOwner", "type": "address", }, ], "name": "OwnershipTransferred", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "user", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "slippageFee", "type": "uint256", }, { "indexed": False, "internalType": "bool", "name": "isDefault", "type": "bool", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, ], "name": "SlippageFeeVoteUpdate", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "receiver", "type": "address", }, { "indexed": True, "internalType": "address", "name": "srcToken", "type": "address", }, { "indexed": False, "internalType": "address", "name": "dstToken", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "result", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "srcAdditionBalance", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "dstRemovalBalance", "type": "uint256", }, { "indexed": False, "internalType": "address", "name": "referral", "type": "address", }, ], "name": "Swapped", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint256", "name": "srcBalance", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "dstBalance", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "fee", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "slippageFee", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "referralShare", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "governanceShare", "type": "uint256", }, ], "name": "Sync", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "to", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "receiver", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "share", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "token0Amount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "token1Amount", "type": "uint256", }, ], "name": "Withdrawn", "type": "event", }, { "inputs": [ {"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}, ], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "decayPeriod", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "uint256", "name": "vote", "type": "uint256"}], "name": "decayPeriodVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "decayPeriodVotes", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "decimals", "outputs": [{"internalType": "uint8", "name": "", "type": "uint8"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "subtractedValue", "type": "uint256"}, ], "name": "decreaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint256[2]", "name": "maxAmounts", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "minAmounts", "type": "uint256[2]"}, ], "name": "deposit", "outputs": [ {"internalType": "uint256", "name": "fairSupply", "type": "uint256"}, { "internalType": "uint256[2]", "name": "receivedAmounts", "type": "uint256[2]", }, ], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "uint256[2]", "name": "maxAmounts", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "minAmounts", "type": "uint256[2]"}, {"internalType": "address", "name": "target", "type": "address"}, ], "name": "depositFor", "outputs": [ {"internalType": "uint256", "name": "fairSupply", "type": "uint256"}, { "internalType": "uint256[2]", "name": "receivedAmounts", "type": "uint256[2]", }, ], "stateMutability": "payable", "type": "function", }, { "inputs": [], "name": "discardDecayPeriodVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "discardFeeVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "discardSlippageFeeVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "fee", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "uint256", "name": "vote", "type": "uint256"}], "name": "feeVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "feeVotes", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "token", "type": "address"} ], "name": "getBalanceForAddition", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "token", "type": "address"} ], "name": "getBalanceForRemoval", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "src", "type": "address"}, {"internalType": "contract IERC20", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "getReturn", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "getTokens", "outputs": [ {"internalType": "contract IERC20[]", "name": "tokens", "type": "address[]"} ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "addedValue", "type": "uint256"}, ], "name": "increaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "mooniswapFactoryGovernance", "outputs": [ { "internalType": "contract IMooniswapFactoryGovernance", "name": "", "type": "address", } ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "name", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "owner", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "rescueFunds", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "contract IMooniswapFactoryGovernance", "name": "newMooniswapFactoryGovernance", "type": "address", } ], "name": "setMooniswapFactoryGovernance", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "slippageFee", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "uint256", "name": "vote", "type": "uint256"}], "name": "slippageFeeVote", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "slippageFeeVotes", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "src", "type": "address"}, {"internalType": "contract IERC20", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256", "name": "minReturn", "type": "uint256"}, {"internalType": "address", "name": "referral", "type": "address"}, ], "name": "swap", "outputs": [{"internalType": "uint256", "name": "result", "type": "uint256"}], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "contract IERC20", "name": "src", "type": "address"}, {"internalType": "contract IERC20", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256", "name": "minReturn", "type": "uint256"}, {"internalType": "address", "name": "referral", "type": "address"}, {"internalType": "address payable", "name": "receiver", "type": "address"}, ], "name": "swapFor", "outputs": [{"internalType": "uint256", "name": "result", "type": "uint256"}], "stateMutability": "payable", "type": "function", }, { "inputs": [], "name": "symbol", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "token0", "outputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "token1", "outputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "uint256", "name": "i", "type": "uint256"}], "name": "tokens", "outputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "sender", "type": "address"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "newOwner", "type": "address"}], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "name": "virtualBalancesForAddition", "outputs": [ {"internalType": "uint216", "name": "balance", "type": "uint216"}, {"internalType": "uint40", "name": "time", "type": "uint40"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "name": "virtualBalancesForRemoval", "outputs": [ {"internalType": "uint216", "name": "balance", "type": "uint216"}, {"internalType": "uint40", "name": "time", "type": "uint40"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "virtualDecayPeriod", "outputs": [ {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint48", "name": "", "type": "uint48"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "virtualFee", "outputs": [ {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint48", "name": "", "type": "uint48"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "virtualSlippageFee", "outputs": [ {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint104", "name": "", "type": "uint104"}, {"internalType": "uint48", "name": "", "type": "uint48"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "name": "volumes", "outputs": [ {"internalType": "uint128", "name": "confirmed", "type": "uint128"}, {"internalType": "uint128", "name": "result", "type": "uint128"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256[]", "name": "minReturns", "type": "uint256[]"}, ], "name": "withdraw", "outputs": [ { "internalType": "uint256[2]", "name": "withdrawnAmounts", "type": "uint256[2]", } ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256[]", "name": "minReturns", "type": "uint256[]"}, {"internalType": "address payable", "name": "target", "type": "address"}, ], "name": "withdrawFor", "outputs": [ { "internalType": "uint256[2]", "name": "withdrawnAmounts", "type": "uint256[2]", } ], "stateMutability": "nonpayable", "type": "function", }, ]
/safe_eth_py_suraneti-5.4.3-py3-none-any.whl/gnosis/eth/oracles/abis/mooniswap_abis.py
0.535098
0.515315
mooniswap_abis.py
pypi
uniswap_v3_factory_abi = [ {"inputs": [], "stateMutability": "nonpayable", "type": "constructor"}, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "uint24", "name": "fee", "type": "uint24", }, { "indexed": True, "internalType": "int24", "name": "tickSpacing", "type": "int24", }, ], "name": "FeeAmountEnabled", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "oldOwner", "type": "address", }, { "indexed": True, "internalType": "address", "name": "newOwner", "type": "address", }, ], "name": "OwnerChanged", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "token0", "type": "address", }, { "indexed": True, "internalType": "address", "name": "token1", "type": "address", }, { "indexed": True, "internalType": "uint24", "name": "fee", "type": "uint24", }, { "indexed": False, "internalType": "int24", "name": "tickSpacing", "type": "int24", }, { "indexed": False, "internalType": "address", "name": "pool", "type": "address", }, ], "name": "PoolCreated", "type": "event", }, { "inputs": [ {"internalType": "address", "name": "tokenA", "type": "address"}, {"internalType": "address", "name": "tokenB", "type": "address"}, {"internalType": "uint24", "name": "fee", "type": "uint24"}, ], "name": "createPool", "outputs": [{"internalType": "address", "name": "pool", "type": "address"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint24", "name": "fee", "type": "uint24"}, {"internalType": "int24", "name": "tickSpacing", "type": "int24"}, ], "name": "enableFeeAmount", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "uint24", "name": "", "type": "uint24"}], "name": "feeAmountTickSpacing", "outputs": [{"internalType": "int24", "name": "", "type": "int24"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "", "type": "address"}, {"internalType": "address", "name": "", "type": "address"}, {"internalType": "uint24", "name": "", "type": "uint24"}, ], "name": "getPool", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "owner", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "parameters", "outputs": [ {"internalType": "address", "name": "factory", "type": "address"}, {"internalType": "address", "name": "token0", "type": "address"}, {"internalType": "address", "name": "token1", "type": "address"}, {"internalType": "uint24", "name": "fee", "type": "uint24"}, {"internalType": "int24", "name": "tickSpacing", "type": "int24"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "address", "name": "_owner", "type": "address"}], "name": "setOwner", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ] uniswap_v3_router_abi = [ { "inputs": [ {"internalType": "address", "name": "_factoryV2", "type": "address"}, {"internalType": "address", "name": "factoryV3", "type": "address"}, {"internalType": "address", "name": "_positionManager", "type": "address"}, {"internalType": "address", "name": "_WETH9", "type": "address"}, ], "stateMutability": "nonpayable", "type": "constructor", }, { "inputs": [], "name": "WETH9", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "approveMax", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "approveMaxMinusOne", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "approveZeroThenMax", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "approveZeroThenMaxMinusOne", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [{"internalType": "bytes", "name": "data", "type": "bytes"}], "name": "callPositionManager", "outputs": [{"internalType": "bytes", "name": "result", "type": "bytes"}], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "bytes[]", "name": "paths", "type": "bytes[]"}, {"internalType": "uint128[]", "name": "amounts", "type": "uint128[]"}, { "internalType": "uint24", "name": "maximumTickDivergence", "type": "uint24", }, {"internalType": "uint32", "name": "secondsAgo", "type": "uint32"}, ], "name": "checkOracleSlippage", "outputs": [], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "bytes", "name": "path", "type": "bytes"}, { "internalType": "uint24", "name": "maximumTickDivergence", "type": "uint24", }, {"internalType": "uint32", "name": "secondsAgo", "type": "uint32"}, ], "name": "checkOracleSlippage", "outputs": [], "stateMutability": "view", "type": "function", }, { "inputs": [ { "components": [ {"internalType": "bytes", "name": "path", "type": "bytes"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amountIn", "type": "uint256"}, { "internalType": "uint256", "name": "amountOutMinimum", "type": "uint256", }, ], "internalType": "struct IV3SwapRouter.ExactInputParams", "name": "params", "type": "tuple", } ], "name": "exactInput", "outputs": [ {"internalType": "uint256", "name": "amountOut", "type": "uint256"} ], "stateMutability": "payable", "type": "function", }, { "inputs": [ { "components": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "address", "name": "tokenOut", "type": "address"}, {"internalType": "uint24", "name": "fee", "type": "uint24"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amountIn", "type": "uint256"}, { "internalType": "uint256", "name": "amountOutMinimum", "type": "uint256", }, { "internalType": "uint160", "name": "sqrtPriceLimitX96", "type": "uint160", }, ], "internalType": "struct IV3SwapRouter.ExactInputSingleParams", "name": "params", "type": "tuple", } ], "name": "exactInputSingle", "outputs": [ {"internalType": "uint256", "name": "amountOut", "type": "uint256"} ], "stateMutability": "payable", "type": "function", }, { "inputs": [ { "components": [ {"internalType": "bytes", "name": "path", "type": "bytes"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amountOut", "type": "uint256"}, { "internalType": "uint256", "name": "amountInMaximum", "type": "uint256", }, ], "internalType": "struct IV3SwapRouter.ExactOutputParams", "name": "params", "type": "tuple", } ], "name": "exactOutput", "outputs": [{"internalType": "uint256", "name": "amountIn", "type": "uint256"}], "stateMutability": "payable", "type": "function", }, { "inputs": [ { "components": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "address", "name": "tokenOut", "type": "address"}, {"internalType": "uint24", "name": "fee", "type": "uint24"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amountOut", "type": "uint256"}, { "internalType": "uint256", "name": "amountInMaximum", "type": "uint256", }, { "internalType": "uint160", "name": "sqrtPriceLimitX96", "type": "uint160", }, ], "internalType": "struct IV3SwapRouter.ExactOutputSingleParams", "name": "params", "type": "tuple", } ], "name": "exactOutputSingle", "outputs": [{"internalType": "uint256", "name": "amountIn", "type": "uint256"}], "stateMutability": "payable", "type": "function", }, { "inputs": [], "name": "factory", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "factoryV2", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "getApprovalType", "outputs": [ { "internalType": "enum IApproveAndCall.ApprovalType", "name": "", "type": "uint8", } ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "components": [ {"internalType": "address", "name": "token0", "type": "address"}, {"internalType": "address", "name": "token1", "type": "address"}, {"internalType": "uint256", "name": "tokenId", "type": "uint256"}, { "internalType": "uint256", "name": "amount0Min", "type": "uint256", }, { "internalType": "uint256", "name": "amount1Min", "type": "uint256", }, ], "internalType": "struct IApproveAndCall.IncreaseLiquidityParams", "name": "params", "type": "tuple", } ], "name": "increaseLiquidity", "outputs": [{"internalType": "bytes", "name": "result", "type": "bytes"}], "stateMutability": "payable", "type": "function", }, { "inputs": [ { "components": [ {"internalType": "address", "name": "token0", "type": "address"}, {"internalType": "address", "name": "token1", "type": "address"}, {"internalType": "uint24", "name": "fee", "type": "uint24"}, {"internalType": "int24", "name": "tickLower", "type": "int24"}, {"internalType": "int24", "name": "tickUpper", "type": "int24"}, { "internalType": "uint256", "name": "amount0Min", "type": "uint256", }, { "internalType": "uint256", "name": "amount1Min", "type": "uint256", }, {"internalType": "address", "name": "recipient", "type": "address"}, ], "internalType": "struct IApproveAndCall.MintParams", "name": "params", "type": "tuple", } ], "name": "mint", "outputs": [{"internalType": "bytes", "name": "result", "type": "bytes"}], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "bytes32", "name": "previousBlockhash", "type": "bytes32"}, {"internalType": "bytes[]", "name": "data", "type": "bytes[]"}, ], "name": "multicall", "outputs": [{"internalType": "bytes[]", "name": "", "type": "bytes[]"}], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "deadline", "type": "uint256"}, {"internalType": "bytes[]", "name": "data", "type": "bytes[]"}, ], "name": "multicall", "outputs": [{"internalType": "bytes[]", "name": "", "type": "bytes[]"}], "stateMutability": "payable", "type": "function", }, { "inputs": [{"internalType": "bytes[]", "name": "data", "type": "bytes[]"}], "name": "multicall", "outputs": [{"internalType": "bytes[]", "name": "results", "type": "bytes[]"}], "stateMutability": "payable", "type": "function", }, { "inputs": [], "name": "positionManager", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}, ], "name": "pull", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [], "name": "refundETH", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}, {"internalType": "uint256", "name": "deadline", "type": "uint256"}, {"internalType": "uint8", "name": "v", "type": "uint8"}, {"internalType": "bytes32", "name": "r", "type": "bytes32"}, {"internalType": "bytes32", "name": "s", "type": "bytes32"}, ], "name": "selfPermit", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "nonce", "type": "uint256"}, {"internalType": "uint256", "name": "expiry", "type": "uint256"}, {"internalType": "uint8", "name": "v", "type": "uint8"}, {"internalType": "bytes32", "name": "r", "type": "bytes32"}, {"internalType": "bytes32", "name": "s", "type": "bytes32"}, ], "name": "selfPermitAllowed", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "nonce", "type": "uint256"}, {"internalType": "uint256", "name": "expiry", "type": "uint256"}, {"internalType": "uint8", "name": "v", "type": "uint8"}, {"internalType": "bytes32", "name": "r", "type": "bytes32"}, {"internalType": "bytes32", "name": "s", "type": "bytes32"}, ], "name": "selfPermitAllowedIfNecessary", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}, {"internalType": "uint256", "name": "deadline", "type": "uint256"}, {"internalType": "uint8", "name": "v", "type": "uint8"}, {"internalType": "bytes32", "name": "r", "type": "bytes32"}, {"internalType": "bytes32", "name": "s", "type": "bytes32"}, ], "name": "selfPermitIfNecessary", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amountIn", "type": "uint256"}, {"internalType": "uint256", "name": "amountOutMin", "type": "uint256"}, {"internalType": "address[]", "name": "path", "type": "address[]"}, {"internalType": "address", "name": "to", "type": "address"}, ], "name": "swapExactTokensForTokens", "outputs": [ {"internalType": "uint256", "name": "amountOut", "type": "uint256"} ], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amountOut", "type": "uint256"}, {"internalType": "uint256", "name": "amountInMax", "type": "uint256"}, {"internalType": "address[]", "name": "path", "type": "address[]"}, {"internalType": "address", "name": "to", "type": "address"}, ], "name": "swapTokensForExactTokens", "outputs": [{"internalType": "uint256", "name": "amountIn", "type": "uint256"}], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "amountMinimum", "type": "uint256"}, {"internalType": "address", "name": "recipient", "type": "address"}, ], "name": "sweepToken", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "amountMinimum", "type": "uint256"}, ], "name": "sweepToken", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "amountMinimum", "type": "uint256"}, {"internalType": "uint256", "name": "feeBips", "type": "uint256"}, {"internalType": "address", "name": "feeRecipient", "type": "address"}, ], "name": "sweepTokenWithFee", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "amountMinimum", "type": "uint256"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "feeBips", "type": "uint256"}, {"internalType": "address", "name": "feeRecipient", "type": "address"}, ], "name": "sweepTokenWithFee", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "int256", "name": "amount0Delta", "type": "int256"}, {"internalType": "int256", "name": "amount1Delta", "type": "int256"}, {"internalType": "bytes", "name": "_data", "type": "bytes"}, ], "name": "uniswapV3SwapCallback", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amountMinimum", "type": "uint256"}, {"internalType": "address", "name": "recipient", "type": "address"}, ], "name": "unwrapWETH9", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amountMinimum", "type": "uint256"} ], "name": "unwrapWETH9", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amountMinimum", "type": "uint256"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "feeBips", "type": "uint256"}, {"internalType": "address", "name": "feeRecipient", "type": "address"}, ], "name": "unwrapWETH9WithFee", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amountMinimum", "type": "uint256"}, {"internalType": "uint256", "name": "feeBips", "type": "uint256"}, {"internalType": "address", "name": "feeRecipient", "type": "address"}, ], "name": "unwrapWETH9WithFee", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [{"internalType": "uint256", "name": "value", "type": "uint256"}], "name": "wrapETH", "outputs": [], "stateMutability": "payable", "type": "function", }, {"stateMutability": "payable", "type": "receive"}, ] uniswap_v3_pool_abi = [ {"inputs": [], "stateMutability": "nonpayable", "type": "constructor"}, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": True, "internalType": "int24", "name": "tickLower", "type": "int24", }, { "indexed": True, "internalType": "int24", "name": "tickUpper", "type": "int24", }, { "indexed": False, "internalType": "uint128", "name": "amount", "type": "uint128", }, { "indexed": False, "internalType": "uint256", "name": "amount0", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "amount1", "type": "uint256", }, ], "name": "Burn", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": False, "internalType": "address", "name": "recipient", "type": "address", }, { "indexed": True, "internalType": "int24", "name": "tickLower", "type": "int24", }, { "indexed": True, "internalType": "int24", "name": "tickUpper", "type": "int24", }, { "indexed": False, "internalType": "uint128", "name": "amount0", "type": "uint128", }, { "indexed": False, "internalType": "uint128", "name": "amount1", "type": "uint128", }, ], "name": "Collect", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "recipient", "type": "address", }, { "indexed": False, "internalType": "uint128", "name": "amount0", "type": "uint128", }, { "indexed": False, "internalType": "uint128", "name": "amount1", "type": "uint128", }, ], "name": "CollectProtocol", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "recipient", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amount0", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "amount1", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "paid0", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "paid1", "type": "uint256", }, ], "name": "Flash", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint16", "name": "observationCardinalityNextOld", "type": "uint16", }, { "indexed": False, "internalType": "uint16", "name": "observationCardinalityNextNew", "type": "uint16", }, ], "name": "IncreaseObservationCardinalityNext", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint160", "name": "sqrtPriceX96", "type": "uint160", }, { "indexed": False, "internalType": "int24", "name": "tick", "type": "int24", }, ], "name": "Initialize", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": True, "internalType": "int24", "name": "tickLower", "type": "int24", }, { "indexed": True, "internalType": "int24", "name": "tickUpper", "type": "int24", }, { "indexed": False, "internalType": "uint128", "name": "amount", "type": "uint128", }, { "indexed": False, "internalType": "uint256", "name": "amount0", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "amount1", "type": "uint256", }, ], "name": "Mint", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint8", "name": "feeProtocol0Old", "type": "uint8", }, { "indexed": False, "internalType": "uint8", "name": "feeProtocol1Old", "type": "uint8", }, { "indexed": False, "internalType": "uint8", "name": "feeProtocol0New", "type": "uint8", }, { "indexed": False, "internalType": "uint8", "name": "feeProtocol1New", "type": "uint8", }, ], "name": "SetFeeProtocol", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "sender", "type": "address", }, { "indexed": True, "internalType": "address", "name": "recipient", "type": "address", }, { "indexed": False, "internalType": "int256", "name": "amount0", "type": "int256", }, { "indexed": False, "internalType": "int256", "name": "amount1", "type": "int256", }, { "indexed": False, "internalType": "uint160", "name": "sqrtPriceX96", "type": "uint160", }, { "indexed": False, "internalType": "uint128", "name": "liquidity", "type": "uint128", }, { "indexed": False, "internalType": "int24", "name": "tick", "type": "int24", }, ], "name": "Swap", "type": "event", }, { "inputs": [ {"internalType": "int24", "name": "tickLower", "type": "int24"}, {"internalType": "int24", "name": "tickUpper", "type": "int24"}, {"internalType": "uint128", "name": "amount", "type": "uint128"}, ], "name": "burn", "outputs": [ {"internalType": "uint256", "name": "amount0", "type": "uint256"}, {"internalType": "uint256", "name": "amount1", "type": "uint256"}, ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "int24", "name": "tickLower", "type": "int24"}, {"internalType": "int24", "name": "tickUpper", "type": "int24"}, {"internalType": "uint128", "name": "amount0Requested", "type": "uint128"}, {"internalType": "uint128", "name": "amount1Requested", "type": "uint128"}, ], "name": "collect", "outputs": [ {"internalType": "uint128", "name": "amount0", "type": "uint128"}, {"internalType": "uint128", "name": "amount1", "type": "uint128"}, ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint128", "name": "amount0Requested", "type": "uint128"}, {"internalType": "uint128", "name": "amount1Requested", "type": "uint128"}, ], "name": "collectProtocol", "outputs": [ {"internalType": "uint128", "name": "amount0", "type": "uint128"}, {"internalType": "uint128", "name": "amount1", "type": "uint128"}, ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "factory", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "fee", "outputs": [{"internalType": "uint24", "name": "", "type": "uint24"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "feeGrowthGlobal0X128", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "feeGrowthGlobal1X128", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount0", "type": "uint256"}, {"internalType": "uint256", "name": "amount1", "type": "uint256"}, {"internalType": "bytes", "name": "data", "type": "bytes"}, ], "name": "flash", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "uint16", "name": "observationCardinalityNext", "type": "uint16", } ], "name": "increaseObservationCardinalityNext", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint160", "name": "sqrtPriceX96", "type": "uint160"} ], "name": "initialize", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "liquidity", "outputs": [{"internalType": "uint128", "name": "", "type": "uint128"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "maxLiquidityPerTick", "outputs": [{"internalType": "uint128", "name": "", "type": "uint128"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "int24", "name": "tickLower", "type": "int24"}, {"internalType": "int24", "name": "tickUpper", "type": "int24"}, {"internalType": "uint128", "name": "amount", "type": "uint128"}, {"internalType": "bytes", "name": "data", "type": "bytes"}, ], "name": "mint", "outputs": [ {"internalType": "uint256", "name": "amount0", "type": "uint256"}, {"internalType": "uint256", "name": "amount1", "type": "uint256"}, ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "name": "observations", "outputs": [ {"internalType": "uint32", "name": "blockTimestamp", "type": "uint32"}, {"internalType": "int56", "name": "tickCumulative", "type": "int56"}, { "internalType": "uint160", "name": "secondsPerLiquidityCumulativeX128", "type": "uint160", }, {"internalType": "bool", "name": "initialized", "type": "bool"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "uint32[]", "name": "secondsAgos", "type": "uint32[]"} ], "name": "observe", "outputs": [ {"internalType": "int56[]", "name": "tickCumulatives", "type": "int56[]"}, { "internalType": "uint160[]", "name": "secondsPerLiquidityCumulativeX128s", "type": "uint160[]", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "bytes32", "name": "", "type": "bytes32"}], "name": "positions", "outputs": [ {"internalType": "uint128", "name": "liquidity", "type": "uint128"}, { "internalType": "uint256", "name": "feeGrowthInside0LastX128", "type": "uint256", }, { "internalType": "uint256", "name": "feeGrowthInside1LastX128", "type": "uint256", }, {"internalType": "uint128", "name": "tokensOwed0", "type": "uint128"}, {"internalType": "uint128", "name": "tokensOwed1", "type": "uint128"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "protocolFees", "outputs": [ {"internalType": "uint128", "name": "token0", "type": "uint128"}, {"internalType": "uint128", "name": "token1", "type": "uint128"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "uint8", "name": "feeProtocol0", "type": "uint8"}, {"internalType": "uint8", "name": "feeProtocol1", "type": "uint8"}, ], "name": "setFeeProtocol", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "slot0", "outputs": [ {"internalType": "uint160", "name": "sqrtPriceX96", "type": "uint160"}, {"internalType": "int24", "name": "tick", "type": "int24"}, {"internalType": "uint16", "name": "observationIndex", "type": "uint16"}, { "internalType": "uint16", "name": "observationCardinality", "type": "uint16", }, { "internalType": "uint16", "name": "observationCardinalityNext", "type": "uint16", }, {"internalType": "uint8", "name": "feeProtocol", "type": "uint8"}, {"internalType": "bool", "name": "unlocked", "type": "bool"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "int24", "name": "tickLower", "type": "int24"}, {"internalType": "int24", "name": "tickUpper", "type": "int24"}, ], "name": "snapshotCumulativesInside", "outputs": [ {"internalType": "int56", "name": "tickCumulativeInside", "type": "int56"}, { "internalType": "uint160", "name": "secondsPerLiquidityInsideX128", "type": "uint160", }, {"internalType": "uint32", "name": "secondsInside", "type": "uint32"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "bool", "name": "zeroForOne", "type": "bool"}, {"internalType": "int256", "name": "amountSpecified", "type": "int256"}, {"internalType": "uint160", "name": "sqrtPriceLimitX96", "type": "uint160"}, {"internalType": "bytes", "name": "data", "type": "bytes"}, ], "name": "swap", "outputs": [ {"internalType": "int256", "name": "amount0", "type": "int256"}, {"internalType": "int256", "name": "amount1", "type": "int256"}, ], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "int16", "name": "", "type": "int16"}], "name": "tickBitmap", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "tickSpacing", "outputs": [{"internalType": "int24", "name": "", "type": "int24"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "int24", "name": "", "type": "int24"}], "name": "ticks", "outputs": [ {"internalType": "uint128", "name": "liquidityGross", "type": "uint128"}, {"internalType": "int128", "name": "liquidityNet", "type": "int128"}, { "internalType": "uint256", "name": "feeGrowthOutside0X128", "type": "uint256", }, { "internalType": "uint256", "name": "feeGrowthOutside1X128", "type": "uint256", }, {"internalType": "int56", "name": "tickCumulativeOutside", "type": "int56"}, { "internalType": "uint160", "name": "secondsPerLiquidityOutsideX128", "type": "uint160", }, {"internalType": "uint32", "name": "secondsOutside", "type": "uint32"}, {"internalType": "bool", "name": "initialized", "type": "bool"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "token0", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "token1", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, ]
/safe_eth_py_suraneti-5.4.3-py3-none-any.whl/gnosis/eth/oracles/abis/uniswap_v3.py
0.515864
0.476275
uniswap_v3.py
pypi
AAVE_ATOKEN_ABI = [ { "inputs": [ { "internalType": "contract ILendingPool", "name": "pool", "type": "address", }, { "internalType": "address", "name": "underlyingAssetAddress", "type": "address", }, { "internalType": "address", "name": "reserveTreasuryAddress", "type": "address", }, {"internalType": "string", "name": "tokenName", "type": "string"}, {"internalType": "string", "name": "tokenSymbol", "type": "string"}, { "internalType": "address", "name": "incentivesController", "type": "address", }, ], "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": True, "internalType": "address", "name": "spender", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "to", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "index", "type": "uint256", }, ], "name": "BalanceTransfer", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "target", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "index", "type": "uint256", }, ], "name": "Burn", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "underlyingAsset", "type": "address", }, { "indexed": True, "internalType": "address", "name": "pool", "type": "address", }, { "indexed": False, "internalType": "address", "name": "treasury", "type": "address", }, { "indexed": False, "internalType": "address", "name": "incentivesController", "type": "address", }, { "indexed": False, "internalType": "uint8", "name": "aTokenDecimals", "type": "uint8", }, { "indexed": False, "internalType": "string", "name": "aTokenName", "type": "string", }, { "indexed": False, "internalType": "string", "name": "aTokenSymbol", "type": "string", }, { "indexed": False, "internalType": "bytes", "name": "params", "type": "bytes", }, ], "name": "Initialized", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "index", "type": "uint256", }, ], "name": "Mint", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "to", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "inputs": [], "name": "ATOKEN_REVISION", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "DOMAIN_SEPARATOR", "outputs": [{"internalType": "bytes32", "name": "", "type": "bytes32"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "EIP712_REVISION", "outputs": [{"internalType": "bytes", "name": "", "type": "bytes"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "PERMIT_TYPEHASH", "outputs": [{"internalType": "bytes32", "name": "", "type": "bytes32"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "POOL", "outputs": [ {"internalType": "contract ILendingPool", "name": "", "type": "address"} ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "RESERVE_TREASURY_ADDRESS", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "UINT_MAX_VALUE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "UNDERLYING_ASSET_ADDRESS", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "address", "name": "", "type": "address"}], "name": "_nonces", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}, ], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "user", "type": "address"}, { "internalType": "address", "name": "receiverOfUnderlying", "type": "address", }, {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256", "name": "index", "type": "uint256"}, ], "name": "burn", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "decimals", "outputs": [{"internalType": "uint8", "name": "", "type": "uint8"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "subtractedValue", "type": "uint256"}, ], "name": "decreaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "getIncentivesController", "outputs": [ { "internalType": "contract IAaveIncentivesController", "name": "", "type": "address", } ], "stateMutability": "view", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "getScaledUserBalanceAndSupply", "outputs": [ {"internalType": "uint256", "name": "", "type": "uint256"}, {"internalType": "uint256", "name": "", "type": "uint256"}, ], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "addedValue", "type": "uint256"}, ], "name": "increaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "uint8", "name": "underlyingAssetDecimals", "type": "uint8", }, {"internalType": "string", "name": "tokenName", "type": "string"}, {"internalType": "string", "name": "tokenSymbol", "type": "string"}, ], "name": "initialize", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "user", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256", "name": "index", "type": "uint256"}, ], "name": "mint", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "uint256", "name": "amount", "type": "uint256"}, {"internalType": "uint256", "name": "index", "type": "uint256"}, ], "name": "mintToTreasury", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "name", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}, {"internalType": "uint256", "name": "deadline", "type": "uint256"}, {"internalType": "uint8", "name": "v", "type": "uint8"}, {"internalType": "bytes32", "name": "r", "type": "bytes32"}, {"internalType": "bytes32", "name": "s", "type": "bytes32"}, ], "name": "permit", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [{"internalType": "address", "name": "user", "type": "address"}], "name": "scaledBalanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "scaledTotalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "symbol", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "sender", "type": "address"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "from", "type": "address"}, {"internalType": "address", "name": "to", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}, ], "name": "transferOnLiquidation", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ {"internalType": "address", "name": "target", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transferUnderlyingTo", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "nonpayable", "type": "function", }, ]
/safe_eth_py_suraneti-5.4.3-py3-none-any.whl/gnosis/eth/oracles/abis/aave_abis.py
0.566019
0.415847
aave_abis.py
pypi
curve_address_provider_abi = [ { "name": "NewAddressIdentifier", "inputs": [ {"type": "uint256", "name": "id", "indexed": True}, {"type": "address", "name": "addr", "indexed": False}, {"type": "string", "name": "description", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "AddressModified", "inputs": [ {"type": "uint256", "name": "id", "indexed": True}, {"type": "address", "name": "new_address", "indexed": False}, {"type": "uint256", "name": "version", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "CommitNewAdmin", "inputs": [ {"type": "uint256", "name": "deadline", "indexed": True}, {"type": "address", "name": "admin", "indexed": True}, ], "anonymous": False, "type": "event", }, { "name": "NewAdmin", "inputs": [{"type": "address", "name": "admin", "indexed": True}], "anonymous": False, "type": "event", }, { "outputs": [], "inputs": [{"type": "address", "name": "_admin"}], "stateMutability": "nonpayable", "type": "constructor", }, { "name": "get_registry", "outputs": [{"type": "address", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 1061, }, { "name": "max_id", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 1258, }, { "name": "get_address", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "uint256", "name": "_id"}], "stateMutability": "view", "type": "function", "gas": 1308, }, { "name": "add_new_id", "outputs": [{"type": "uint256", "name": ""}], "inputs": [ {"type": "address", "name": "_address"}, {"type": "string", "name": "_description"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 291275, }, { "name": "set_address", "outputs": [{"type": "bool", "name": ""}], "inputs": [ {"type": "uint256", "name": "_id"}, {"type": "address", "name": "_address"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 182430, }, { "name": "unset_address", "outputs": [{"type": "bool", "name": ""}], "inputs": [{"type": "uint256", "name": "_id"}], "stateMutability": "nonpayable", "type": "function", "gas": 101348, }, { "name": "commit_transfer_ownership", "outputs": [{"type": "bool", "name": ""}], "inputs": [{"type": "address", "name": "_new_admin"}], "stateMutability": "nonpayable", "type": "function", "gas": 74048, }, { "name": "apply_transfer_ownership", "outputs": [{"type": "bool", "name": ""}], "inputs": [], "stateMutability": "nonpayable", "type": "function", "gas": 60125, }, { "name": "revert_transfer_ownership", "outputs": [{"type": "bool", "name": ""}], "inputs": [], "stateMutability": "nonpayable", "type": "function", "gas": 21400, }, { "name": "admin", "outputs": [{"type": "address", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 1331, }, { "name": "transfer_ownership_deadline", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 1361, }, { "name": "future_admin", "outputs": [{"type": "address", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 1391, }, { "name": "get_id_info", "outputs": [ {"type": "address", "name": "addr"}, {"type": "bool", "name": "is_active"}, {"type": "uint256", "name": "version"}, {"type": "uint256", "name": "last_modified"}, {"type": "string", "name": "description"}, ], "inputs": [{"type": "uint256", "name": "arg0"}], "stateMutability": "view", "type": "function", "gas": 12168, }, ] curve_registry_abi = [ { "name": "PoolAdded", "inputs": [ {"type": "address", "name": "pool", "indexed": True}, {"type": "bytes", "name": "rate_method_id", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "PoolRemoved", "inputs": [{"type": "address", "name": "pool", "indexed": True}], "anonymous": False, "type": "event", }, { "outputs": [], "inputs": [ {"type": "address", "name": "_address_provider"}, {"type": "address", "name": "_gauge_controller"}, ], "stateMutability": "nonpayable", "type": "constructor", }, { "name": "find_pool_for_coins", "outputs": [{"type": "address", "name": ""}], "inputs": [ {"type": "address", "name": "_from"}, {"type": "address", "name": "_to"}, ], "stateMutability": "view", "type": "function", }, { "name": "find_pool_for_coins", "outputs": [{"type": "address", "name": ""}], "inputs": [ {"type": "address", "name": "_from"}, {"type": "address", "name": "_to"}, {"type": "uint256", "name": "i"}, ], "stateMutability": "view", "type": "function", }, { "name": "get_n_coins", "outputs": [{"type": "uint256[2]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 1704, }, { "name": "get_coins", "outputs": [{"type": "address[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 12285, }, { "name": "get_underlying_coins", "outputs": [{"type": "address[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 12347, }, { "name": "get_decimals", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 8199, }, { "name": "get_underlying_decimals", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 8261, }, { "name": "get_rates", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 34780, }, { "name": "get_gauges", "outputs": [ {"type": "address[10]", "name": ""}, {"type": "int128[10]", "name": ""}, ], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 20310, }, { "name": "get_balances", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 16818, }, { "name": "get_underlying_balances", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 158953, }, { "name": "get_virtual_price_from_lp_token", "outputs": [{"type": "uint256", "name": ""}], "inputs": [{"type": "address", "name": "_token"}], "stateMutability": "view", "type": "function", "gas": 2080, }, { "name": "get_A", "outputs": [{"type": "uint256", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 1198, }, { "name": "get_parameters", "outputs": [ {"type": "uint256", "name": "A"}, {"type": "uint256", "name": "future_A"}, {"type": "uint256", "name": "fee"}, {"type": "uint256", "name": "admin_fee"}, {"type": "uint256", "name": "future_fee"}, {"type": "uint256", "name": "future_admin_fee"}, {"type": "address", "name": "future_owner"}, {"type": "uint256", "name": "initial_A"}, {"type": "uint256", "name": "initial_A_time"}, {"type": "uint256", "name": "future_A_time"}, ], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 6458, }, { "name": "get_fees", "outputs": [{"type": "uint256[2]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 1603, }, { "name": "get_admin_balances", "outputs": [{"type": "uint256[8]", "name": ""}], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "view", "type": "function", "gas": 36719, }, { "name": "get_coin_indices", "outputs": [ {"type": "int128", "name": ""}, {"type": "int128", "name": ""}, {"type": "bool", "name": ""}, ], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "address", "name": "_from"}, {"type": "address", "name": "_to"}, ], "stateMutability": "view", "type": "function", "gas": 27456, }, { "name": "estimate_gas_used", "outputs": [{"type": "uint256", "name": ""}], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "address", "name": "_from"}, {"type": "address", "name": "_to"}, ], "stateMutability": "view", "type": "function", "gas": 32329, }, { "name": "add_pool", "outputs": [], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "uint256", "name": "_n_coins"}, {"type": "address", "name": "_lp_token"}, {"type": "bytes32", "name": "_rate_method_id"}, {"type": "uint256", "name": "_decimals"}, {"type": "uint256", "name": "_underlying_decimals"}, {"type": "bool", "name": "_has_initial_A"}, {"type": "bool", "name": "_is_v1"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 10196577, }, { "name": "add_pool_without_underlying", "outputs": [], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "uint256", "name": "_n_coins"}, {"type": "address", "name": "_lp_token"}, {"type": "bytes32", "name": "_rate_method_id"}, {"type": "uint256", "name": "_decimals"}, {"type": "uint256", "name": "_use_rates"}, {"type": "bool", "name": "_has_initial_A"}, {"type": "bool", "name": "_is_v1"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 5590664, }, { "name": "add_metapool", "outputs": [], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "uint256", "name": "_n_coins"}, {"type": "address", "name": "_lp_token"}, {"type": "uint256", "name": "_decimals"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 10226976, }, { "name": "remove_pool", "outputs": [], "inputs": [{"type": "address", "name": "_pool"}], "stateMutability": "nonpayable", "type": "function", "gas": 779646579509, }, { "name": "set_pool_gas_estimates", "outputs": [], "inputs": [ {"type": "address[5]", "name": "_addr"}, {"type": "uint256[2][5]", "name": "_amount"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 355578, }, { "name": "set_coin_gas_estimates", "outputs": [], "inputs": [ {"type": "address[10]", "name": "_addr"}, {"type": "uint256[10]", "name": "_amount"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 357165, }, { "name": "set_gas_estimate_contract", "outputs": [], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "address", "name": "_estimator"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 37747, }, { "name": "set_liquidity_gauges", "outputs": [], "inputs": [ {"type": "address", "name": "_pool"}, {"type": "address[10]", "name": "_liquidity_gauges"}, ], "stateMutability": "nonpayable", "type": "function", "gas": 365793, }, { "name": "address_provider", "outputs": [{"type": "address", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 2111, }, { "name": "gauge_controller", "outputs": [{"type": "address", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 2141, }, { "name": "pool_list", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "uint256", "name": "arg0"}], "stateMutability": "view", "type": "function", "gas": 2280, }, { "name": "pool_count", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "stateMutability": "view", "type": "function", "gas": 2201, }, { "name": "get_pool_from_lp_token", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "address", "name": "arg0"}], "stateMutability": "view", "type": "function", "gas": 2446, }, { "name": "get_lp_token", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "address", "name": "arg0"}], "stateMutability": "view", "type": "function", "gas": 2476, }, ] curve_pool_abi = [ { "name": "TokenExchange", "inputs": [ {"type": "address", "name": "buyer", "indexed": True}, {"type": "int128", "name": "sold_id", "indexed": False}, {"type": "uint256", "name": "tokens_sold", "indexed": False}, {"type": "int128", "name": "bought_id", "indexed": False}, {"type": "uint256", "name": "tokens_bought", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "TokenExchangeUnderlying", "inputs": [ {"type": "address", "name": "buyer", "indexed": True}, {"type": "int128", "name": "sold_id", "indexed": False}, {"type": "uint256", "name": "tokens_sold", "indexed": False}, {"type": "int128", "name": "bought_id", "indexed": False}, {"type": "uint256", "name": "tokens_bought", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "AddLiquidity", "inputs": [ {"type": "address", "name": "provider", "indexed": True}, {"type": "uint256[4]", "name": "token_amounts", "indexed": False}, {"type": "uint256[4]", "name": "fees", "indexed": False}, {"type": "uint256", "name": "invariant", "indexed": False}, {"type": "uint256", "name": "token_supply", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "RemoveLiquidity", "inputs": [ {"type": "address", "name": "provider", "indexed": True}, {"type": "uint256[4]", "name": "token_amounts", "indexed": False}, {"type": "uint256[4]", "name": "fees", "indexed": False}, {"type": "uint256", "name": "token_supply", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "RemoveLiquidityImbalance", "inputs": [ {"type": "address", "name": "provider", "indexed": True}, {"type": "uint256[4]", "name": "token_amounts", "indexed": False}, {"type": "uint256[4]", "name": "fees", "indexed": False}, {"type": "uint256", "name": "invariant", "indexed": False}, {"type": "uint256", "name": "token_supply", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "CommitNewAdmin", "inputs": [ {"type": "uint256", "name": "deadline", "indexed": True, "unit": "sec"}, {"type": "address", "name": "admin", "indexed": True}, ], "anonymous": False, "type": "event", }, { "name": "NewAdmin", "inputs": [{"type": "address", "name": "admin", "indexed": True}], "anonymous": False, "type": "event", }, { "name": "CommitNewParameters", "inputs": [ {"type": "uint256", "name": "deadline", "indexed": True, "unit": "sec"}, {"type": "uint256", "name": "A", "indexed": False}, {"type": "uint256", "name": "fee", "indexed": False}, {"type": "uint256", "name": "admin_fee", "indexed": False}, ], "anonymous": False, "type": "event", }, { "name": "NewParameters", "inputs": [ {"type": "uint256", "name": "A", "indexed": False}, {"type": "uint256", "name": "fee", "indexed": False}, {"type": "uint256", "name": "admin_fee", "indexed": False}, ], "anonymous": False, "type": "event", }, { "outputs": [], "inputs": [ {"type": "address[4]", "name": "_coins"}, {"type": "address[4]", "name": "_underlying_coins"}, {"type": "address", "name": "_pool_token"}, {"type": "uint256", "name": "_A"}, {"type": "uint256", "name": "_fee"}, ], "constant": False, "payable": False, "type": "constructor", }, { "name": "get_virtual_price", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 1570535, }, { "name": "calc_token_amount", "outputs": [{"type": "uint256", "name": ""}], "inputs": [ {"type": "uint256[4]", "name": "amounts"}, {"type": "bool", "name": "deposit"}, ], "constant": True, "payable": False, "type": "function", "gas": 6103471, }, { "name": "add_liquidity", "outputs": [], "inputs": [ {"type": "uint256[4]", "name": "amounts"}, {"type": "uint256", "name": "min_mint_amount"}, ], "constant": False, "payable": False, "type": "function", "gas": 9331701, }, { "name": "get_dy", "outputs": [{"type": "uint256", "name": ""}], "inputs": [ {"type": "int128", "name": "i"}, {"type": "int128", "name": "j"}, {"type": "uint256", "name": "dx"}, ], "constant": True, "payable": False, "type": "function", "gas": 3489637, }, { "name": "get_dy_underlying", "outputs": [{"type": "uint256", "name": ""}], "inputs": [ {"type": "int128", "name": "i"}, {"type": "int128", "name": "j"}, {"type": "uint256", "name": "dx"}, ], "constant": True, "payable": False, "type": "function", "gas": 3489467, }, { "name": "exchange", "outputs": [], "inputs": [ {"type": "int128", "name": "i"}, {"type": "int128", "name": "j"}, {"type": "uint256", "name": "dx"}, {"type": "uint256", "name": "min_dy"}, ], "constant": False, "payable": False, "type": "function", "gas": 7034253, }, { "name": "exchange_underlying", "outputs": [], "inputs": [ {"type": "int128", "name": "i"}, {"type": "int128", "name": "j"}, {"type": "uint256", "name": "dx"}, {"type": "uint256", "name": "min_dy"}, ], "constant": False, "payable": False, "type": "function", "gas": 7050488, }, { "name": "remove_liquidity", "outputs": [], "inputs": [ {"type": "uint256", "name": "_amount"}, {"type": "uint256[4]", "name": "min_amounts"}, ], "constant": False, "payable": False, "type": "function", "gas": 241191, }, { "name": "remove_liquidity_imbalance", "outputs": [], "inputs": [ {"type": "uint256[4]", "name": "amounts"}, {"type": "uint256", "name": "max_burn_amount"}, ], "constant": False, "payable": False, "type": "function", "gas": 9330864, }, { "name": "commit_new_parameters", "outputs": [], "inputs": [ {"type": "uint256", "name": "amplification"}, {"type": "uint256", "name": "new_fee"}, {"type": "uint256", "name": "new_admin_fee"}, ], "constant": False, "payable": False, "type": "function", "gas": 146045, }, { "name": "apply_new_parameters", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 133452, }, { "name": "revert_new_parameters", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 21775, }, { "name": "commit_transfer_ownership", "outputs": [], "inputs": [{"type": "address", "name": "_owner"}], "constant": False, "payable": False, "type": "function", "gas": 74452, }, { "name": "apply_transfer_ownership", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 60508, }, { "name": "revert_transfer_ownership", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 21865, }, { "name": "withdraw_admin_fees", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 23448, }, { "name": "kill_me", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 37818, }, { "name": "unkill_me", "outputs": [], "inputs": [], "constant": False, "payable": False, "type": "function", "gas": 21955, }, { "name": "coins", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "int128", "name": "arg0"}], "constant": True, "payable": False, "type": "function", "gas": 2130, }, { "name": "underlying_coins", "outputs": [{"type": "address", "name": ""}], "inputs": [{"type": "int128", "name": "arg0"}], "constant": True, "payable": False, "type": "function", "gas": 2160, }, { "name": "balances", "outputs": [{"type": "uint256", "name": ""}], "inputs": [{"type": "int128", "name": "arg0"}], "constant": True, "payable": False, "type": "function", "gas": 2190, }, { "name": "A", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2021, }, { "name": "fee", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2051, }, { "name": "admin_fee", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2081, }, { "name": "owner", "outputs": [{"type": "address", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2111, }, { "name": "admin_actions_deadline", "outputs": [{"type": "uint256", "unit": "sec", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2141, }, { "name": "transfer_ownership_deadline", "outputs": [{"type": "uint256", "unit": "sec", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2171, }, { "name": "future_A", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2201, }, { "name": "future_fee", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2231, }, { "name": "future_admin_fee", "outputs": [{"type": "uint256", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2261, }, { "name": "future_owner", "outputs": [{"type": "address", "name": ""}], "inputs": [], "constant": True, "payable": False, "type": "function", "gas": 2291, }, ]
/safe_eth_py_suraneti-5.4.3-py3-none-any.whl/gnosis/eth/oracles/abis/curve_abis.py
0.663124
0.531149
curve_abis.py
pypi
cream_ctoken_abi = [ { "inputs": [ {"internalType": "address", "name": "underlying_", "type": "address"}, { "internalType": "contract ComptrollerInterface", "name": "comptroller_", "type": "address", }, { "internalType": "contract InterestRateModel", "name": "interestRateModel_", "type": "address", }, { "internalType": "uint256", "name": "initialExchangeRateMantissa_", "type": "uint256", }, {"internalType": "string", "name": "name_", "type": "string"}, {"internalType": "string", "name": "symbol_", "type": "string"}, {"internalType": "uint8", "name": "decimals_", "type": "uint8"}, {"internalType": "address payable", "name": "admin_", "type": "address"}, {"internalType": "address", "name": "implementation_", "type": "address"}, { "internalType": "bytes", "name": "becomeImplementationData", "type": "bytes", }, ], "payable": False, "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint256", "name": "cashPrior", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "interestAccumulated", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "borrowIndex", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "totalBorrows", "type": "uint256", }, ], "name": "AccrueInterest", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": True, "internalType": "address", "name": "spender", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "borrower", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "borrowAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "accountBorrows", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "totalBorrows", "type": "uint256", }, ], "name": "Borrow", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint256", "name": "error", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "info", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "detail", "type": "uint256", }, ], "name": "Failure", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "liquidator", "type": "address", }, { "indexed": False, "internalType": "address", "name": "borrower", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "repayAmount", "type": "uint256", }, { "indexed": False, "internalType": "address", "name": "cTokenCollateral", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "seizeTokens", "type": "uint256", }, ], "name": "LiquidateBorrow", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "minter", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "mintAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "mintTokens", "type": "uint256", }, ], "name": "Mint", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "oldAdmin", "type": "address", }, { "indexed": False, "internalType": "address", "name": "newAdmin", "type": "address", }, ], "name": "NewAdmin", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "contract ComptrollerInterface", "name": "oldComptroller", "type": "address", }, { "indexed": False, "internalType": "contract ComptrollerInterface", "name": "newComptroller", "type": "address", }, ], "name": "NewComptroller", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "oldImplementation", "type": "address", }, { "indexed": False, "internalType": "address", "name": "newImplementation", "type": "address", }, ], "name": "NewImplementation", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "contract InterestRateModel", "name": "oldInterestRateModel", "type": "address", }, { "indexed": False, "internalType": "contract InterestRateModel", "name": "newInterestRateModel", "type": "address", }, ], "name": "NewMarketInterestRateModel", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "oldPendingAdmin", "type": "address", }, { "indexed": False, "internalType": "address", "name": "newPendingAdmin", "type": "address", }, ], "name": "NewPendingAdmin", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "uint256", "name": "oldReserveFactorMantissa", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "newReserveFactorMantissa", "type": "uint256", }, ], "name": "NewReserveFactor", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "redeemer", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "redeemAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "redeemTokens", "type": "uint256", }, ], "name": "Redeem", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "payer", "type": "address", }, { "indexed": False, "internalType": "address", "name": "borrower", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "repayAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "accountBorrows", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "totalBorrows", "type": "uint256", }, ], "name": "RepayBorrow", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "benefactor", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "addAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "newTotalReserves", "type": "uint256", }, ], "name": "ReservesAdded", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": False, "internalType": "address", "name": "admin", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "reduceAmount", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "newTotalReserves", "type": "uint256", }, ], "name": "ReservesReduced", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "from", "type": "address", }, { "indexed": True, "internalType": "address", "name": "to", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amount", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, {"payable": True, "stateMutability": "payable", "type": "fallback"}, { "constant": False, "inputs": [], "name": "_acceptAdmin", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "uint256", "name": "addAmount", "type": "uint256"}], "name": "_addReserves", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "reduceAmount", "type": "uint256"} ], "name": "_reduceReserves", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ { "internalType": "contract ComptrollerInterface", "name": "newComptroller", "type": "address", } ], "name": "_setComptroller", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "implementation_", "type": "address"}, {"internalType": "bool", "name": "allowResign", "type": "bool"}, { "internalType": "bytes", "name": "becomeImplementationData", "type": "bytes", }, ], "name": "_setImplementation", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ { "internalType": "contract InterestRateModel", "name": "newInterestRateModel", "type": "address", } ], "name": "_setInterestRateModel", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ { "internalType": "address payable", "name": "newPendingAdmin", "type": "address", } ], "name": "_setPendingAdmin", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ { "internalType": "uint256", "name": "newReserveFactorMantissa", "type": "uint256", } ], "name": "_setReserveFactor", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "accrualBlockNumber", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [], "name": "accrueInterest", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "admin", "outputs": [{"internalType": "address payable", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}, ], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "owner", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [{"internalType": "address", "name": "owner", "type": "address"}], "name": "balanceOfUnderlying", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "borrowAmount", "type": "uint256"} ], "name": "borrow", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "borrowBalanceCurrent", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "borrowBalanceStored", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "borrowIndex", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "borrowRatePerBlock", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "comptroller", "outputs": [ { "internalType": "contract ComptrollerInterface", "name": "", "type": "address", } ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "decimals", "outputs": [{"internalType": "uint8", "name": "", "type": "uint8"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [{"internalType": "bytes", "name": "data", "type": "bytes"}], "name": "delegateToImplementation", "outputs": [{"internalType": "bytes", "name": "", "type": "bytes"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "bytes", "name": "data", "type": "bytes"}], "name": "delegateToViewImplementation", "outputs": [{"internalType": "bytes", "name": "", "type": "bytes"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [], "name": "exchangeRateCurrent", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "exchangeRateStored", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "getAccountSnapshot", "outputs": [ {"internalType": "uint256", "name": "", "type": "uint256"}, {"internalType": "uint256", "name": "", "type": "uint256"}, {"internalType": "uint256", "name": "", "type": "uint256"}, {"internalType": "uint256", "name": "", "type": "uint256"}, ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getCash", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "implementation", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "interestRateModel", "outputs": [ { "internalType": "contract InterestRateModel", "name": "", "type": "address", } ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "isCToken", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "borrower", "type": "address"}, {"internalType": "uint256", "name": "repayAmount", "type": "uint256"}, { "internalType": "contract CTokenInterface", "name": "cTokenCollateral", "type": "address", }, ], "name": "liquidateBorrow", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "mintAmount", "type": "uint256"} ], "name": "mint", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "name", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "pendingAdmin", "outputs": [{"internalType": "address payable", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "redeemTokens", "type": "uint256"} ], "name": "redeem", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "redeemAmount", "type": "uint256"} ], "name": "redeemUnderlying", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "repayAmount", "type": "uint256"} ], "name": "repayBorrow", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "reserveFactorMantissa", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "liquidator", "type": "address"}, {"internalType": "address", "name": "borrower", "type": "address"}, {"internalType": "uint256", "name": "seizeTokens", "type": "uint256"}, ], "name": "seize", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "supplyRatePerBlock", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "symbol", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "totalBorrows", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [], "name": "totalBorrowsCurrent", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "totalReserves", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "src", "type": "address"}, {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}, ], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "underlying", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, ]
/safe_eth_py_suraneti-5.4.3-py3-none-any.whl/gnosis/eth/oracles/abis/cream_abis.py
0.577495
0.492249
cream_abis.py
pypi
balancer_pool_abi = [ { "inputs": [], "payable": False, "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "src", "type": "address", }, { "indexed": True, "internalType": "address", "name": "dst", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amt", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": True, "inputs": [ { "indexed": True, "internalType": "bytes4", "name": "sig", "type": "bytes4", }, { "indexed": True, "internalType": "address", "name": "caller", "type": "address", }, { "indexed": False, "internalType": "bytes", "name": "data", "type": "bytes", }, ], "name": "LOG_CALL", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "caller", "type": "address", }, { "indexed": True, "internalType": "address", "name": "tokenOut", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "tokenAmountOut", "type": "uint256", }, ], "name": "LOG_EXIT", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "caller", "type": "address", }, { "indexed": True, "internalType": "address", "name": "tokenIn", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "tokenAmountIn", "type": "uint256", }, ], "name": "LOG_JOIN", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "caller", "type": "address", }, { "indexed": True, "internalType": "address", "name": "tokenIn", "type": "address", }, { "indexed": True, "internalType": "address", "name": "tokenOut", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "tokenAmountIn", "type": "uint256", }, { "indexed": False, "internalType": "uint256", "name": "tokenAmountOut", "type": "uint256", }, ], "name": "LOG_SWAP", "type": "event", }, { "anonymous": False, "inputs": [ { "indexed": True, "internalType": "address", "name": "src", "type": "address", }, { "indexed": True, "internalType": "address", "name": "dst", "type": "address", }, { "indexed": False, "internalType": "uint256", "name": "amt", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "constant": True, "inputs": [], "name": "BONE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "BPOW_PRECISION", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "EXIT_FEE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "INIT_POOL_SUPPLY", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_BOUND_TOKENS", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_BPOW_BASE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_FEE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_IN_RATIO", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_OUT_RATIO", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_TOTAL_WEIGHT", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MAX_WEIGHT", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MIN_BALANCE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MIN_BOUND_TOKENS", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MIN_BPOW_BASE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MIN_FEE", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "MIN_WEIGHT", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "address", "name": "src", "type": "address"}, {"internalType": "address", "name": "dst", "type": "address"}, ], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amt", "type": "uint256"}, ], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "whom", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "balance", "type": "uint256"}, {"internalType": "uint256", "name": "denorm", "type": "uint256"}, ], "name": "bind", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenBalanceOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcInGivenOut", "outputs": [ {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenBalanceOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcOutGivenIn", "outputs": [ {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightOut", "type": "uint256"}, {"internalType": "uint256", "name": "poolSupply", "type": "uint256"}, {"internalType": "uint256", "name": "totalWeight", "type": "uint256"}, {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcPoolInGivenSingleOut", "outputs": [ {"internalType": "uint256", "name": "poolAmountIn", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightIn", "type": "uint256"}, {"internalType": "uint256", "name": "poolSupply", "type": "uint256"}, {"internalType": "uint256", "name": "totalWeight", "type": "uint256"}, {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcPoolOutGivenSingleIn", "outputs": [ {"internalType": "uint256", "name": "poolAmountOut", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightIn", "type": "uint256"}, {"internalType": "uint256", "name": "poolSupply", "type": "uint256"}, {"internalType": "uint256", "name": "totalWeight", "type": "uint256"}, {"internalType": "uint256", "name": "poolAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcSingleInGivenPoolOut", "outputs": [ {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightOut", "type": "uint256"}, {"internalType": "uint256", "name": "poolSupply", "type": "uint256"}, {"internalType": "uint256", "name": "totalWeight", "type": "uint256"}, {"internalType": "uint256", "name": "poolAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcSingleOutGivenPoolIn", "outputs": [ {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "uint256", "name": "tokenBalanceIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightIn", "type": "uint256"}, {"internalType": "uint256", "name": "tokenBalanceOut", "type": "uint256"}, {"internalType": "uint256", "name": "tokenWeightOut", "type": "uint256"}, {"internalType": "uint256", "name": "swapFee", "type": "uint256"}, ], "name": "calcSpotPrice", "outputs": [ {"internalType": "uint256", "name": "spotPrice", "type": "uint256"} ], "payable": False, "stateMutability": "pure", "type": "function", }, { "constant": True, "inputs": [], "name": "decimals", "outputs": [{"internalType": "uint8", "name": "", "type": "uint8"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amt", "type": "uint256"}, ], "name": "decreaseApproval", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "poolAmountIn", "type": "uint256"}, {"internalType": "uint256[]", "name": "minAmountsOut", "type": "uint256[]"}, ], "name": "exitPool", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenOut", "type": "address"}, {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "maxPoolAmountIn", "type": "uint256"}, ], "name": "exitswapExternAmountOut", "outputs": [ {"internalType": "uint256", "name": "poolAmountIn", "type": "uint256"} ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenOut", "type": "address"}, {"internalType": "uint256", "name": "poolAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "minAmountOut", "type": "uint256"}, ], "name": "exitswapPoolAmountIn", "outputs": [ {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"} ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [], "name": "finalize", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "getBalance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getColor", "outputs": [{"internalType": "bytes32", "name": "", "type": "bytes32"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getController", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getCurrentTokens", "outputs": [ {"internalType": "address[]", "name": "tokens", "type": "address[]"} ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "getDenormalizedWeight", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getFinalTokens", "outputs": [ {"internalType": "address[]", "name": "tokens", "type": "address[]"} ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "getNormalizedWeight", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getNumTokens", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "address", "name": "tokenOut", "type": "address"}, ], "name": "getSpotPrice", "outputs": [ {"internalType": "uint256", "name": "spotPrice", "type": "uint256"} ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "address", "name": "tokenOut", "type": "address"}, ], "name": "getSpotPriceSansFee", "outputs": [ {"internalType": "uint256", "name": "spotPrice", "type": "uint256"} ], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getSwapFee", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "getTotalDenormalizedWeight", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "gulp", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amt", "type": "uint256"}, ], "name": "increaseApproval", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [{"internalType": "address", "name": "t", "type": "address"}], "name": "isBound", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "isFinalized", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "isPublicSwap", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "uint256", "name": "poolAmountOut", "type": "uint256"}, {"internalType": "uint256[]", "name": "maxAmountsIn", "type": "uint256[]"}, ], "name": "joinPool", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "minPoolAmountOut", "type": "uint256"}, ], "name": "joinswapExternAmountIn", "outputs": [ {"internalType": "uint256", "name": "poolAmountOut", "type": "uint256"} ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "uint256", "name": "poolAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "maxAmountIn", "type": "uint256"}, ], "name": "joinswapPoolAmountOut", "outputs": [ {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"} ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "name", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256", "name": "balance", "type": "uint256"}, {"internalType": "uint256", "name": "denorm", "type": "uint256"}, ], "name": "rebind", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "address", "name": "manager", "type": "address"}], "name": "setController", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "bool", "name": "public_", "type": "bool"}], "name": "setPublicSwap", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "uint256", "name": "swapFee", "type": "uint256"}], "name": "setSwapFee", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"}, {"internalType": "address", "name": "tokenOut", "type": "address"}, {"internalType": "uint256", "name": "minAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "maxPrice", "type": "uint256"}, ], "name": "swapExactAmountIn", "outputs": [ {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "spotPriceAfter", "type": "uint256"}, ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "tokenIn", "type": "address"}, {"internalType": "uint256", "name": "maxAmountIn", "type": "uint256"}, {"internalType": "address", "name": "tokenOut", "type": "address"}, {"internalType": "uint256", "name": "tokenAmountOut", "type": "uint256"}, {"internalType": "uint256", "name": "maxPrice", "type": "uint256"}, ], "name": "swapExactAmountOut", "outputs": [ {"internalType": "uint256", "name": "tokenAmountIn", "type": "uint256"}, {"internalType": "uint256", "name": "spotPriceAfter", "type": "uint256"}, ], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": True, "inputs": [], "name": "symbol", "outputs": [{"internalType": "string", "name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": True, "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": False, "stateMutability": "view", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amt", "type": "uint256"}, ], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [ {"internalType": "address", "name": "src", "type": "address"}, {"internalType": "address", "name": "dst", "type": "address"}, {"internalType": "uint256", "name": "amt", "type": "uint256"}, ], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": False, "stateMutability": "nonpayable", "type": "function", }, { "constant": False, "inputs": [{"internalType": "address", "name": "token", "type": "address"}], "name": "unbind", "outputs": [], "payable": False, "stateMutability": "nonpayable", "type": "function", }, ]
/safe_eth_py_suraneti-5.4.3-py3-none-any.whl/gnosis/eth/oracles/abis/balancer_abis.py
0.493897
0.450299
balancer_abis.py
pypi