nucypher.blockchain

Submodules

class BaseEconomics(initial_supply: int, total_supply: int, issuance_decay_coefficient: int, lock_duration_coefficient_1: int, lock_duration_coefficient_2: int, maximum_rewarded_periods: int, first_phase_supply: int, first_phase_max_issuance: int, hours_per_period: int = 24, minimum_locked_periods: int = 30, minimum_allowed_locked: int = 15000000000000000000000, maximum_allowed_locked: int = 30000000000000000000000000, minimum_worker_periods: int = 2, hash_algorithm: int = 1, base_penalty: int = 2, penalty_history_coefficient: int = 0, percentage_penalty_coefficient: int = 100000, reward_coefficient: int = 2, worklock_supply: int = 225000000000000000000000000, bidding_start_date: int = 1598918400, bidding_end_date: int = 1601337599, cancellation_end_date: int = 1601510399, worklock_boosting_refund_rate: int = 800, worklock_commitment_duration: int = 180, worklock_min_allowed_bid: int = 5000000000000000000)

Bases: object

A representation of a contract deployment set’s constructor parameters, and the calculations used to generate those values from high-level human-understandable parameters.

Formula for staking in one period for the second phase: (totalSupply - currentSupply) * (lockedValue / totalLockedValue) * (k1 + allLockedPeriods) / d / k2

d - Coefficient which modifies the rate at which the maximum issuance decays k1 - Numerator of the locking duration coefficient k2 - Denominator of the locking duration coefficient

if allLockedPeriods > maximum_rewarded_periods then allLockedPeriods = maximum_rewarded_periods kappa * log(2) / halving_delay === (k1 + allLockedPeriods) / d

nunits_per_token = 1000000000000000000
HASH_ALGORITHM_KECCAK256 = 0
HASH_ALGORITHM_SHA256 = 1
HASH_ALGORITHM_RIPEMD160 = 2
class MayaDT(epoch)

Bases: object

The Maya Datetime object.

add(**kwargs)

Returns a new MayaDT object with the given offsets.

property date
datetime(to_timezone=None, naive=False)

Returns a timezone-aware datetime… Defaulting to UTC (as it should).

Keyword Arguments
  • {str} -- timezone to convert to (default (to_timezone) – None/UTC)

  • {bool} -- if True, (naive) – the tzinfo is simply dropped (default: False)

property day
property epoch
classmethod from_datetime(*args, **kwargs)
classmethod from_iso8601(iso8601_string)

Returns MayaDT instance from iso8601 string.

static from_rfc2822(rfc2822_string)

Returns MayaDT instance from rfc2822 string.

static from_rfc3339(rfc3339_string)

Returns MayaDT instance from rfc3339 string.

classmethod from_struct(*args, **kwargs)
property hour
iso8601()

Returns an ISO 8601 representation of the MayaDT.

local_datetime()

Returns a local timezone-aware datetime object

It’s the same as: mayaDt.datetime(to_timezone=mayaDt.local_timezone)

property local_timezone

Returns the name of the local timezone.

property microsecond
property minute
property month
rfc2822()

Returns an RFC 2822 representation of the MayaDT.

rfc3339()

Returns an RFC 3339 representation of the MayaDT.

property second
slang_date(locale='en')

“Returns human slang representation of date.

Keyword Arguments

-- locale to translate to, e.g. 'fr' for french. (locale) – (default: ‘en’ - English)

slang_time(locale='en')

“Returns human slang representation of time.

Keyword Arguments

-- locale to translate to, e.g. 'fr' for french. (locale) – (default: ‘en’ - English)

snap(instruction)

Returns a new MayaDT object modified by the given instruction.

Powered by snaptime. See https://github.com/zartstrom/snaptime for a complete documentation about the snaptime instructions.

subtract(**kwargs)

Returns a new MayaDT object with the given offsets.

subtract_date(**kwargs)

Returns a timedelta object with the duration between the dates

property timezone

Returns the UTC tzinfo name. It’s always UTC. Always.

property week
property weekday

Return the day of the week as an integer.

Monday is 1 and Sunday is 7.

property year
class Web3(provider: Optional[web3.providers.base.BaseProvider] = None, middlewares: Optional[Sequence[Any]] = None, modules: Optional[Dict[str, Sequence[Any]]] = None, ens: ens.main.ENS = <web3._utils.empty.Empty object>)

Bases: object

class EthereumTesterProvider(ethereum_tester: Optional[EthereumTester] = None, api_endpoints: Optional[Dict[str, Dict[str, Callable[[…], web3.types.RPCResponse]]]] = None)

Bases: web3.providers.base.BaseProvider

