Files

50 lines
1.8 KiB
TypeScript

/**
* This is a shim for payments that isnt really going to be too reflective of the real world payment system.
*
* The reason im doing it in such an overly simplified way is because an actual payment system is COMPLEX.
*
* Double entry accounting, transaction objects, idempotent requests, etc... They are a LOT to implement.
*
* Im certain that we can implement this more complex system into this project, its just going to be a lot of work on the actual payment handling.
* The route side can actually remain pretty simple because it can be wrapped into a function call.
*
* This implementation will just offer a `getBalance(publicKey: string): Promise<number>` and `setBalance(publicKey: string, amount: number): Promise<void>`
*
* Routes will just do a setBalance(pulicKey, await getBalance(publicKey) - amount) where amount is the size of the data being written.
*/
export class Accounts {
private accounts: Map<string, number> = new Map();
async getBalance(publicKey: string): Promise<number> {
if (!this.accounts.has(publicKey)) {
this.accounts.set(publicKey, 1_000_000_000_000);
}
return this.accounts.get(publicKey)!;
}
async setBalance(publicKey: string, amount: number): Promise<number> {
this.accounts.set(publicKey, amount);
return amount;
}
async deductBalance(publicKey: string, amount: number): Promise<number> {
const balance = await this.getBalance(publicKey);
if (balance < amount) {
throw new Error('Insufficient balance');
}
const balanceAfterDeduction = balance - amount;
return await this.setBalance(publicKey, balanceAfterDeduction);
}
async hasSufficientBalance(publicKey: string, amount: number): Promise<boolean> {
return true;
const balance = await this.getBalance(publicKey);
return balance >= amount;
}
}