github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/modules/wasm/runtime/runtime.go (about)

     1  package runtime
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/pkg/errors"
     7  
     8  	"github.com/machinefi/w3bstream/pkg/modules/wasm/abi/proxy"
     9  	"github.com/machinefi/w3bstream/pkg/modules/wasm/abi/types"
    10  	"github.com/machinefi/w3bstream/pkg/modules/wasm/runtime/wasmtime"
    11  )
    12  
    13  var ErrUnknownRuntimeName = errors.New("unknown runtime name")
    14  
    15  func NewRuntime(ctx context.Context, engine string, id string, code []byte) (types.Instance, error) {
    16  	switch engine {
    17  	case "wasmtime":
    18  		vm := wasmtime.NewWasmtimeVM(id)
    19  		mod, err := vm.NewModule(code)
    20  		if err != nil {
    21  			return nil, err
    22  		}
    23  		instance := wasmtime.NewWasmtimeInstance(vm.(*wasmtime.VM), mod.(*wasmtime.Module))
    24  		imports := proxy.NewImports(ctx)
    25  		instance.SetUserdata(&proxy.ABIContext{
    26  			Imports:  imports,
    27  			Instance: instance,
    28  		})
    29  		return instance, nil
    30  	default:
    31  		return nil, ErrUnknownRuntimeName
    32  	}
    33  }