api_endpoints = None
ethereum_tester = None
isConnected() → typing_extensions.Literal[True][True]
make_request(method: NewType.<locals>.new_type, params: Any) → web3.types.RPCResponse
middlewares = (<function default_transaction_fields_middleware>, <function construct_web3_formatting_middleware.<locals>.formatter_middleware>)
class HTTPProvider(endpoint_uri: Union[NewType.<locals>.new_type, str, None] = None, request_kwargs: Optional[Any] = None, session: Optional[Any] = None)

Bases: web3.providers.base.JSONBaseProvider

endpoint_uri = None
get_request_headers() → Dict[str, str]
get_request_kwargs() → Iterable[Tuple[str, Any]]
logger = <Logger web3.providers.HTTPProvider (WARNING)>
make_request(method: NewType.<locals>.new_type, params: Any) → web3.types.RPCResponse
class IPCProvider(ipc_path: Union[str, pathlib.Path] = None, timeout: int = 10, *args: Any, **kwargs: Any)

Bases: web3.providers.base.JSONBaseProvider

logger = <Logger web3.providers.IPCProvider (WARNING)>
make_request(method: NewType.<locals>.new_type, params: Any) → web3.types.RPCResponse
class Iban(iban: str)

Bases: object

address() → Union[str, NewType.<locals>.new_type]

Should be called to get client direct address

@method address @returns {String} client direct address

checksum()str

Should be called to get iban checksum Uses the mod-97-10 checksumming protocol (ISO/IEC 7064:2003)

@method checksum @returns {String} checksum

client()str

Should be called to get client identifier within institution eg. GAVOFYORK

@method client @returns {String} client identifier

static createIndirect(options: web3.iban.IbanOptions) → web3.iban.Iban

Should be used to create IBAN object for given institution and identifier

@method createIndirect @param {Object} options, required options are “institution” and “identifier” @return {Iban} the IBAN object

static fromAddress(address: Union[NewType.<locals>.new_type, NewType.<locals>.new_type]) → web3.iban.Iban

This method should be used to create an iban object from ethereum address

@method fromAddress @param {String} address @return {Iban} the IBAN object

static fromBban(bban: str) → web3.iban.Iban

Convert the passed BBAN to an IBAN for this country specification. Please note that <i>”generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account”</i>. This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits

@method fromBban @param {String} bban the BBAN to convert to IBAN @returns {Iban} the IBAN object

institution()str

Should be called to get institution identifier eg. XREG

@method institution @returns {String} institution identifier

isDirect()bool

Should be called to check if iban number is direct

@method isDirect @returns {Boolean} true if it is, otherwise false

isIndirect()bool

Should be called to check if iban number if indirect

@method isIndirect @returns {Boolean} true if it is, otherwise false

isValid()bool
toString()str
class RequestManager(web3: Web3, provider: Optional[web3.providers.base.BaseProvider] = None, middlewares: Optional[Sequence[Tuple[Callable[[Callable[[NewType.<locals>.new_type, Any], web3.types.RPCResponse], Web3], Any], str]]] = None)

Bases: object

async coro_request(method: Union[NewType.<locals>.new_type, Callable[[...], NewType.<locals>.new_type]], params: Any, error_formatters: Optional[Callable[[...], Any]] = None) → Any

Couroutine for making a request using the provider

static default_middlewares(web3: Web3) → List[Tuple[Callable[[Callable[[NewType.<locals>.new_type, Any], web3.types.RPCResponse], Web3], Any], str]]

List the default middlewares for the request manager. Leaving ens unspecified will prevent the middleware from resolving names.

logger = <Logger web3.RequestManager (WARNING)>
property provider
receive_async(request_id: uuid.UUID, *args: Any, **kwargs: Any) → NoReturn
receive_blocking(request_id: uuid.UUID, timeout: Optional[float] = None) → Any
request_async(raw_method: str, raw_params: Any)uuid.UUID
request_blocking(method: Union[NewType.<locals>.new_type, Callable[[...], NewType.<locals>.new_type]], params: Any, error_formatters: Optional[Callable[[...], Any]] = None) → Any

Make a synchronous request using the provider

web3: Web3 = None
class WebsocketProvider(endpoint_uri: Union[NewType.<locals>.new_type, str, None] = None, websocket_kwargs: Optional[Any] = None, websocket_timeout: int = 10)

Bases: web3.providers.base.JSONBaseProvider

async coro_make_request(request_data: bytes) → web3.types.RPCResponse
logger = <Logger web3.providers.WebsocketProvider (WARNING)>
make_request(method: NewType.<locals>.new_type, params: Any) → web3.types.RPCResponse
property api
property clientVersion
enable_strict_bytes_type_checking()None
enable_unstable_package_management_api()None
property ens
eth = None
static fromWei(number: int, unit: str) → Union[int, decimal.Decimal]

Takes a number of wei and converts it to any other ether unit.

geth = None
static isAddress(value: Any)bool

Checks if the given string in a supported value is an address in any of the known formats.

