Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add documentation for self #1787

Merged
merged 2 commits into from
Dec 30, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion docs/built-in-functions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,13 @@ contracts.

.. py:function:: ecrecover(hash: bytes32, v: uint256, r: uint256, s: uint256) -> address

Takes a signed hash and vrs and returns the public key of the signer.
Recovers the address associated with the public key from the given elliptic curve signature.

* ``r``: first 32 bytes of signature
* ``s``: second 32 bytes of signature
* ``v``: final 1 byte of signature

Returns the associated address, or ``0`` on error.

.. py:function:: ecadd(a: uint256[2], b: uint256[2]) -> uint256[2]

Expand Down
136 changes: 94 additions & 42 deletions docs/constants-and-vars.rst
Original file line number Diff line number Diff line change
@@ -1,10 +1,85 @@
.. index:: type

.. _types:

Constants and Environment Variables
Environment Variables and Constants
***********************************

.. _types-env-vars:

Environment Variables
=====================

Environment variables always exist in the namespace and are primarily used to provide information about the blockchain or current transaction.

Block and Transaction Properties
--------------------------------

==================== ================ =============================================
Name Type Value
==================== ================ =============================================
``block.coinbase`` ``address`` Current block miner’s address
``block.difficulty`` ``uint256`` Current block difficulty
``block.number`` ``uint256`` Current block number
``block.prevhash`` ``bytes32`` Equivalent to ``blockhash(block.number - 1)``
``block.timestamp`` ``uint256`` Current block epoch timestamp
``msg.gas`` ``uint256`` Remaining gas
``msg.sender`` ``address`` Sender of the message (current call)
``msg.value`` ``uint256(wei)`` Number of wei sent with the message
``tx.origin`` ``address`` Sender of the transaction (full call chain)
==================== ================ =============================================

.. note::

``msg.sender`` and ``msg.value`` can only be accessed from public functions. If you require these values within a private function they must be passed as parameters.

.. _constants-self:

The self Variable
-----------------

``self`` is an environment variable used to reference a contract from within itself. Along with the normal :ref:`address<address>` members, ``self`` allows you to read and write to state variables and to call private functions within the contract.

==================== ================ ==========================
Name Type Value
==================== ================ ==========================
``self`` ``address`` Current contract's address
``self.balance`` ``uint256(wei)`` Current contract's balance
==================== ================ ==========================

Accessing State Variables
~~~~~~~~~~~~~~~~~~~~~~~~~

``self`` is used to access a contract's :ref:`state variables<structure-state-variables>`, as shown in the following example:

.. code-block:: python

state_var: uint256

@public
def set_var(value: uint256) -> bool:
self.state_var = value
return True

@public
@constant
def get_var() -> uint256:
return self.state_var


Calling Private Functions
~~~~~~~~~~~~~~~~~~~~~~~~~

``self`` is also used to call :ref:`private functions<structure-functions-private>` within a contract:

.. code-block:: python

@private
def _times_two(amount: uint256) -> uint256:
return amount * 2

@public
def calculate(amount: uint256) -> uint256:
return self._times_two(amount)

.. _types-constants:

Built In Constants
Expand All @@ -31,50 +106,27 @@ Custom Constants
Custom constants can be defined at a global level in Vyper. To define a constant make use of the ``constant`` keyword.

**Example:**
::

TOTAL_SUPPLY: constant(uint256) = 10000000
total_supply: public(uint256)
.. code-block:: python

@public
def __init__():
self.total_supply = TOTAL_SUPPLY
TOTAL_SUPPLY: constant(uint256) = 10000000
total_supply: public(uint256)

**Advanced Example:**
::

units: {
share: "Share unit"
}

MAX_SHARES: constant(uint256(share)) = 1000
SHARE_PRICE: constant(uint256(wei/share)) = 5

@public
def market_cap() -> uint256(wei):
return MAX_SHARES * SHARE_PRICE
@public
def __init__():
self.total_supply = TOTAL_SUPPLY

.. _types-env-vars:

Environment Variables
=====================
**Advanced Example:**

Environment variables always exist in the namespace and are used to provide information about the blockchain or current transaction.
.. code-block:: python

.. note::
units: {
share: "Share unit"
}

