From 167e99db544fd55d20224acf8441debe06a147fd Mon Sep 17 00:00:00 2001 From: n3wbie Date: Tue, 13 Jun 2023 15:19:10 +0900 Subject: [PATCH] feat: std.TestSetPrevRealm --- examples/gno.land/r/demo/inner/inner.gno | 1 + examples/gno.land/r/demo/inner/inner_test.gno | 30 +++++++++++ gnovm/tests/imports.go | 52 +++++++++++++++++++ 3 files changed, 83 insertions(+) create mode 100644 examples/gno.land/r/demo/inner/inner.gno create mode 100644 examples/gno.land/r/demo/inner/inner_test.gno diff --git a/examples/gno.land/r/demo/inner/inner.gno b/examples/gno.land/r/demo/inner/inner.gno new file mode 100644 index 00000000000..8a7eab5c415 --- /dev/null +++ b/examples/gno.land/r/demo/inner/inner.gno @@ -0,0 +1 @@ +package inner diff --git a/examples/gno.land/r/demo/inner/inner_test.gno b/examples/gno.land/r/demo/inner/inner_test.gno new file mode 100644 index 00000000000..0b98a523cd3 --- /dev/null +++ b/examples/gno.land/r/demo/inner/inner_test.gno @@ -0,0 +1,30 @@ +package inner + +import ( + "std" + "testing" + + "gno.land/p/demo/testutils" +) + +var ( + oc std.Address = testutils.TestAddress("origin caller ") + or string = "gno.land/r/demo/outer_realm" +) + +func TestOuterCallInner(t *testing.T) { + std.TestSetOrigCaller(oc) + shouldEQ(t, std.GetOrigCaller(), oc) + + std.TestSetPrevRealm(or) + pr := std.PrevRealm() + shouldEQ(t, pr.Addr(), std.DerivePkgAddr(or)) + shouldEQ(t, pr.PkgPath(), or) + shouldEQ(t, std.GetOrigCaller(), oc) +} + +func shouldEQ(t *testing.T, got, want interface{}) { + if got != want { + t.Errorf("got %v, want %v", got, want) + } +} diff --git a/gnovm/tests/imports.go b/gnovm/tests/imports.go index 58d62f02d8d..1196564f224 100644 --- a/gnovm/tests/imports.go +++ b/gnovm/tests/imports.go @@ -567,6 +567,58 @@ func testPackageInjector(store gno.Store, pn *gno.PackageNode) { m.Context = ctx }, ) + pn.DefineNative("TestSetPrevRealm", + gno.Flds( // params + "", gno.AnyT(), + ), + gno.Flds( // results + ), + func(m *gno.Machine) { + arg0 := m.LastBlock().GetParams1().TV + + switch arg0.T.String() { + case "std.Address": + // Set PrevRealm as an user + addr := arg0.GetString() + ctx := m.Context.(stdlibs.ExecContext) + ctx.OrigCaller = crypto.Bech32Address(addr) + m.Context = ctx + + case "string": + // Set PrevRealm as a realm + realm := arg0.GetString() + + // overwrite orig caller + ctx := m.Context.(stdlibs.ExecContext) + ctx.OrigCaller = crypto.Bech32Address(realm) + + // Set PkgPath + for i := m.NumFrames() - 1; i > 0; i-- { + fr := m.Frames[i] + if fr.LastPackage == nil || !fr.LastPackage.IsRealm() { + if i != 1 { + fr.LastPackage = &gno.PackageValue{ + PkgPath: "gno.land/r/dummy", + } + + m.Frames[i] = fr + } else { + fr.LastPackage = &gno.PackageValue{ + PkgPath: realm, + } + + m.Frames[i] = fr + } + + } + } + default: + panic( + fmt.Sprintf("TestSetPrevRealm: invlaid type %v", arg0.T), + ) + } + }, + ) pn.DefineNative("TestSetOrigPkgAddr", gno.Flds( // params "", "Address",