Skip to content

Commit

Permalink
Add writing tokens gas cost to memory
Browse files Browse the repository at this point in the history
  • Loading branch information
MaksymMalicki committed Jan 7, 2025
1 parent 73f6dd5 commit 17b17df
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 5 deletions.
2 changes: 1 addition & 1 deletion integration_tests/.env
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
# Set to run some specific file tests (ex. fib.cairo,alloc.cairo)
INTEGRATION_TESTS_FILTERS=
INTEGRATION_TESTS_FILTERS=ecdsa_recover__starknet.cairo
72 changes: 72 additions & 0 deletions pkg/runner/gas.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package runner

import (
"fmt"

"github.com/NethermindEth/cairo-vm-go/pkg/vm"
"github.com/NethermindEth/cairo-vm-go/pkg/vm/memory"
mem "github.com/NethermindEth/cairo-vm-go/pkg/vm/memory"
)

type TokenGasCost uint8

const (
ConstToken TokenGasCost = iota + 1
HoleToken
RangeCheckToken
RangeCheck96Token
PedersenToken
PoseidonToken
BitwiseToken
EcOpToken
AddModToken
MulModToken
)

func getTokenGasCost(token TokenGasCost) (uint64, error) {
switch token {
case ConstToken:
return 1, nil
case PedersenToken:
return 4050, nil
case PoseidonToken:
return 491, nil
case BitwiseToken:
return 583, nil
case EcOpToken:
return 4085, nil
case AddModToken:
return 230, nil
case MulModToken:
return 604, nil
default:
return 0, fmt.Errorf("token has no cost")
}
}

func gasInitialization(memory *memory.Memory) error {
builtinsCostSegmentAddress := memory.AllocateEmptySegment()
mv := mem.MemoryValueFromMemoryAddress(&builtinsCostSegmentAddress)
programSegment := memory.Segments[vm.ProgramSegment]
err := memory.Write(0, programSegment.Len(), &mv)
if err != nil {
return err
}
preCostTokenTypes := []TokenGasCost{PedersenToken, PoseidonToken, BitwiseToken, EcOpToken, AddModToken, MulModToken}
for _, token := range preCostTokenTypes {
cost, err := getTokenGasCost(token)
if err != nil {
return err
}
mv := mem.MemoryValueFromUint(cost)
err = memory.WriteToAddress(&builtinsCostSegmentAddress, &mv)
if err != nil {
return err
}
builtinsCostSegmentAddress, err = builtinsCostSegmentAddress.AddOffset(1)
if err != nil {
return err
}
}
return nil
}
5 changes: 1 addition & 4 deletions pkg/runner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,10 +266,7 @@ func (runner *Runner) initializeBuiltins(memory *mem.Memory) ([]mem.MemoryValue,
}
// Write builtins costs segment address to the end of the program segment
if runner.isCairoMode() {
builtinsCostSegmentAddress := memory.AllocateEmptySegment()
mv := mem.MemoryValueFromMemoryAddress(&builtinsCostSegmentAddress)
programSegment := memory.Segments[vm.ProgramSegment]
err := memory.Write(0, programSegment.Len(), &mv)
err := gasInitialization(memory)
if err != nil {
return nil, err
}
Expand Down

0 comments on commit 17b17df

Please sign in to comment.