``msg.sender`` and ``msg.value`` can only be accessed from public functions. If you require these values within a private function they must be passed as parameters.
MAX_SHARES: constant(uint256(share)) = 1000
SHARE_PRICE: constant(uint256(wei/share)) = 5

==================== ================ =============================================
Name Type Value
==================== ================ =============================================
``block.coinbase`` ``address`` Current block miner’s address
``block.difficulty`` ``uint256`` Current block difficulty
``block.number`` ``uint256`` Current block number
``block.prevhash`` ``bytes32`` Equivalent to ``blockhash(block.number - 1)``
``block.timestamp`` ``uint256`` Current block epoch timestamp
``msg.gas`` ``uint256`` Remaining gas
``msg.sender`` ``address`` Sender of the message (current call)
``msg.value`` ``uint256(wei)`` Number of wei sent with the message
``tx.origin`` ``address`` Sender of the transaction (full call chain)
==================== ================ =============================================
@public
def market_cap() -> uint256(wei):
return MAX_SHARES * SHARE_PRICE
5 changes: 2 additions & 3 deletions docs/contributing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ Style Guide
===========


Vyper's codebase follows the
Vyper's codebase follows the
`Snake Charmer's Style Guide <https://github.com/ethereum/snake-charmers-tactical-manual/blob/master/style-guide.md>`_.
Some of the things not covered by style guide that we maintain in our codebase is the use of
`f-strings <https://github.com/vyperlang/vyper/issues/1567>`_ across the repository (when helpful for clarity),
Expand All @@ -71,8 +71,7 @@ and instead, ``git rebase`` your branch.

**Implement Features**

If you are writing a new feature, please ensure you write appropriate
Boost test cases and place them under ``tests/``.
If you are writing a new feature, please ensure you write appropriate Pytest test cases and place them under ``tests/``.

If you are making a larger change, please consult first with the Gitter channel.

Expand Down
55 changes: 17 additions & 38 deletions docs/index.rst
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
.. Vyper documentation master file, created by
sphinx-quickstart on Wed Jul 26 11:18:29 2017.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.

Vyper
#####

Expand All @@ -16,47 +11,31 @@ Vyper is a contract-oriented, pythonic programming language that targets the `Et
Principles and Goals
********************

* **Security:** It should be possible and natural to build secure smart-contracts in Vyper.
* **Language and compiler simplicity:** The language and the compiler implementation should strive to be simple.
* **Auditability:** Vyper code should be maximally human-readable. Furthermore, it should be maximally difficult to write misleading code. Simplicity for the reader
is more important than simplicity for the writer, and simplicity for readers with low prior experience with Vyper (and low prior experience with programming in
general) is particularly important.
* **Security**: It should be possible and natural to build secure smart-contracts in Vyper.
* **Language and compiler simplicity**: The language and the compiler implementation should strive to be simple.
* **Auditability**: Vyper code should be maximally human-readable. Furthermore, it should be maximally difficult to write misleading code. Simplicity for the reader is more important than simplicity for the writer, and simplicity for readers with low prior experience with Vyper (and low prior experience with programming in general) is particularly important.

Because of this Vyper aims to provide the following features:
Because of this Vyper provides the following features:

* **Bounds and overflow checking:** On array accesses as well as on arithmetic level.
* **Bounds and overflow checking**: On array accesses and arithmetic.
* **Support for signed integers and decimal fixed point numbers**
* **Decidability:** It should be possible to compute a precise upper bound for the gas consumption of any function call.
* **Strong typing:** Including support for units (e.g. timestamp, timedelta, seconds, wei, wei per second, meters per second squared).
* **Decidability**: It is possible to compute a precise upper bound for the gas consumption of any Vyper function call.
* **Strong typing**: Including support for units (e.g. timestamp, timedelta, seconds, wei, wei per second, meters per second squared).
* **Small and understandable compiler code**
* **Limited support for pure functions:** Anything marked constant is not allowed to change the state.
* **Limited support for pure functions**: Anything marked constant is not allowed to change the state.

Following the principles and goals, Vyper **does not** provide the following features:

* **Modifiers**: For example in Solidity you can define a ``function foo() mod1 { ... }``, where ``mod1`` can be defined elsewhere in the code to include a check that is done before execution,
a check that is done after execution, some state changes, or possibly other things. Vyper does not have this, because it makes it too easy to write misleading code. ``mod1`` just looks
too innocuous for something that could add arbitrary pre-conditions, post-conditions or state changes. Also, it encourages people to write code where the execution jumps around the file,
harming auditability. The usual use case for a modifier is something that performs a single check before execution of a program; our recommendation is to simply inline these checks as asserts.
* **Class inheritance:** Class inheritance requires people to jump between multiple files to understand what a program is doing, and requires people to understand the rules of precedence in case of conflicts
("Which class's function 'X' is the one that's actually used?"). Hence, it makes code too complicated to understand which negatively impacts auditability.
* **Inline assembly:** Adding inline assembly would make it no longer possible to search for a variable name in order to find all instances where that variable is read or modified.
* **Function overloading** - This can cause lots of confusion on which function is called at any given time. Thus it's easier to write missleading code (``foo("hello")`` logs "hello" but ``foo("hello", "world")`` steals you funds).
Another problem with function overloading is that it makes the code much harder to search through as you have to keep track on which call refers to which function.
* **Operator overloading:** Operator overloading makes writing misleading code possible. For example "+" could be overloaded so that it executes commands that are not visible at a first glance, such as sending funds the
user did not want to send.
* **Recursive calling:** Recursive calling makes it impossible to set an upper bound on gas limits, opening the door for gas limit attacks.
* **Infinite-length loops:** Similar to recursive calling, infinite-length loops make it impossible to set an upper bound on gas limits, opening the door for gas limit attacks.
* **Binary fixed point:** Decimal fixed point is better, because any decimal fixed point value written as a literal in code has an exact representation, whereas with binary fixed point approximations are often required
(e.g. (0.2)\ :sub:`10` = (0.001100110011...)\ :sub:`2`, which needs to be truncated), leading to unintuitive results, e.g. in Python 0.3 + 0.3 + 0.3 + 0.1 != 1.


Some changes that may be considered after Metropolis when `STATICCALL <https://github.com/ethereum/EIPs/pull/214/files>`_ becomes available include:

