internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: vyperlang/vyper

Issue:
[Question] Attack Vector described in Vipercoin's `approve` annotation
In [L89 of `vipercoin.v.py`](https://github.com/ethereum/viper/blob/master/examples/tokens/vipercoin.v.py#L89), the `approve` method has an annotation that begins like this

>To prevent attack vectors like the one described here and discussed here,

I don't see any description of the attack vectors described, perhaps there should be an external link here?  Point me in the right direction and I can make the PR for it. :)

Thanks!


Discussion:
[This](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md) is the page where the `note` is from.
Please have `described here` link to (https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/edit)
and `discussed here` link to (https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729)
Thanks a lot!

Resolving patch:
diff --git a/examples/tokens/vipercoin.v.py b/examples/tokens/vipercoin.v.py
--- a/examples/tokens/vipercoin.v.py
+++ b/examples/tokens/vipercoin.v.py
@@ -86,12 +86,15 @@ def transferFrom(_from: address, _to: address, _value: num(num256)) -> bool:
 # Allow _spender to withdraw from your account, multiple times, up to the _value amount.
 # If this function is called again it overwrites the current allowance with _value.
 #
-# NOTE: To prevent attack vectors like the one described here and discussed here,
-#       clients SHOULD make sure to create user interfaces in such a way that they
+# NOTE: We would like to prevent attack vectors like the one described here:
+#       https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/edit#heading=h.m9fhqynw2xvt
+#       and discussed here:
+#       https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
+#
+#       Clients SHOULD make sure to create user interfaces in such a way that they
 #       set the allowance first to 0 before setting it to another value for the
 #       same spender. THOUGH The contract itself shouldn't enforce it, to allow
 #       backwards compatilibilty with contracts deployed before.
-#
 @public
 def approve(_spender: address, _amount: num(num256)) -> bool:
 
@@ -101,7 +104,7 @@ def approve(_spender: address, _amount: num(num256)) -> bool:
     return True
 
 
-# Get the allowance an address has to spend anothers' token.
+# Get the allowance an address has to spend another's token.
 @public
 def allowance(_owner: address, _spender: address) -> num256:
 


Test patch:
Repository: vyperlang/vyper

Issue:
Failed to compile a for loop with a variable as a range() argument
This code compilation is failing with the next error message: _**"Repeat must have a nonzero positive integral number of rounds"**_.

`some_value = 4`
`for i in range(some_value):` 
`// do something`

The same situation is present if check that the value is grater than 0:

`some_value = 4`
`if some_value > 0:` 
`for i in range(some_value):` 
`// do something`

* viper Version: 0.0.2



Discussion:
This is by design, we do not allow looping over variable lengths. Doing so would allow for potentially infinite gas costs, violating a major precept of Viper's design (being able to estimate gas for all functions).

While I understand this may be a hassle, we have to find other ways to enable similar functionality without violating this precept e.g. stacks/queues as list types
I think in this circumstances the error message should describe the problem better. In the example above variable satisfies the "nonzero positive" restriction. 
Totally agree on that point. That error message doesn't say anything about how it was given a variable and that's why it failed to compile.
@DavidKnott
I'm on board with that, I'll make a PR for it.  @khotkevych Thanks a lot for making an issue!

Resolving patch:
diff --git a/viper/parser/stmt.py b/viper/parser/stmt.py
--- a/viper/parser/stmt.py
+++ b/viper/parser/stmt.py
@@ -182,7 +182,7 @@ def parse_for(self):
         # Type 1 for, eg. for i in range(10): ...
         if len(self.stmt.iter.args) == 1:
             if not isinstance(self.stmt.iter.args[0], ast.Num):
-                raise StructureException("Repeat must have a nonzero positive integral number of rounds", self.stmt.iter)
+                raise StructureException("Range only accepts literal values", self.stmt.iter)
             start = LLLnode.from_list(0, typ='num', pos=getpos(self.stmt))
             rounds = self.stmt.iter.args[0].n
         elif isinstance(self.stmt.iter.args[0], ast.Num) and isinstance(self.stmt.iter.args[1], ast.Num):
@@ -197,7 +197,7 @@ def parse_for(self):
             if ast.dump(self.stmt.iter.args[0]) != ast.dump(self.stmt.iter.args[1].left):
                 raise StructureException("Two-arg for statements of the form `for i in range(x, x + y): ...` must have x identical in both places: %r %r" % (ast.dump(self.stmt.iter.args[0]), ast.dump(self.stmt.iter.args[1].left)), self.stmt.iter)
             if not isinstance(self.stmt.iter.args[1].right, ast.Num):
-                raise StructureException("Repeat must have a nonzero positive integral number of rounds", self.stmt.iter.args[1])
+                raise StructureException("Range only accepts literal values", self.stmt.iter.args[1])
             start = Expr.parse_value_expr(self.stmt.iter.args[0], self.context)
             rounds = self.stmt.iter.args[1].right.n
         varname = self.stmt.target.id


Test patch:
Repository: vyperlang/vyper

Issue:
Viper LLL line that doesn't compile
### What's your issue about?

```python
LLLnode.from_list(['calldatacopy', 32, 0, ['calldatasize']])
```
results in
```python
parser_utils.py in __init__(self, value, args, typ, location, pos, annotation, mutable, add_gas_estimate)
     87                         size = self.args[2].value
     88                     else:
---> 89                         size = self.args[2].args[-1].value
     90                     self.gas += ceil32(size) // 32 * 3
     91                 # Gas limits in call

IndexError: list index out of range
```
(on current master)


Discussion:

Resolving patch:
diff --git a/viper/parser/parser_utils.py b/viper/parser/parser_utils.py
--- a/viper/parser/parser_utils.py
+++ b/viper/parser/parser_utils.py
@@ -83,10 +83,11 @@ def __init__(self, value, args=None, typ=None, location=None, pos=None, annotati
                     self.gas += 15000
                 # Dynamic gas cost: calldatacopy
                 elif self.value.upper() in ('CALLDATACOPY', 'CODECOPY'):
+                    size = 34000
                     if isinstance(self.args[2].value, int):
                         size = self.args[2].value
-                    else:
-                        size = self.args[2].args[-1].value
+                    elif isinstance(self.args[2], LLLnode) and len(self.args[2].args) > 0:
+                        size = self.args[2].args / [-1].value
                     self.gas += ceil32(size) // 32 * 3
                 # Gas limits in call
                 if self.value.upper() == 'CALL' and isinstance(self.args[0].value, int):


Test patch:
diff --git a/tests/compiler/test_calldatacopy.py b/tests/compiler/test_calldatacopy.py
new file mode 100644
--- /dev/null
+++ b/tests/compiler/test_calldatacopy.py
@@ -0,0 +1,6 @@
+import pytest
+
+
+def test_calldatacopy(get_contract_from_lll):
+    lll = ['calldatacopy', 32, 0, ['calldatasize']]
+    get_contract_from_lll(lll)
Repository: vyperlang/vyper

Issue:
"in" list doesn't check whether variable type matches the list subtype
### What's your issue about?
```
@public
def testin(x: address) -> bool:
    y = 1
    s = [1, 2, 3, 4]
    if x in s:
        return True
    return False
```
This program is allowed by the Viper compiler. However the type of the varialbe `x` doesn't match the list subtype `num`.

### How can it be fixed?

Add type check in `build_in_comparator`. Pay attention to the situation when list is of MixedType.

#### Cute Animal Picture

![image](https://user-images.githubusercontent.com/5641590/33868959-c58d5758-decb-11e7-8820-abf134b6c7f2.png)




Discussion:
@fubuloubu @DavidKnott if y'all verify this issue I can implement the fix.
What do you mean by verify? We were talking about this in gitter, and we agree it's a problem.
Oh my bad, I'll hop on Gitter. By verify I meant agree it's a problem 😄.

Resolving patch:
diff --git a/viper/parser/expr.py b/viper/parser/expr.py
--- a/viper/parser/expr.py
+++ b/viper/parser/expr.py
@@ -309,6 +309,8 @@ def build_in_comparator(self):
         left = Expr(self.expr.left, self.context).lll_node
         right = Expr(self.expr.comparators[0], self.context).lll_node
 
+        if left.typ.typ != right.typ.subtype.typ:
+            raise TypeMismatchException("%s cannot be in a list of %s" % (left.typ.typ, right.typ.subtype.typ))
         result_placeholder = self.context.new_placeholder(BaseType('bool'))
         setter = []
 


Test patch:
diff --git a/tests/parser/features/iteration/test_range_in.py b/tests/parser/features/iteration/test_range_in.py
--- a/tests/parser/features/iteration/test_range_in.py
+++ b/tests/parser/features/iteration/test_range_in.py
@@ -107,3 +107,15 @@ def is_owner() -> bool:
     # Owner in place 0 can be replaced.
     c.set_owner(0, t.a1)
     assert c.is_owner() is False
+
+
+def test_in_fails_when_types_dont_match(get_contract_with_gas_estimation, assert_tx_failed):
+    code = """
+@public
+def testin(x: address) -> bool:
+    s: num[4] = [1, 2, 3, 4]
+    if x in s:
+        return True
+    return False
+"""
+    assert_tx_failed(lambda: get_contract_with_gas_estimation(code), TypeMismatchException)
Repository: vyperlang/vyper

Issue:
Fix slice function
### What's your issue about?
Found a case where slice function breaks.

```python
def test_conv2(get_contract):
	code = """
@public
def ret10_slice() -> bytes <= 10:
	b: bytes <= 32 = concat(convert(65, 'bytes32'), '')
	`# return b
	c: bytes <= 10 = slice(b, start=31, len=1)
	return c
	"""

	c = get_contract(code)
	assert c.ret10_slice() == b'A'
```

### How can it be fixed?

#### Cute Animal Picture

![](https://i.ytimg.com/vi/MIJ6g1vpask/maxresdefault.jpg)


Discussion:

Resolving patch:
diff --git a/vyper/functions/functions.py b/vyper/functions/functions.py
--- a/vyper/functions/functions.py
+++ b/vyper/functions/functions.py
@@ -163,11 +163,12 @@ def _slice(expr, args, kwargs, context):
     copier = make_byte_slice_copier(placeholder_plus_32_node, adj_sub, ['add', '_length', 32], sub.typ.maxlen)
     # New maximum length in the type of the result
     newmaxlen = length.value if not len(length.args) else sub.typ.maxlen
+    maxlen = ['mload', Expr(sub, context=context).lll_node]  # Retrieve length of the bytes.
     out = ['with', '_start', start,
               ['with', '_length', length,
                   ['with', '_opos', ['add', placeholder_node, ['mod', '_start', 32]],
                        ['seq',
-                           ['assert', ['lt', ['add', '_start', '_length'], sub.typ.maxlen]],
+                           ['assert', ['le', ['add', '_start', '_length'], maxlen]],
                            copier,
                            ['mstore', '_opos', '_length'],
                            '_opos']]]]


Test patch:
diff --git a/tests/parser/functions/test_slice.py b/tests/parser/functions/test_slice.py
--- a/tests/parser/functions/test_slice.py
+++ b/tests/parser/functions/test_slice.py
@@ -100,3 +100,16 @@ def foo(inp: bytes <= 10, start: int128, len: int128) -> bytes <= 10:
         c.foo(b"badminton", 10, 0)
 
     print('Passed slice edge case test')
+
+
+def test_slice_at_end(get_contract):
+    code = """
+@public
+def ret10_slice() -> bytes <= 10:
+    b: bytes <= 32 = concat(convert(65, 'bytes32'), '')
+    c: bytes <= 10 = slice(b, start=31, len=1)
+    return c
+    """
+
+    c = get_contract(code)
+    assert c.ret10_slice() == b'A'
Repository: vyperlang/vyper

Issue:
List assignment test with mismatched number of elements incorrectly passes
As the title says.

https://github.com/ethereum/vyper/blob/3eb961ecccb8ced76f19217843bb9ee88f6f8750/tests/parser/features/iteration/test_for_in_list.py#L8


Discussion:
I am pretty sure the elements count is completely fine, keep in mind that arrays start for 0 (not from 1) so 0 to 5 is actually 6 elements (here s[0] is 1, s[1] is 2, and so on).
This looks contradictory with the syntax of common languages. I expected `n` in `int128[n]` to mean the number of elements, like it is in C/Java/etc.


In fact the check is not performed at all. Try `s: int128[1] = [1, 2, 3, 4, 5, 6] ` .

Yup, this is a bug. I think a bug in the parsing section of the compiler. If you try to set a global with that variable `s`, it fails right?
Yes, if `s` is global assignment fails with `Mismatched number of elements.`

I see this bug is pretty wide. This code also works:
`struct: {a: int128, b: decimal} = {a: 1.2, b: 1} `
And fails when struct is a global variable.
I think those seems pretty similar. Sounds like we have our work cut out for us!
@denis-bogdanas thanks for the report! :smile: 

Resolving patch:
diff --git a/vyper/parser/stmt.py b/vyper/parser/stmt.py
--- a/vyper/parser/stmt.py
+++ b/vyper/parser/stmt.py
@@ -100,7 +100,7 @@ def ann_assign(self):
         if self.stmt.value is not None:
             sub = Expr(self.stmt.value, self.context).lll_node
             self._check_valid_assign(sub)
-            variable_loc = LLLnode.from_list(pos, typ=sub.typ, location='memory', pos=getpos(self.stmt))
+            variable_loc = LLLnode.from_list(pos, typ=typ, location='memory', pos=getpos(self.stmt))
             o = make_setter(variable_loc, sub, 'memory', pos=getpos(self.stmt))
         self.context.set_in_assignment(False)
         return o


Test patch:
diff --git a/tests/parser/features/iteration/test_for_in_list.py b/tests/parser/features/iteration/test_for_in_list.py
--- a/tests/parser/features/iteration/test_for_in_list.py
+++ b/tests/parser/features/iteration/test_for_in_list.py
@@ -5,7 +5,7 @@ def test_basic_for_in_list(get_contract_with_gas_estimation):
     code = """
 @public
 def data() -> int128:
-    s: int128[5] = [1, 2, 3, 4, 5, 6]
+    s: int128[5] = [1, 2, 3, 4, 5]
     for i in s:
         if i >= 3:
             return i
diff --git a/tests/parser/syntax/test_ann_assign.py b/tests/parser/syntax/test_ann_assign.py
--- a/tests/parser/syntax/test_ann_assign.py
+++ b/tests/parser/syntax/test_ann_assign.py
@@ -47,7 +47,24 @@ def do_stuff() -> bool:
 @public
 def test():
     a: bool = False or self.do_stuff()
-    """, StructureException)
+    """, StructureException),
+    ("""
+@public
+def data() -> int128:
+    s: int128[5] = [1, 2, 3, 4, 5, 6]
+    """, TypeMismatchException),
+    ("""
+@public
+def foo() -> int128:
+    struct: {a: int128, b: decimal} = {a: 1.2, b: 1}
+    return struct.a
+    """, TypeMismatchException),
+    ("""
+@public
+def foo() -> int128:
+    struct: {a: int128, b: decimal} = {b: 1.2, c: 1, d: 33, e: 55}
+    return struct.a
+    """, TypeMismatchException)
 ]
Repository: vyperlang/vyper

Issue:
Remove dependency on pyethereum
### What's your issue about?

This is a blocker for pyethereum Casper branch.

Vyper depends on [pyethereum 2.1.3](https://github.com/ethereum/vyper/blob/master/setup.py#L26), this introduces errors to the installation.

```
error: ethereum 2.1.0 is installed but ethereum==2.1.3 is required by {'vyper'}
```

### How can it be fixed?

Move pyethereum to dev_requirements.txt.

The pyethereum is mainly imported in two places of the codebase. Mostly it is imported in `scripts/`, removing it should not affect the functionality of the package. It is also imported in [parser_utils](https://github.com/ethereum/vyper/blob/master/vyper/parser/parser_utils.py#L3), which should be replaceable with constants in `vyper/opcodes`



#### Cute Animal Picture

![](https://i.imgur.com/EYuLW94.gif)



Discussion:
Just a note for the `parser_utils` changes. pyethereum package is only used to get the necesary opcode gas values - these can easily put it's own structure :smile: 
We can probably pull the opcodes from `py-evm`

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -22,12 +22,8 @@
     url='https://github.com/ethereum/vyper',
     license=license,
     packages=find_packages(exclude=('tests', 'docs')),
-    install_requires=[
-        'ethereum==2.1.3',
-        'bumpversion',
-        'pytest-cov',
-        'pytest-runner',  # Must be after pytest-cov or it will not work
-                          # due to https://github.com/pypa/setuptools/issues/196
-    ],
+    install_requires=['py-evm>=0.2.0a12'],
+    setup_requires=['pytest-runner'],
+    tests_require=['pytest', 'pytest-cov', 'ethereum==2.3.1'],
     scripts=['bin/vyper', 'bin/vyper-serve']
 )
diff --git a/vyper/parser/parser_utils.py b/vyper/parser/parser_utils.py
--- a/vyper/parser/parser_utils.py
+++ b/vyper/parser/parser_utils.py
@@ -1,6 +1,6 @@
 import re
 
-from ethereum import opcodes
+from evm.constants import GAS_IDENTITY, GAS_IDENTITYWORD
 
 from vyper.exceptions import TypeMismatchException
 from vyper.opcodes import comb_opcodes
@@ -257,8 +257,7 @@ def make_byte_array_copier(destination, source):
         raise TypeMismatchException("Cannot cast from greater max-length %d to shorter max-length %d" % (source.typ.maxlen, destination.typ.maxlen))
     # Special case: memory to memory
     if source.location == "memory" and destination.location == "memory":
-        gas_calculation = opcodes.GIDENTITYBASE + \
-            opcodes.GIDENTITYWORD * (ceil32(source.typ.maxlen) // 32)
+        gas_calculation = GAS_IDENTITY + GAS_IDENTITYWORD * (ceil32(source.typ.maxlen) // 32)
         o = LLLnode.from_list(
             ['with', '_source', source,
                 ['with', '_sz', ['add', 32, ['mload', '_source']],


Test patch:
Repository: vyperlang/vyper

Issue:
Improve gas cost for `shift` function
### What's your issue about?
`shift` is compiled to the following code:
```
   ['if', ['sle', '_s', 0], 
          ['div', '_v', ['exp', 2, ['sub', 0, '_s']]], 
          ['mul', '_v', ['exp', 2, '_s']]]]],
```
When _s == 0, `['div', '_v', ['exp', 2, ['sub', 0, '_s']]] and ['mul', '_v', ['exp', 2, '_s']]]] `are the same. But in the div branch, it need to execute sub which potentially costs more gas. Suggest using slt instead of sle. This will also ease the verification. 

### How can it be fixed?

change `sle` to `slt`

#### Cute Animal Picture

![image](https://user-images.githubusercontent.com/5641590/38510709-6b8ab7a0-3beb-11e8-9e43-017e08c83777.png)



Discussion:

Resolving patch:
diff --git a/vyper/functions/functions.py b/vyper/functions/functions.py
--- a/vyper/functions/functions.py
+++ b/vyper/functions/functions.py
@@ -650,7 +650,7 @@ def shift(expr, args, kwargs, context):
                                     # If it is negative, divide by a power of two
                                     # node that if the abs of the second argument >= 256, then in the EVM
                                     # 2**(second arg) = 0, and multiplying OR dividing by 0 gives 0
-                                    ['if', ['sle', '_s', 0],
+                                    ['if', ['slt', '_s', 0],
                                            ['div', '_v', ['exp', 2, ['sub', 0, '_s']]],
                                            ['mul', '_v', ['exp', 2, '_s']]]]],
     typ=BaseType('uint256'), pos=getpos(expr))


Test patch:
Repository: vyperlang/vyper

Issue:
Add 'python_requires' to setup.py
### What's your issue about?
Should we add `python_requires` to our `setup.py`?
https://packaging.python.org/tutorials/distributing-packages/#python-requires

### How can it be fixed?
If so, it should be >`python3.6` due to our dependancy on PEP 484



Discussion:
PEP 484 is supported in Python3.5 as well - I had to upgrade from 3.4 to 3.5 to get it for an unrelated project. Unless there's something more specific that's 3.6-only?

https://docs.python.org/3.5/library/typing.html
@paultiplady I think you're right, Python3.5 should work. To minimize supported versions, I think mandating 3.6 may be beneficial (at least for now). Either that, or we need to develop a framework for testing both of those on Travis
Tox is the standard way of doing that, perhaps you can crib a Travis/Tox config from an established project like Requests?

https://github.com/requests/requests/blob/master/tox.ini
https://github.com/requests/requests/blob/master/.travis.yml

Appreciate that might be more work than the MVP of only supporting 3.6 though.
If you want to submit a PR for adding tox support for 3.5, I can get behind supporting 2 versions. They're not that much different
Discussed, add `> 3.6` for now.

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -24,6 +24,7 @@
     packages=find_packages(exclude=('tests', 'docs')),
     install_requires=['py-evm>=0.2.0a12'],
     setup_requires=['pytest-runner'],
+    python_requires='>=3.6',
     tests_require=['pytest', 'pytest-cov', 'ethereum==2.3.1'],
     scripts=['bin/vyper', 'bin/vyper-serve', 'bin/vyper-run']
 )


Test patch:
Repository: vyperlang/vyper

Issue:
clamp has different behavior on checking the lowerbound and the upperbound
### What's your issue about?

`clamp` is compiled to following EVM bytecode:
```
o.extend(compile_to_assembly(code.args[2], withargs, break_dest, height + 3))
o.extend(['SWAP1', comp1, 'PC', 'JUMPI'])
o.extend(['DUP1', 'SWAP2', 'SWAP1', comp2, 'ISZERO'])
o.extend(get_revert())
```
When the value is greater than the upper-bound, the code jump to an invalid pc. When the value is smaller than the lower-bound, the code use REVERT to revert the state. 


### How can it be fixed?

It's better to use REVERT on both cases.

#### Cute Animal Picture

![image](https://user-images.githubusercontent.com/5641590/39583950-dda264f4-4eb6-11e8-8e6a-54278c481932.png)




Discussion:
@yzhang90 thanks! :smile_cat: 


Resolving patch:
diff --git a/vyper/compile_lll.py b/vyper/compile_lll.py
--- a/vyper/compile_lll.py
+++ b/vyper/compile_lll.py
@@ -211,7 +211,8 @@ def compile_to_assembly(code, withargs=None, break_dest=None, height=0):
         o.extend(compile_to_assembly(code.args[1], withargs, break_dest, height + 1))
         o.extend(['DUP1'])
         o.extend(compile_to_assembly(code.args[2], withargs, break_dest, height + 3))
-        o.extend(['SWAP1', comp1, 'PC', 'JUMPI'])
+        o.extend(['SWAP1', comp1, 'ISZERO'])
+        o.extend(get_revert())
         o.extend(['DUP1', 'SWAP2', 'SWAP1', comp2, 'ISZERO'])
         o.extend(get_revert())
         return o


Test patch: