From 77b6a7a1c3204a4cda4afce41f2e319e6d61f6de Mon Sep 17 00:00:00 2001 From: KOSASIH Date: Sun, 11 Aug 2024 15:24:58 +0700 Subject: [PATCH] Create NexusModel.js --- pi-nexus-blockchain/models/NexusModel.js | 70 ++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 pi-nexus-blockchain/models/NexusModel.js diff --git a/pi-nexus-blockchain/models/NexusModel.js b/pi-nexus-blockchain/models/NexusModel.js new file mode 100644 index 000000000..bcd46db0c --- /dev/null +++ b/pi-nexus-blockchain/models/NexusModel.js @@ -0,0 +1,70 @@ +import { Model, DataTypes } from 'sequelize'; +import { sequelize } from '../database'; +import { BlockchainModel } from './BlockchainModel'; + +class NexusModel extends Model { + static init(sequelize) { + super.init({ + id: { + type: DataTypes.UUID, + defaultValue: DataTypes.UUIDV4, + primaryKey: true, + }, + address: { + type: DataTypes.STRING, + allowNull: false, + unique: true, + }, + balance: { + type: DataTypes.BIGINT, + allowNull: false, + defaultValue: 0, + }, + blockchainId: { + type: DataTypes.UUID, + references: { + model: BlockchainModel, + key: 'id', + }, + }, + }, { + sequelize, + modelName: 'Nexus', + tableName: 'nexus', + timestamps: true, + underscored: true, + }); + } + + static associate(models) { + this.belongsTo(models.Blockchain, { foreignKey: 'blockchainId', onDelete: 'CASCADE' }); + } + + async deposit(amount) { + this.balance += amount; + await this.save(); + } + + async withdraw(amount) { + if (this.balance < amount) { + throw new Error('Insufficient balance'); + } + this.balance -= amount; + await this.save(); + } + + async transfer(to, amount) { + if (this.balance < amount) { + throw new Error('Insufficient balance'); + } + const toNexus = await NexusModel.findOne({ where: { address: to } }); + if (!toNexus) { + throw new Error('Recipient not found'); + } + this.balance -= amount; + toNexus.balance += amount; + await Promise.all([this.save(), toNexus.save()]); + } +} + +export default NexusModel;