* Forbidding state changes after non-static calls unless the address being non-statically called is explicitly marked "trusted". This would reduce risk of re-entrancy attacks.
* Forbidding "inline" non-static calls, e.g. `send(some_address, contract.do_something_and_return_a_weivalue())`, enforcing clear separation between "call to get a response" and "call to do something".
* **Modifiers**: For example in Solidity you can define a ``function foo() mod1 { ... }``, where ``mod1`` can be defined elsewhere in the code to include a check that is done before execution, a check that is done after execution, some state changes, or possibly other things. Vyper does not have this, because it makes it too easy to write misleading code. ``mod1`` just looks too innocuous for something that could add arbitrary pre-conditions, post-conditions or state changes. Also, it encourages people to write code where the execution jumps around the file, harming auditability. The usual use case for a modifier is something that performs a single check before execution of a program; our recommendation is to simply inline these checks as asserts.
* **Class inheritance**: Class inheritance requires people to jump between multiple files to understand what a program is doing, and requires people to understand the rules of precedence in case of conflicts ("Which class's function ``X`` is the one that's actually used?"). Hence, it makes code too complicated to understand which negatively impacts auditability.
* **Inline assembly**: Adding inline assembly would make it no longer possible to search for a variable name in order to find all instances where that variable is read or modified.
* **Function overloading**: This can cause lots of confusion on which function is called at any given time. Thus it's easier to write missleading code (``foo("hello")`` logs "hello" but ``foo("hello", "world")`` steals your funds). Another problem with function overloading is that it makes the code much harder to search through as you have to keep track on which call refers to which function.
* **Operator overloading**: Operator overloading makes writing misleading code possible. For example ``+`` could be overloaded so that it executes commands that are not visible at a first glance, such as sending funds the user did not want to send.
* **Recursive calling**: Recursive calling makes it impossible to set an upper bound on gas limits, opening the door for gas limit attacks.
* **Infinite-length loops**: Similar to recursive calling, infinite-length loops make it impossible to set an upper bound on gas limits, opening the door for gas limit attacks.
* **Binary fixed point**: Decimal fixed point is better, because any decimal fixed point value written as a literal in code has an exact representation, whereas with binary fixed point approximations are often required (e.g. (0.2)\ :sub:`10` = (0.001100110011...)\ :sub:`2`, which needs to be truncated), leading to unintuitive results, e.g. in Python 0.3 + 0.3 + 0.3 + 0.1 != 1.

