From 4eced65dbf3906c724209c2354f5d448b2c3d92d Mon Sep 17 00:00:00 2001 From: Ladd Hoffman Date: Thu, 2 Feb 2023 21:54:37 -0600 Subject: [PATCH] Add basic virtual machine concept --- forum-network/src/classes/vm.js | 65 ++++++++++++++++++++++ forum-network/src/index.html | 2 +- forum-network/src/tests/scripts/vm.test.js | 42 ++++++++++++++ forum-network/src/tests/vm.test.html | 32 +++++++++++ 4 files changed, 140 insertions(+), 1 deletion(-) create mode 100644 forum-network/src/classes/vm.js create mode 100644 forum-network/src/tests/scripts/vm.test.js create mode 100644 forum-network/src/tests/vm.test.html diff --git a/forum-network/src/classes/vm.js b/forum-network/src/classes/vm.js new file mode 100644 index 0000000..ee6f1a6 --- /dev/null +++ b/forum-network/src/classes/vm.js @@ -0,0 +1,65 @@ +import { Action } from './action.js'; + +class ContractRecord { + constructor(id, instance) { + this.id = id; + this.instance = instance; + } +} + +export class VMHandle { + constructor(vm, sender) { + this.vm = vm; + this.sender = sender; + this.actions = { + call: new Action('call'), + }; + } + + /** + * @param {string} id Contract ID + * @param {string} method + */ + callContract(id, method, ...args) { + const instance = this.vm.getContractInstance(id); + const fn = instance[method]; + if (!fn) throw new Error(`Contract ${id} method ${method} not found!`); + this.actions.call.log(this.sender, instance, method); + return fn.call(instance, this.sender, ...args); + } +} + +export class VM { + constructor() { + this.contracts = new Map(); + } + + /** + * @param {string} id + * @param {class} ContractClass + * @param {any[]} ...args Passed to contractClass constructor after `vm` + */ + addContract(id, ContractClass, ...args) { + const instance = new ContractClass(this, ...args); + const contract = new ContractRecord(id, instance); + this.contracts.set(id, contract); + } + + getHandle(sender) { + return new VMHandle(this, sender); + } + + /** + * @param {string} id + */ + getContract(id) { + return this.contracts.get(id); + } + + /** + * @param {string} id + */ + getContractInstance(id) { + return this.getContract(id)?.instance; + } +} diff --git a/forum-network/src/index.html b/forum-network/src/index.html index 0051aba..7f6fa7b 100644 --- a/forum-network/src/index.html +++ b/forum-network/src/index.html @@ -24,8 +24,8 @@ -

Tertiary