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