github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/modules/wasm/runtime/wasmtime/vm.go (about) 1 package wasmtime 2 3 import ( 4 "github.com/bytecodealliance/wasmtime-go/v17" 5 "github.com/pkg/errors" 6 7 "github.com/machinefi/w3bstream/pkg/modules/wasm/abi/types" 8 ) 9 10 const MaxFuelInStore = 1024 * 1024 * 1024 11 12 // NewWasmtimeVM creates wasmtime vm 13 func NewWasmtimeVM(id string) types.VM { 14 v := &VM{id: id, _fuel: MaxFuelInStore} 15 v.Init() 16 return v 17 } 18 19 var _ types.VM = (*VM)(nil) 20 21 type VM struct { 22 id string 23 engine *wasmtime.Engine 24 store *wasmtime.Store 25 _fuel uint64 26 } 27 28 func (vm *VM) ID() string { return vm.id } 29 30 func (vm *VM) Name() string { return "wasmtime" } 31 32 func (vm *VM) Init() { 33 config := wasmtime.NewConfig() 34 // config.SetConsumeFuel(true) 35 // config.SetEpochInterruption(true) 36 vm.engine = wasmtime.NewEngineWithConfig(config) 37 vm.store = wasmtime.NewStore(vm.engine) 38 vm.store.SetWasi(wasmtime.NewWasiConfig()) 39 // if err := vm.store.AddFuel(vm._fuel); err != nil { 40 // panic(err) 41 // } 42 } 43 44 func (vm *VM) NewModule(code []byte) (types.Module, error) { 45 if len(code) == 0 { 46 return nil, ErrInvalidWasmCode 47 } 48 49 mod, err := wasmtime.NewModule(vm.engine, code) 50 if err != nil { 51 return nil, errors.Wrap(ErrFailedToNewWasmModule, err.Error()) 52 } 53 54 return NewWasmtimeModule(vm, mod, code) 55 } 56 57 func (vm *VM) Close() error { 58 // TODO 59 return nil 60 }