Skip to content

Commit

Permalink
Fixes add function with felt-to-address addition
Browse files Browse the repository at this point in the history
  • Loading branch information
jkktom committed Sep 28, 2023
1 parent 0e66d54 commit c5d96d1
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 14 deletions.
38 changes: 26 additions & 12 deletions pkg/vm/memory/memory_value.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion pkg/vm/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion pkg/vm/vm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down

0 comments on commit c5d96d1

Please sign in to comment.