Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

console, internal/jsre: fix autocomplete issues #26518

Merged
merged 4 commits into from
Jan 19, 2023
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 33 additions & 3 deletions console/console.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ import (
"github.com/ethereum/go-ethereum/rpc"
"github.com/mattn/go-colorable"
"github.com/peterh/liner"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)

var (
Expand Down Expand Up @@ -194,11 +196,38 @@ func (c *Console) initWeb3(bridge *bridge) error {
transport.Set("send", jsre.MakeCallback(vm, bridge.Send))
transport.Set("sendAsync", jsre.MakeCallback(vm, bridge.Send))
vm.Set("_consoleWeb3Transport", transport)
_, err = vm.RunString("var web3 = new Web3(_consoleWeb3Transport)")
var val goja.Value
val, err = vm.RunString("new Web3(_consoleWeb3Transport)")
if err != nil {
return
}
// Some JS properties like eth.protocolVersion are non-configurable in web3.js.
// I.e. they cannot be deleted via `delete`. Work-around: copy all properties
// except the ones to be deleted to a new object.
web3 := val.ToObject(vm)
eth := web3.Get("eth").ToObject(vm)
eth = deleteProperties(vm, eth, map[string]struct{}{"protocolVersion": struct{}{}, asyncGetterName("protocolVersion"): struct{}{}})
web3.Set("eth", eth)
vm.GlobalObject().Set("web3", web3)
})
return err
}

func deleteProperties(vm *goja.Runtime, obj *goja.Object, names map[string]struct{}) *goja.Object {
new := vm.NewObject()
for _, k := range obj.Keys() {
if _, ignore := names[k]; ignore {
continue
}
new.Set(k, obj.Get(k))
}
return new
}

func asyncGetterName(name string) string {
return fmt.Sprintf("get%s", cases.Title(language.English, cases.NoLower).String(name))
s1na marked this conversation as resolved.
Show resolved Hide resolved
}

var defaultAPIs = map[string]string{"eth": "1.0", "net": "1.0", "debug": "1.0"}

// initExtensions loads and registers web3.js extensions.
Expand Down Expand Up @@ -309,8 +338,9 @@ func (c *Console) AutoCompleteInput(line string, pos int) (string, []string, str
continue
}
// Handle web3 in a special way (i.e. other numbers aren't auto completed)
if start >= 3 && line[start-3:start] == "web3" {
start -= 3
if start >= 3 && line[start-3:start+1] == "web3" {
// Start will be decremented one more by loop
start -= 2
continue
}
// We've hit an unexpected character, autocomplete form here
Expand Down