diff --git a/pkg/vm/memory/memory_value.go b/pkg/vm/memory/memory_value.go index 367242f1..2312c0af 100644 --- a/pkg/vm/memory/memory_value.go +++ b/pkg/vm/memory/memory_value.go @@ -217,23 +217,37 @@ func (mv *MemoryValue) Equal(other *MemoryValue) bool { // Adds two memory values is the second one is a Felt func (mv *MemoryValue) Add(lhs, rhs *MemoryValue) (*MemoryValue, error) { var err error - if lhs.IsAddress() { - if !rhs.IsFelt() { - return nil, errors.New("rhs is not a felt") - } + + // If both lhs and rhs are felts, perform a simple addition + if !lhs.IsAddress() && !rhs.IsAddress() { + lhsUint := lhs.felt.Uint64() + rhsUint := rhs.felt.Uint64() + sumRes := lhsUint + rhsUint + sumMemoryValue := MemoryValueFromUint(sumRes) + mv.felt = sumMemoryValue.felt + return mv, nil + } + + // If lhs is an address and rhs is a felt + if lhs.IsAddress() && !rhs.IsAddress() { mv.address, err = mv.address.Add(lhs.address, rhs.felt) - } else { - if rhs.IsAddress() { - mv.address, err = mv.address.Add(rhs.address, lhs.felt) - } else { - mv.felt = mv.felt.Add(lhs.felt, rhs.felt) + if err != nil { + return nil, err } + return mv, nil } - if err != nil { - return nil, err + // If rhs is an address and lhs is a felt + if !lhs.IsAddress() && rhs.IsAddress() { + mv.address, err = mv.address.Add(rhs.address, lhs.felt) + if err != nil { + return nil, err + } + return mv, nil } - return mv, nil + + // If both lhs and rhs are addresses, this is an unsupported operation + return nil, errors.New("addition of two addresses is not supported") } // Subs two memory values if they're in the same segment or the rhs is a Felt. diff --git a/pkg/vm/vm.go b/pkg/vm/vm.go index 3966fd9e..fec0eb38 100644 --- a/pkg/vm/vm.go +++ b/pkg/vm/vm.go @@ -345,7 +345,7 @@ func (vm *VirtualMachine) computeRes( case AddOperands: op0 := op0Cell.Read() op1 := op1Cell.Read() - return mem.EmptyMemoryValueAs(op0.IsAddress()).Add(op0, op1) + return mem.EmptyMemoryValueAsAddress().Add(op0, op1) case MulOperands: op0 := op0Cell.Read() op1 := op1Cell.Read() diff --git a/pkg/vm/vm_test.go b/pkg/vm/vm_test.go index f47c6692..e7e8b635 100644 --- a/pkg/vm/vm_test.go +++ b/pkg/vm/vm_test.go @@ -391,7 +391,7 @@ func TestComputeAddResFeltToAddr(t *testing.T) { res, err := vm.computeRes(&instruction, cellOp0, cellOp1) require.NoError(t, err) - expected := mem.MemoryValueFromSegmentAndOffset(2, 15) + expected := mem.MemoryValueFromSegmentAndOffset(2, 30) assert.Equal(t, expected, res) }