complexargs.gno

1.95 Kb ยท 82 lines
 1package complexargs
 2
 3import (
 4	"strings"
 5
 6	"gno.land/p/demo/ufmt"
 7)
 8
 9// Some example complex types, ie a slice, and a custom type
10var (
11	slice    = []int{1, 2, 3}
12	myObject = &CustomType{
13		Name:    "Alice",
14		Numbers: []int{4, 5, 6},
15	}
16)
17
18type CustomType struct {
19	Name    string
20	Numbers []int
21}
22
23// SetSlice takes a complex argument that must be called using MsgRun or from another contract that imports this one.
24func SetSlice(newSlice []int) {
25	slice = newSlice
26}
27
28// SetMyObject takes a complex argument that must be called using MsgRun or from another contract that imports this one.
29func SetMyObject(newCoolObject CustomType) {
30	myObject = &newCoolObject
31}
32
33func Render(_ string) string {
34	out := "# Complex argument functions\n\n"
35	out += `Exposed realm functions and methods that take in complex arguments, such as slices, structs, pointers, etc,
36cannot be called via a standard "MsgCall" transaction. To call these functions, users need to use "MsgRun".
37
38Check out the source code to see example functions and objects.
39
40In this case, the following "MsgRun" code would be used to call the function:  
41`
42	out += ufmt.Sprintf("```go\n%s\n```\n\n", msgrun)
43
44	out += "Value of int slice: "
45	for i, v := range slice {
46		if i > 0 {
47			out += ", "
48		}
49		out += ufmt.Sprintf("%d", v)
50	}
51	out += "\n\n"
52
53	if myObject != nil {
54		s := ""
55		for i, v := range myObject.Numbers {
56			if i > 0 {
57				s += ","
58			}
59			s += ufmt.Sprintf("%d", v)
60		}
61		out += ufmt.Sprintf("Value of myObject: `CustomObject{Name: %s, Numbers: %s}`", myObject.Name, s)
62	}
63
64	out = strings.Replace(out, "\"", "`", -1)
65	return out
66}
67
68const msgrun = `package main
69
70// Import the realm you want to call
71import "gno.land/r/docs/complexargs"
72
73func main() {
74	// Create the complex arguments to pass:
75	slice := []int{1, 2, 3}
76	// Call the function
77	complexargs.SetSlice(slice)
78
79	// The same can be done with custom types:
80	obj := complexargs.CustomType{Name: "whatever", Numbers: []int{1, 10, 100}}
81	complexargs.SetMyObject(obj)
82}`