static isChecksumAddress(value: Any)bool
isConnected()bool
is_encodable(_type: str, value: Any)bool
static keccak(primitive: Union[bytes, int, bool, None] = None, text: Optional[str] = None, hexstr: Optional[NewType.<locals>.new_type] = None)bytes
property middleware_onion
net = None
parity = None
property pm
property provider
static sha3(primitive: Union[bytes, int, bool, None] = None, text: Optional[str] = None, hexstr: Optional[NewType.<locals>.new_type] = None)bytes
solidityKeccak(abi_types: List[str], values: List[Any])bytes

Executes keccak256 exactly as Solidity does. Takes list of abi_types as inputs – [uint24, int8[], bool] and list of corresponding values – [20, [-1, 5, 0], True]

soliditySha3(abi_types: List[str], values: List[Any])bytes
static toBytes(primitive: Union[bytes, int, bool] = None, hexstr: NewType.<locals>.new_type = None, text: str = None)bytes
static toChecksumAddress(value: AnyStr) → NewType.<locals>.new_type

Makes a checksum address given a supported format.

static toHex(primitive: Union[bytes, int, bool] = None, hexstr: NewType.<locals>.new_type = None, text: str = None) → NewType.<locals>.new_type

Auto converts any supported value into its hex representation. Trims leading zeros, as defined in: https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding

static toInt(primitive: Union[bytes, int, bool] = None, hexstr: NewType.<locals>.new_type = None, text: str = None)int

Converts value to its integer representation. Values are converted this way:

  • primitive:

    • bytes, bytearrays: big-endian integer

    • bool: True => 1, False => 0

  • hexstr: interpret hex as integer

  • text: interpret as string of digits, like ‘12’ => 12

static toJSON(obj: Dict[Any, Any])str

Convert a complex object (like a transaction object) to a JSON string

static toText(primitive: Union[bytes, int, bool] = None, hexstr: NewType.<locals>.new_type = None, text: str = None)str
static toWei(number: Union[int, float, str, decimal.Decimal], unit: str)int

Takes a number of a unit and converts it to wei.

property erc20_initial_supply
property erc20_reward_supply
property erc20_total_supply
property staking_deployment_parameters

Cast coefficient attributes to uint256 compatible type for solidity+EVM

property slashing_deployment_parameters

Cast coefficient attributes to uint256 compatible type for solidity+EVM

property worklock_deployment_parameters

0 token - Token contract 1 escrow - Staking Escrow contract … 2 startBidDate - Timestamp when bidding starts 3 endBidDate - Timestamp when bidding will end 4 endCancellationDate - Timestamp when cancellation window will end 5 boostingRefund - Coefficient to boost refund ETH 6 stakingPeriods - Duration of tokens locking 7 minAllowedBid - Minimum allowed ETH amount for bidding

property bidding_duration

Returns the total bidding window duration in seconds.

property cancellation_window_duration

Returns the total cancellation window duration in seconds.

class StandardTokenEconomics(initial_supply: int = 1000000000000000000000000000, first_phase_supply: int = 1829579800000000000000000000, first_phase_duration: int = 5, decay_half_life: int = 2, reward_saturation: int = 1, small_stake_multiplier: decimal.Decimal = Decimal('0.5'), **kwargs)

Bases: nucypher.blockchain.economics.BaseEconomics

Formula for staking in one period for the second phase: (totalSupply - currentSupply) * (lockedValue / totalLockedValue) * (k1 + allLockedPeriods) / d / k2

d - Coefficient which modifies the rate at which the maximum issuance decays k1 - Numerator of the locking duration coefficient k2 - Denominator of the locking duration coefficient

if allLockedPeriods > maximum_rewarded_periods then allLockedPeriods = maximum_rewarded_periods kappa * log(2) / halving_delay === (k1 + allLockedPeriods) / d / k2

…but also…

kappa = small_stake_multiplier + (1 - small_stake_multiplier) * min(T, T1) / T1 where allLockedPeriods == min(T, T1)

Academic Reference:

NuCypher: Mining & Staking Economics - Michael Egorov, MacLane Wilkison, NuCypher <https://github.com/nucypher/mining-paper/blob/master/mining-paper.pdf>

first_phase_final_period()int

Returns final period for first phase, assuming that all stakers locked tokens for more than 365 days.

token_supply_at_period(period: int)int

Returns predicted total supply at specified period, assuming that all stakers locked tokens for more than 365 days.

cumulative_rewards_at_period(period: int)int
rewards_during_period(period: int)int
class EconomicsFactory

Bases: object

classmethod get_economics(registry: nucypher.blockchain.eth.registry.BaseContractRegistry)nucypher.blockchain.economics.BaseEconomics
static retrieve_from_blockchain(registry: nucypher.blockchain.eth.registry.BaseContractRegistry)nucypher.blockchain.economics.BaseEconomics