dao-governance-framework/forum-network/src/classes/availability.js

62 lines
1.6 KiB
JavaScript
Raw Normal View History

2023-01-02 13:14:32 -06:00
import { Action } from './action.js';
2022-12-31 16:08:42 -06:00
import { Actor } from './actor.js';
2023-01-01 21:09:02 -06:00
class Worker {
2023-01-18 01:07:10 -06:00
constructor(tokenId) {
this.tokenId = tokenId;
this.stakeAmount = 0;
this.available = true;
this.assignedRequestId = null;
2023-01-01 21:09:02 -06:00
}
}
2022-12-31 16:08:42 -06:00
/**
* Purpose: Enable staking reputation to enter the pool of workers
*/
2023-01-01 21:09:02 -06:00
export class Availability extends Actor {
workers = new Map();
constructor(bench, name, scene) {
super(name, scene);
this.bench = bench;
2023-01-02 13:14:32 -06:00
this.actions = {
assignWork: new Action('assign work', scene),
};
2023-01-01 21:09:02 -06:00
}
2023-01-18 01:07:10 -06:00
register({ stakeAmount, tokenId }) {
2023-01-05 01:19:14 -06:00
// TODO: expire after duration
2023-01-01 21:09:02 -06:00
// ? Is a particular stake amount required?
2023-01-18 01:07:10 -06:00
const worker = this.workers.get(tokenId) ?? new Worker(tokenId);
2023-01-01 21:09:02 -06:00
if (!worker.available) {
2023-01-12 09:04:17 -06:00
throw new Error('Worker is already registered and busy. Can not increase stake.');
2023-01-01 21:09:02 -06:00
}
2023-01-18 01:07:10 -06:00
worker.stakeAmount += stakeAmount;
2023-01-05 01:19:14 -06:00
// TODO: Interact with Bench contract to encumber reputation?
2023-01-18 01:07:10 -06:00
this.workers.set(tokenId, worker);
2023-01-01 21:09:02 -06:00
}
2023-01-05 01:19:14 -06:00
// unregister() { }
2023-01-01 21:09:02 -06:00
get availableWorkers() {
return Array.from(this.workers.values()).filter(({ available }) => !!available);
}
async assignWork(requestId) {
// Get random worker
2023-01-05 01:19:14 -06:00
// TODO: Probability proportional to stakes
2023-01-01 21:09:02 -06:00
const index = Math.floor(Math.random() * this.availableWorkers.length);
const worker = this.availableWorkers[index];
worker.available = false;
worker.assignedRequestId = requestId;
2023-01-02 13:14:32 -06:00
// TODO: Notify assignee
2023-01-05 01:19:14 -06:00
return worker;
2023-01-02 13:14:32 -06:00
}
async getAssignedWork(reputationPublicKey) {
const worker = this.workers.get(reputationPublicKey);
return worker.assignedRequestId;
2023-01-01 21:09:02 -06:00
}
}