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

Commit

Permalink
feat: WASM Go - registering wasm module function in random js object
Browse files Browse the repository at this point in the history
  • Loading branch information
ppedziwiatr committed Mar 10, 2022
1 parent 5866c35 commit 7bc7535
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 809 deletions.
8 changes: 1 addition & 7 deletions go/README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
# Go smartweave example contract
# Go SmartWeave example contract

## Install go 1.17
https://go.dev/doc/install

## How to use (default Go compiler)
- [Install easyjson](https://github.com/mailru/easyjson#install)
- Run `easyjson -all easyjson/easyjson.go`
- Build wasm contract file: `bash build.sh` (it should create `out` folder)
- Run wasm contract simulation: `node run.js`

## How to use (tinygo compiler)
- [Install tinygo](https://tinygo.org/getting-started/install/)
- [Install easyjson](https://github.com/mailru/easyjson#install)
Expand Down
11 changes: 11 additions & 0 deletions go/common/async.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package common

import (
"math/rand"
"syscall/js"
)

Expand Down Expand Up @@ -30,3 +31,13 @@ func Await(awaitable js.Value) ([]js.Value, []js.Value) {
return nil, err
}
}

var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

func RandSeq(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
13 changes: 13 additions & 0 deletions go/common/imports/wasm_module/imports.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package wasm_module

import (
"syscall/js"
)

func RegisterWasmModule(wasmModuleId string) {
importModule().Call("registerWasmModule", wasmModuleId)
}

func importModule() js.Value {
return js.Global().Get("redstone").Get("go").Get("WasmModule")
}
21 changes: 16 additions & 5 deletions go/common/wasm.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,30 @@ package common

import (
"encoding/json"
"github.com/redstone-finance/redstone-contracts-wasm/go/common/imports/wasm_module"
"github.com/redstone-finance/redstone-contracts-wasm/go/common_types"
"math/rand"
"syscall/js"
"time"
)

func Run(contract common_types.SwContract) {
// generating random module id and registering it on host
// a workaround for potential wasm modules collision
rand.Seed(time.Now().UnixNano())
moduleId := RandSeq(20)
js.Global().Set(moduleId, make(map[string]interface{}))
wasmModule := js.Global().Get(moduleId)
// the Go way of defining WASM exports...
// standard "exports" from the wasm module do not work here...
// that's kinda ugly TBH
js.Global().Set("handle", handle(contract))
js.Global().Set("initState", initState(contract))
js.Global().Set("currentState", currentState(contract))
js.Global().Set("contractType", contractType())
js.Global().Set("lang", lang())
wasmModule.Set("handle", handle(contract))
wasmModule.Set("initState", initState(contract))
wasmModule.Set("currentState", currentState(contract))
wasmModule.Set("contractType", contractType())
wasmModule.Set("lang", lang())

wasm_module.RegisterWasmModule(moduleId)

// Prevent the function from returning, which is required in a wasm module
// i.e. "Error: Go program has already exited" is thrown otherwise on host
Expand Down
35 changes: 23 additions & 12 deletions go/run-tiny.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@ async function main() {

let usedGas = 0;

console.log(go.importObject)
//console.log(go.importObject)
go.importObject.metering = {
usegas: function (value) {
usedGas += value;
}
}

let moduleExports = {};

global.redstone.go = {
console: {
log: function (...args) {
Expand Down Expand Up @@ -74,9 +76,17 @@ async function main() {
}
}
},
},
WasmModule: {
registerWasmModule: function(moduleId) {
moduleExports = global[moduleId];
delete moduleId;
console.log(moduleExports);
}
}
}


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

const wasm = module.instance;
go.run(wasm);

console.log(wasm.exports);

console.log('\nlang():', lang());
console.log('\ncontractType():', contractType());
console.log('\ninitState():', initState(JSON.stringify(
console.log('calling go run');
go.run(wasm);
console.log('go run called');
console.log('\nlang():', moduleExports.lang());
console.log('\ncontractType():', moduleExports.contractType());
console.log('\ninitState():', moduleExports.initState(JSON.stringify(
{
"ticker": "EXAMPLE_PST_TOKEN",
"owner": "uhE-QeYS8i4pmUtnxQyHD7dzXFNaJ9oMK-IM-QPNY6M",
Expand All @@ -102,13 +113,13 @@ async function main() {
}
}
)));
console.log('\ncurrentState()', JSON.parse(currentState()));
console.log('\ncurrentState()', JSON.parse(moduleExports.currentState()));

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

usedGas = 0;

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

console.log('\ncurrentState()', JSON.parse(currentState()));
console.log('\ncurrentState()', JSON.parse(moduleExports.currentState()));

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

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

console.log("\n\nChecking exception handling (should throw here)");
try {
await handle(JSON.stringify({
await moduleExports.handle(JSON.stringify({
function: 'someRandomFunction',
}));
} catch (e) {
Expand Down
149 changes: 0 additions & 149 deletions go/run.js

This file was deleted.

Loading

0 comments on commit 7bc7535

Please sign in to comment.