From 6b3cf83d16b844bcf6b75172a7ca491466146fef Mon Sep 17 00:00:00 2001 From: Well Date: Thu, 15 May 2025 02:11:43 +0800 Subject: [PATCH] add console.log/error support --- eth/tracers/js/goja.go | 23 ++++++++++++++++++++++- eth/tracers/js/tracer_test.go | 10 ++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/eth/tracers/js/goja.go b/eth/tracers/js/goja.go index d1e65bf7f4..ce8214232d 100644 --- a/eth/tracers/js/goja.go +++ b/eth/tracers/js/goja.go @@ -21,7 +21,9 @@ import ( "errors" "fmt" "math/big" + "os" "slices" + "strings" "sync" "github.com/dop251/goja" @@ -470,7 +472,26 @@ func wrapError(context string, err error) error { // It depends on type converters having been set up. func (t *jsTracer) setBuiltinFunctions() { vm := t.vm - // TODO: load console from goja-nodejs + // Initialize console object with log and error methods + console := vm.NewObject() + console.Set("log", func(call goja.FunctionCall) goja.Value { + var output []string + for _, argument := range call.Arguments { + output = append(output, fmt.Sprintf("%v", argument)) + } + fmt.Fprintln(os.Stdout, strings.Join(output, " ")) + return goja.Undefined() + }) + console.Set("error", func(call goja.FunctionCall) goja.Value { + var output []string + for _, argument := range call.Arguments { + output = append(output, fmt.Sprintf("%v", argument)) + } + fmt.Fprintln(os.Stderr, strings.Join(output, " ")) + return goja.Undefined() + }) + vm.Set("console", console) + vm.Set("toHex", func(v goja.Value) string { b, err := t.fromBuf(vm, v, false) if err != nil { diff --git a/eth/tracers/js/tracer_test.go b/eth/tracers/js/tracer_test.go index dbfc7308f7..d74c6100cc 100644 --- a/eth/tracers/js/tracer_test.go +++ b/eth/tracers/js/tracer_test.go @@ -146,6 +146,16 @@ func TestTracer(t *testing.T) { }, { // tests ctx.coinbase code: "{lengths: [], step: function(log) { }, fault: function() {}, result: function(ctx) { var coinbase = ctx.coinbase; return toAddress(coinbase); }}", want: `{"0":0,"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0}`, + }, { + code: `{ + step: function() { + console.log("test log"); + console.error("test error"); + }, + fault: function() {}, + result: function() {}, + }`, + want: `{}`, }, } { if have, err := execTracer(tt.code, tt.contract); tt.want != string(have) || tt.fail != err {