Skip to content

Commit

Permalink
Create NexusModel.js
Browse files Browse the repository at this point in the history
  • Loading branch information
KOSASIH authored Aug 11, 2024
1 parent b2ef373 commit 77b6a7a
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions pi-nexus-blockchain/models/NexusModel.js
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit 77b6a7a

Please sign in to comment.