0

The following code allows a user(defined by userid) to subscribe to a policy (defined by policy address of the policy smart contract)

function subscribeToPolicy(address policyAddress, uint userId) public payable {
    uint policyPrice = 0.1 ether;
    require (msg.value >= policyPrice);
    userMapping[userId].mySubscriptions.push(policyAddress);
}

This piece of code works as expected (after supplying 0.1ETH and appropriate gas) and the policy is added to the user's subscription array.

I modified this code to add a modifier to prevent the addition of duplicate policies as follows

modifier policyExists(address policyAddress, uint userId) {
    for(uint j=0; j<userMapping[userId].mySubscriptions.length+1; j++){
        if (userMapping[userId].mySubscriptions[j] == policyAddress ){
            emit Log("Policy already purchased");
            revert();
        }
    }
    _;
}
function subscribeToPolicy(address policyAddress, uint userId)            
policyExists(policyAddress, userId) public payable {
    uint policyPrice = 0.1 ether;
    require (msg.value >= policyPrice);
    userMapping[userId].mySubscriptions.push(policyAddress);
}

This code does not work as expected and the error returned by the VM is as follows

transact to OasisUser.subscribeToPolicy errored: VM error: invalid opcode. invalid opcode

The execution might have thrown. Any ideas for solving this error?

0

1 Answer 1

0

You are attempting to access the array out of bound.

Change this:

j<userMapping[userId].mySubscriptions.length+1

To this:

j<userMapping[userId].mySubscriptions.length

BTW, I might be wrong here, but when a transaction reverts, nothing is written into the blockchain. So emitting an event beforehand (emit Log("Policy already purchased")) is useless, because it is not going to be registered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.