Should I require a specific condition when working with indexes in Solidity

0 votes
pragma solidity ^0.4.0;

contract A{
    byte[10] arr;

    function setElement(uint index, byte value) public {
        require(index >= 0 && index < arr.length); //Should I leave it as is?
        arr[index] = value;

    function getElement(uint index) view public returns (byte) {
        require(index >= 0 && index < arr.length); //Or not?
        return arr[index];

As I know an assert-style exception is generated in the following situations and not only:

  • If you access an array at a too large or negative index (i.e. x[i] where i >= x.length or i < 0).

But should I check the condition every time?

Also I would like to refund the remaining gas to the executor.

Jul 17, 2018 in Blockchain by charlie_brown
• 7,780 points

1 answer to this question.

0 votes

You are using it correctly. require is intended to be used to check input parameters whereas assert is to verify the internals of your contract (mostly for testing purposes). If a requirecondition fails, the remaining gas will be refunded.

From the Solidity documentation:

The convenience functions assert and require can be used to check for conditions and throw an exception if the condition is not met. The assert function should only be used to test for internal errors, and to check invariants. The require function should be used to ensure valid conditions, such as inputs, or contract state variables are met, or to validate return values from calls to external contracts.

answered Jul 17, 2018 by aryya
• 7,440 points

Related Questions In Blockchain

0 votes
1 answer

Do we require a specific condition when working with indices on solidity?

Your code is written correctly. require is intended to ...READ MORE

answered Jul 23, 2018 in Blockchain by Perry
• 17,100 points
0 votes
1 answer
+4 votes
2 answers

How do I create a new block in Hyperledger Fabric?

This link might help you: ...READ MORE

answered Oct 11, 2018 in Blockchain by Sahu
0 votes
1 answer

Truffle tests not running after truffle init

This was a bug. They've fixed it. ...READ MORE

answered Sep 11, 2018 in Blockchain by Christine
• 15,830 points
+1 vote
3 answers

Removing double quotes from a string from JSON response in PHP

Just remove the json_encode call, and it should work: $resp ...READ MORE

answered Sep 12, 2018 in Blockchain by digger
• 26,720 points
0 votes
1 answer
0 votes
1 answer