Vyper does NOT strive to be a 100% replacement for everything that can be done in Solidity; it will deliberately forbid things or make things harder if it deems fit to do so for the goal of
increasing security.
Vyper **does not** strive to be a 100% replacement for everything that can be done in Solidity; it will deliberately forbid things or make things harder if it deems fit to do so for the goal of increasing security.

Glossary
********
Expand Down
12 changes: 6 additions & 6 deletions docs/release-notes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Date released: 27-09-2019

The following VIPs were implemented for Beta 13:

- Add `vyper-json` compilation mode (VIP `#1520 <https://github.com/vyperlang/vyper/issues/1520>`_)
- Add ``vyper-json`` compilation mode (VIP `#1520 <https://github.com/vyperlang/vyper/issues/1520>`_)
- Environment variables and constants can now be used as default parameters (VIP `#1525 <https://github.com/vyperlang/vyper/issues/1525>`_)
- Require unitialized memory be set on creation (VIP `#1493 <https://github.com/vyperlang/vyper/issues/1493>`_)

Expand All @@ -41,7 +41,7 @@ Some of the bug and stability fixes:
- Type check for default params and arrays (`#1596 <https://github.com/vyperlang/vyper/pull/1596>`_)
- Fixed bug when using assertions inside for loops (`#1619 <https://github.com/vyperlang/vyper/pull/1619>`_)
- Fixed zero padding error for ABI encoder (`#1611 <https://github.com/vyperlang/vyper/pull/1611>`_)
- Check `calldatasize` before `calldataload` for function selector (`#1606 <https://github.com/vyperlang/vyper/pull/1606>`_)
- Check ``calldatasize`` before ``calldataload`` for function selector (`#1606 <https://github.com/vyperlang/vyper/pull/1606>`_)

v0.1.0-beta.12
**************
Expand Down Expand Up @@ -79,7 +79,7 @@ Beta 11 brings some performance and stability fixes.
- Improvements for Windows users (`#1486 <https://github.com/vyperlang/vyper/pull/1486>`_) (`#1488 <https://github.com/vyperlang/vyper/pull/1488>`_)
- Array copy optimisation (`#1487 <https://github.com/vyperlang/vyper/pull/1487>`_)
- Fixing ``@nonreentrant`` decorator for return statements (`#1532 <https://github.com/vyperlang/vyper/pull/1532>`_)
- `sha3` builtin function removed (`#1328 <https://github.com/vyperlang/vyper/issues/1328>`_)
- ``sha3`` builtin function removed (`#1328 <https://github.com/vyperlang/vyper/issues/1328>`_)
- Disallow conflicting method IDs (`#1530 <https://github.com/vyperlang/vyper/pull/1530>`_)
- Additional ``convert()`` supported types (`#1524 <https://github.com/vyperlang/vyper/pull/1524>`_) (`#1500 <https://github.com/vyperlang/vyper/pull/1500>`_)
- Equality operator for strings and bytes (`#1507 <https://github.com/vyperlang/vyper/pull/1507>`_)
Expand Down Expand Up @@ -110,9 +110,9 @@ v0.1.0-beta.9
Date released: 12-03-2019

- Add support for list constants (`#1211 <https://github.com/vyperlang/vyper/issues/1211>`_)
- Add sha256 function (`#1327 <https://github.com/vyperlang/vyper/issues/1327>`_)
- Renamed create_with_code_of to create_forwarder_to (`#1177 <https://github.com/vyperlang/vyper/issues/1177>`_)
- @nonreentrant Decorator (`#1204 <https://github.com/vyperlang/vyper/issues/1204>`_)
- Add ``sha256`` function (`#1327 <https://github.com/vyperlang/vyper/issues/1327>`_)
- Renamed ``create_with_code_of`` to ``create_forwarder_to`` (`#1177 <https://github.com/vyperlang/vyper/issues/1177>`_)
- ``@nonreentrant`` Decorator (`#1204 <https://github.com/vyperlang/vyper/issues/1204>`_)
- Add opcodes and opcodes_runtime flags to compiler (`#1255 <https://github.com/vyperlang/vyper/pull/1255>`_)
- Improved External contract call interfaces (`#885 <https://github.com/vyperlang/vyper/issues/885>`_)

Expand Down
Loading