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

     1  package vm
     2  
     3  /*
     4  import w "github.com/wasmerio/wasmer-go/wasmer"
     5  
     6  type Wasm struct {
     7  	code     []byte
     8  	engine   *w.Engine
     9  	store    *w.Store
    10  	module   *w.Module
    11  	instance *w.Instance
    12  }
    13  
    14  type NativeFunc = func(args []w.Value) ([]w.Value, error)
    15  
    16  type WasmImportFunc struct {
    17  	name        string
    18  	inputTypes  []w.ValueKind
    19  	outputTypes []w.ValueKind
    20  	nativeFunc  NativeFunc
    21  }
    22  
    23  type WasmImport struct {
    24  	namespace string
    25  	functions []WasmImportFunc
    26  }
    27  
    28  func NewWasm(code []byte, imports []WasmImport) (*Wasm, error) {
    29  	var instance *w.Instance
    30  
    31  	engine := w.NewEngine()
    32  	store := w.NewStore(engine)
    33  	module, _ := w.NewModule(store, code)
    34  
    35  	importObject := w.NewImportObject()
    36  
    37  	for _, v := range imports {
    38  		intoExtern := make(map[string]w.IntoExtern)
    39  		for _, fn := range v.functions {
    40  			intoExtern[fn.name] = w.NewFunction(
    41  				store,
    42  				w.NewFunctionType(w.NewValueTypes(fn.inputTypes...), w.NewValueTypes(fn.outputTypes...)),
    43  				fn.nativeFunc,
    44  			)
    45  		}
    46  		importObject.Register(
    47  			v.namespace,
    48  			intoExtern,
    49  		)
    50  	}
    51  
    52  	instance, e := w.NewInstance(module, importObject)
    53  	if e != nil {
    54  		return nil, e
    55  	}
    56  
    57  	return &Wasm{
    58  		code:     code,
    59  		engine:   engine,
    60  		store:    store,
    61  		module:   module,
    62  		instance: instance,
    63  	}, nil
    64  }
    65  
    66  func (wasm *Wasm) GetFunction(name string) (w.NativeFunction, error) {
    67  	return wasm.instance.Exports.GetFunction(name)
    68  }
    69  
    70  func (wasm *Wasm) ExecuteFunction(name string, args ...interface{}) (interface{}, error) {
    71  	fn, e := wasm.instance.Exports.GetFunction(name)
    72  	if e != nil {
    73  		return nil, e
    74  	}
    75  	return fn(args...)
    76  }
    77  
    78  func (wasm *Wasm) GetMemory(name string) ([]byte, error) {
    79  	memory, e := wasm.instance.Exports.GetMemory(name)
    80  	if e != nil {
    81  		return nil, e
    82  	}
    83  	return memory.Data(), nil
    84  }
    85  */