From 90b90dc46161b6eadfc71b37bad41d9f4cd61d5c Mon Sep 17 00:00:00 2001 From: Arnaud Bailly Date: Tue, 2 Dec 2025 08:41:54 +0100 Subject: introduce test (with a bug) using LevelDB --- pbt/ts/src/levelbank.ts | 52 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 pbt/ts/src/levelbank.ts (limited to 'pbt/ts/src/levelbank.ts') diff --git a/pbt/ts/src/levelbank.ts b/pbt/ts/src/levelbank.ts new file mode 100644 index 0000000..ead4e38 --- /dev/null +++ b/pbt/ts/src/levelbank.ts @@ -0,0 +1,52 @@ +// Specify types of keys and values (any, in the case of json). + +import {Level} from 'level'; +import {Account, Bank} from './bank'; +import {Option, fromNullable} from 'fp-ts/lib/Option'; + +export class LevelBank implements Bank { + db: Level; + file: string; + + constructor(file: string) { + this.file = file; + this.db = new Level(file, { + valueEncoding: 'json', + }); + } + + async populateWith( + initialAccounts: Map, + ): Promise { + await this.db.open({createIfMissing: true}); + + const puts: Promise[] = []; + + initialAccounts.forEach((v, k) => { + puts.push(this.db.put(k, v)); + }); + + await Promise.all(puts); + + return this; + } + + async balance(account: string): Promise> { + const result = await this.db.get(account); + return fromNullable(result); + } + + async deposit(account: string, amt: number): Promise { + const current = await this.db.get(account); + if (current) { + await this.db.put(account, current + amt); + } + } + + async withdraw(account: string, amt: number): Promise { + const current = await this.db.get(account); + if (current) { + await this.db.put(account, current + amt); + } + } +} -- cgit v1.3.1