Skip to content
This repository was archived by the owner on Oct 15, 2024. It is now read-only.

Commit 7bc7535

Browse files
committed
feat: WASM Go - registering wasm module function in random js object
1 parent 5866c35 commit 7bc7535

File tree

7 files changed

+64
-809
lines changed

7 files changed

+64
-809
lines changed

go/README.md

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,8 @@
1-
# Go smartweave example contract
1+
# Go SmartWeave example contract
22

33
## Install go 1.17
44
https://go.dev/doc/install
55

6-
## How to use (default Go compiler)
7-
- [Install easyjson](https://github.com/mailru/easyjson#install)
8-
- Run `easyjson -all easyjson/easyjson.go`
9-
- Build wasm contract file: `bash build.sh` (it should create `out` folder)
10-
- Run wasm contract simulation: `node run.js`
11-
126
## How to use (tinygo compiler)
137
- [Install tinygo](https://tinygo.org/getting-started/install/)
148
- [Install easyjson](https://github.com/mailru/easyjson#install)

go/common/async.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package common
22

33
import (
4+
"math/rand"
45
"syscall/js"
56
)
67

@@ -30,3 +31,13 @@ func Await(awaitable js.Value) ([]js.Value, []js.Value) {
3031
return nil, err
3132
}
3233
}
34+
35+
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
36+
37+
func RandSeq(n int) string {
38+
b := make([]rune, n)
39+
for i := range b {
40+
b[i] = letters[rand.Intn(len(letters))]
41+
}
42+
return string(b)
43+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package wasm_module
2+
3+
import (
4+
"syscall/js"
5+
)
6+
7+
func RegisterWasmModule(wasmModuleId string) {
8+
importModule().Call("registerWasmModule", wasmModuleId)
9+
}
10+
11+
func importModule() js.Value {
12+
return js.Global().Get("redstone").Get("go").Get("WasmModule")
13+
}

go/common/wasm.go

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,30 @@ package common
22

33
import (
44
"encoding/json"
5+
"github.com/redstone-finance/redstone-contracts-wasm/go/common/imports/wasm_module"
56
"github.com/redstone-finance/redstone-contracts-wasm/go/common_types"
7+
"math/rand"
68
"syscall/js"
9+
"time"
710
)
811

912
func Run(contract common_types.SwContract) {
13+
// generating random module id and registering it on host
14+
// a workaround for potential wasm modules collision
15+
rand.Seed(time.Now().UnixNano())
16+
moduleId := RandSeq(20)
17+
js.Global().Set(moduleId, make(map[string]interface{}))
18+
wasmModule := js.Global().Get(moduleId)
1019
// the Go way of defining WASM exports...
1120
// standard "exports" from the wasm module do not work here...
1221
// that's kinda ugly TBH
13-
js.Global().Set("handle", handle(contract))
14-
js.Global().Set("initState", initState(contract))
15-
js.Global().Set("currentState", currentState(contract))
16-
js.Global().Set("contractType", contractType())
17-
js.Global().Set("lang", lang())
22+
wasmModule.Set("handle", handle(contract))
23+
wasmModule.Set("initState", initState(contract))
24+
wasmModule.Set("currentState", currentState(contract))
25+
wasmModule.Set("contractType", contractType())
26+
wasmModule.Set("lang", lang())
27+
28+
wasm_module.RegisterWasmModule(moduleId)
1829

1930
// Prevent the function from returning, which is required in a wasm module
2031
// i.e. "Error: Go program has already exited" is thrown otherwise on host

go/run-tiny.js

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,15 @@ async function main() {
1616

1717
let usedGas = 0;
1818

19-
console.log(go.importObject)
19+
//console.log(go.importObject)
2020
go.importObject.metering = {
2121
usegas: function (value) {
2222
usedGas += value;
2323
}
2424
}
2525

26+
let moduleExports = {};
27+
2628
global.redstone.go = {
2729
console: {
2830
log: function (...args) {
@@ -74,9 +76,17 @@ async function main() {
7476
}
7577
}
7678
},
79+
},
80+
WasmModule: {
81+
registerWasmModule: function(moduleId) {
82+
moduleExports = global[moduleId];
83+
delete moduleId;
84+
console.log(moduleExports);
85+
}
7786
}
7887
}
7988

89+
8090
const wasmBinary = fs.readFileSync('./.out/contract_tiny.wasm');
8191
/*const meteredWasmBinary = metering.meterWASM(wasmBinary, {
8292
meterType: "i32",
@@ -85,13 +95,14 @@ async function main() {
8595
const module = await WebAssembly.instantiate(wasmBinary, go.importObject);
8696

8797
const wasm = module.instance;
88-
go.run(wasm);
8998

9099
console.log(wasm.exports);
91-
92-
console.log('\nlang():', lang());
93-
console.log('\ncontractType():', contractType());
94-
console.log('\ninitState():', initState(JSON.stringify(
100+
console.log('calling go run');
101+
go.run(wasm);
102+
console.log('go run called');
103+
console.log('\nlang():', moduleExports.lang());
104+
console.log('\ncontractType():', moduleExports.contractType());
105+
console.log('\ninitState():', moduleExports.initState(JSON.stringify(
95106
{
96107
"ticker": "EXAMPLE_PST_TOKEN",
97108
"owner": "uhE-QeYS8i4pmUtnxQyHD7dzXFNaJ9oMK-IM-QPNY6M",
@@ -102,13 +113,13 @@ async function main() {
102113
}
103114
}
104115
)));
105-
console.log('\ncurrentState()', JSON.parse(currentState()));
116+
console.log('\ncurrentState()', JSON.parse(moduleExports.currentState()));
106117

107118
console.log("\nCalling async handle - transfer");
108119

109120
usedGas = 0;
110121

111-
const resultTransfer = await handle(JSON.stringify({
122+
const resultTransfer = await moduleExports.handle(JSON.stringify({
112123
function: 'transfer',
113124
target: 'uhE-QeYS8i4pmUtnxQyHD7dzXFNaJ9oMK-IM-QPNY6M',
114125
qty: 555555
@@ -117,18 +128,18 @@ async function main() {
117128
console.log('Result from transfer:', resultTransfer);
118129
console.log('Gas used', usedGas);
119130

120-
console.log('\ncurrentState()', JSON.parse(currentState()));
131+
console.log('\ncurrentState()', JSON.parse(moduleExports.currentState()));
121132

122133
console.log("\nCalling async handle - balance");
123-
const resultBalance = await handle(JSON.stringify({
134+
const resultBalance = await moduleExports.handle(JSON.stringify({
124135
function: 'balance',
125136
target: 'uhE-QeYS8i4pmUtnxQyHD7dzXFNaJ9oMK-IM-QPNY6M',
126137
}));
127138
// result should be target balance value - "view" functions return value
128139
console.log('Result from balance:', resultBalance);
129140

130141
console.log("\nCalling async handle - foreignCall");
131-
const resultFc = await handle(JSON.stringify({
142+
const resultFc = await moduleExports.handle(JSON.stringify({
132143
function: 'foreignCall',
133144
target: 'some-random-contract',
134145
}));
@@ -137,7 +148,7 @@ async function main() {
137148

138149
console.log("\n\nChecking exception handling (should throw here)");
139150
try {
140-
await handle(JSON.stringify({
151+
await moduleExports.handle(JSON.stringify({
141152
function: 'someRandomFunction',
142153
}));
143154
} catch (e) {

go/run.js

Lines changed: 0 additions & 149 deletions
This file was deleted.

0 commit comments

Comments
 (0)