@broxus/js-core
Version:
MobX-based JavaScript Core library
552 lines (551 loc) • 22.9 kB
JavaScript
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoteEscrowAccount = void 0;
const js_utils_1 = require("@broxus/js-utils");
const mobx_1 = require("mobx");
const console_1 = require("../../console");
const core_1 = require("../../core");
const vote_escrow_1 = require("../../models/vote-escrow");
const VoteEscrowAccountUtils_1 = require("../../models/vote-escrow-account/VoteEscrowAccountUtils");
const utils_1 = require("../../utils");
class VoteEscrowAccount extends core_1.SmartContractModel {
_connection;
options;
_provider;
static Utils = VoteEscrowAccountUtils_1.VoteEscrowAccountUtils;
/**
* @param {ProviderRpcClient} _connection
* Standalone RPC client that doesn't require connection to the TVM wallet provider
* @param {Address | string} address
* VoteEscrowAccount root address
* @param {Readonly<VoteEscrowAccountCtorOptions>} [options]
* (optional) VoteEscrowAccount Smart Contract Model options
* @param {ProviderRpcClient} [_provider]
* (optional) RPC provider that require connection to the TVM wallet
*/
constructor(_connection, address, options, _provider) {
super(_connection, address);
this._connection = _connection;
this.options = options;
this._provider = _provider;
this.setData(() => ({
castedVotes: [],
createdProposals: [],
}));
(0, mobx_1.makeObservable)(this);
}
/**
* @param {ProviderRpcClient} connection
* Standalone RPC client that doesn't require connection to the TVM wallet provider
* @param {Address | string} address
* VoteEscrowAccount root address
* @param {Readonly<VoteEscrowAccountCreateOptions>} [options]
* (optional) VoteEscrowAccount Smart Contract Model options
* @param {ProviderRpcClient} [provider]
* (optional) RPC provider that require connection to the TVM wallet
*/
static async create(connection, address, options, provider) {
const { sync = true, watch, watchCallback, ...restOptions } = { ...options };
const voteEscrowAccount = new VoteEscrowAccount(connection, address, restOptions, provider);
if (sync) {
await voteEscrowAccount.sync({ force: false });
}
if (watch) {
await voteEscrowAccount.watch(watchCallback);
}
return voteEscrowAccount;
}
async sync(options) {
if (!options?.force && this.isSyncing) {
return;
}
try {
this.setState('isSyncing', !options?.silent);
const state = await this.syncContractState({ force: options?.force || !this.contractState });
await this.syncComputedStorageData();
if (!this.isDeployed) {
(0, js_utils_1.throwException)('VoteEscrowAccount is not deployed');
}
const [details, calculatedVeAverage, castedVotes, createdProposals, lockedTokens] = await Promise.all([
VoteEscrowAccount.Utils.getDetails(this._connection, this.address, state),
VoteEscrowAccount.Utils.calculateVeAverage(this._connection, this.address, state),
VoteEscrowAccount.Utils.castedVotes(this._connection, this.address, state),
VoteEscrowAccount.Utils.createdProposals(this._connection, this.address, state),
VoteEscrowAccount.Utils.lockedTokens(this._connection, this.address, state),
]);
this.setData({ ...details, ...calculatedVeAverage, castedVotes, createdProposals, lockedTokens });
}
catch (e) {
if (process.env.NODE_ENV !== 'production') {
const state = await this._connection.getProviderState();
(0, utils_1.syncErrorMessage)(this.constructor.name, this.address, e, state.networkId.toString());
}
}
finally {
this.setState('isSyncing', false);
}
}
async watch(callback) {
try {
this.contractSubscriber = new this._connection.Subscriber();
await this.contractSubscriber.states(this.address).delayed(stream => {
if (process.env.NODE_ENV !== 'production') {
(0, utils_1.subscribeDebugMessage)(this.constructor.name, this.address);
}
return stream.on((0, js_utils_1.debounce)(async (event) => {
if (process.env.NODE_ENV !== 'production') {
const state = await this._connection.getProviderState();
(0, utils_1.contractStateChangeDebugMessage)(this.constructor.name, this.address, event, state.networkId.toString());
}
if ((0, utils_1.areAddressesEqual)(event.address, this.address)) {
await this.sync({ force: !this.isSyncing, silent: true });
callback?.(...this.toJSON(true));
return;
}
await this.unwatch();
}, this.options?.watchDebounceDelay ?? 3000));
});
return this.contractSubscriber;
}
catch (e) {
await this.unwatch();
throw e;
}
}
async unwatch() {
if (this.contractSubscriber === undefined) {
return;
}
try {
await this.contractSubscriber?.unsubscribe();
this.contractSubscriber = undefined;
if (process.env.NODE_ENV !== 'production') {
(0, utils_1.unsubscribeDebugMessage)(this.constructor.name, this.address);
}
}
catch (e) {
if (process.env.NODE_ENV !== 'production') {
const state = await this._connection.getProviderState();
(0, utils_1.unsubscribeErrorMessage)(this.constructor.name, this.address, e, state.networkId.toString());
}
}
}
async tryUnlockCastedVotes(params, args) {
if (!this._provider) {
throw new utils_1.ProviderNotDefinedError(this.constructor.name);
}
const callId = params.callId ?? (0, utils_1.getRandomInt)();
const subscriber = new this._connection.Subscriber();
let transaction;
try {
const message = await vote_escrow_1.VoteEscrow.Utils.tryUnlockCastedVotes(this._provider, this.voteEscrow, { proposalIds: params.proposalIds }, { from: this.user, ...args });
await params.onSend?.(message, { callId });
transaction = await message.transaction;
await params.onTransactionSent?.({ callId, transaction });
const stream = await subscriber
.trace(transaction)
.filterMap(async (tx) => {
if (!(0, utils_1.areAddressesEqual)(tx.account, this.address)) {
return undefined;
}
const events = await this.decodeTransactionEvents(tx);
if (events.length === 0) {
return undefined;
}
const event = events.find(e => e.event === 'UnlockCastedVotes');
if (!event) {
return undefined;
}
if (process.env.NODE_ENV !== 'production') {
(0, js_utils_1.debug)(`%c${this.constructor.name}%c %cUnlockCastedVotes%c event was captured`, console_1.successLabelStyle, console_1.inheritTextStyle, console_1.successTextStyle, console_1.inheritTextStyle, event);
}
await params.onTransactionSuccess?.({
callId,
input: event.data,
transaction: tx,
});
return event;
})
.delayed(s => s.first());
await stream();
return transaction;
}
catch (e) {
params.onTransactionFailure?.({
callId,
error: e,
transaction,
});
throw e;
}
finally {
if (process.env.NODE_ENV !== 'production') {
(0, js_utils_1.debug)(`%c${this.constructor.name}%c Unsubscribe from VoteEscrowAccount unlock casted votes stream`, console_1.warningLabelStyle, console_1.inheritTextStyle);
}
await subscriber?.unsubscribe();
}
}
async tryUnlockVoteTokens(params, args) {
if (!this._provider) {
throw new utils_1.ProviderNotDefinedError(this.constructor.name);
}
const callId = params.callId ?? (0, utils_1.getRandomInt)();
const subscriber = new this._connection.Subscriber();
let transaction;
try {
const message = await vote_escrow_1.VoteEscrow.Utils.tryUnlockVoteTokens(this._provider, this.voteEscrow, { proposalId: params.proposalId }, args);
await params.onSend?.(message, { callId });
transaction = await message.transaction;
await params.onTransactionSent?.({ callId, transaction });
const stream = await subscriber
.trace(transaction)
.filterMap(async (tx) => {
if (!(0, utils_1.areAddressesEqual)(tx.account, this.address)) {
return undefined;
}
const events = await this.decodeTransactionEvents(tx);
if (events.length === 0) {
return undefined;
}
const event = events.find(e => e.event === 'UnlockVotes');
if (!event) {
return undefined;
}
if (process.env.NODE_ENV !== 'production') {
(0, js_utils_1.debug)(`%c${this.constructor.name}%c %cUnlockVotes%c event was captured`, console_1.successLabelStyle, console_1.inheritTextStyle, console_1.successTextStyle, console_1.inheritTextStyle, event);
}
await params.onTransactionSuccess?.({
callId,
input: event.data,
transaction: tx,
});
return event;
})
.delayed(s => s.first());
await stream();
return transaction;
}
catch (e) {
params.onTransactionFailure?.({
callId,
error: e,
transaction,
});
throw e;
}
finally {
if (process.env.NODE_ENV !== 'production') {
(0, js_utils_1.debug)(`%c${this.constructor.name}%c Unsubscribe from VoteEscrowAccount unlock vote tokens stream`, console_1.warningLabelStyle, console_1.inheritTextStyle);
}
await subscriber?.unsubscribe();
}
}
async castVote(params, args) {
if (!this._provider) {
throw new utils_1.ProviderNotDefinedError(this.constructor.name);
}
const callId = params.callId ?? (0, utils_1.getRandomInt)();
const subscriber = new this._connection.Subscriber();
let transaction;
try {
const message = await vote_escrow_1.VoteEscrow.Utils.castVote(this._provider, this.voteEscrow, {
proposalId: params.proposalId,
support: params.support,
}, args);
await params.onSend?.(message, { callId });
transaction = await message.transaction;
await params.onTransactionSent?.({ callId, transaction });
const stream = await subscriber
.trace(transaction)
.filterMap(async (tx) => {
if (!(0, utils_1.areAddressesEqual)(tx.account, this.address)) {
return undefined;
}
const events = await this.decodeTransactionEvents(tx);
if (events.length === 0) {
return undefined;
}
const event = events.find(e => e.event === 'VoteCast');
if (!event) {
return undefined;
}
if (process.env.NODE_ENV !== 'production') {
(0, js_utils_1.debug)(`%c${this.constructor.name}%c %cVoteCast%c event was captured`, console_1.successLabelStyle, console_1.inheritTextStyle, console_1.successTextStyle, console_1.inheritTextStyle, event);
}
await params.onTransactionSuccess?.({
callId,
input: event.data,
transaction: tx,
});
return event;
})
.delayed(s => s.first());
await stream();
return transaction;
}
catch (e) {
params.onTransactionFailure?.({
callId,
error: e,
transaction,
});
throw e;
}
finally {
if (process.env.NODE_ENV !== 'production') {
(0, js_utils_1.debug)(`%c${this.constructor.name}%c Unsubscribe from VoteEscrowAccount unlock vote tokens stream`, console_1.warningLabelStyle, console_1.inheritTextStyle);
}
await subscriber?.unsubscribe();
}
}
async castVoteWithReason(params, args) {
if (!this._provider) {
throw new utils_1.ProviderNotDefinedError(this.constructor.name);
}
const callId = params.callId ?? (0, utils_1.getRandomInt)();
const subscriber = new this._connection.Subscriber();
let transaction;
try {
const message = await vote_escrow_1.VoteEscrow.Utils.castVoteWithReason(this._provider, this.voteEscrow, {
proposalId: params.proposalId,
reason: params.reason,
support: params.support,
}, args);
await params.onSend?.(message, { callId });
transaction = await message.transaction;
await params.onTransactionSent?.({ callId, transaction });
const stream = await subscriber
.trace(transaction)
.filterMap(async (tx) => {
if (!(0, utils_1.areAddressesEqual)(tx.account, this.address)) {
return undefined;
}
const events = await this.decodeTransactionEvents(tx);
if (events.length === 0) {
return undefined;
}
const event = events.find(e => e.event === 'VoteCast');
if (!event) {
return undefined;
}
if (process.env.NODE_ENV !== 'production') {
(0, js_utils_1.debug)(`%c${this.constructor.name}%c %cVoteCast%c event was captured`, console_1.successLabelStyle, console_1.inheritTextStyle, console_1.successTextStyle, console_1.inheritTextStyle, event);
}
await params.onTransactionSuccess?.({
callId,
input: event.data,
transaction: tx,
});
return event;
})
.delayed(s => s.first());
await stream();
return transaction;
}
catch (e) {
params.onTransactionFailure?.({
callId,
error: e,
transaction,
});
throw e;
}
finally {
if (process.env.NODE_ENV !== 'production') {
(0, js_utils_1.debug)(`%c${this.constructor.name}%c Unsubscribe from VoteEscrowAccount unlock vote tokens stream`, console_1.warningLabelStyle, console_1.inheritTextStyle);
}
await subscriber?.unsubscribe();
}
}
calculateMinGas() {
return VoteEscrowAccount.Utils.calculateMinGas(this._connection, this.address, this.contractState);
}
calculateVeAverage() {
return VoteEscrowAccount.Utils.calculateVeAverage(this._connection, this.address, this.contractState);
}
get activeDeposits() {
return this._data.activeDeposits;
}
get castedVotes() {
return this._data.castedVotes;
}
get createdProposals() {
return this._data.createdProposals;
}
get currentVersion() {
return this._data.currentVersion;
}
get lastEpochVoted() {
return this._data.lastEpochVoted;
}
get lastUpdateTime() {
return this._data.lastUpdateTime;
}
get lockedTokens() {
return this._data.lockedTokens;
}
get qubeBalance() {
return this._data.qubeBalance;
}
get unlockedQubes() {
return this._data.unlockedQubes;
}
get user() {
return this._data.user;
}
get veQubeAverage() {
return this._data.veQubeAverage;
}
get veQubeAveragePeriod() {
return this._data.veQubeAveragePeriod;
}
get veQubeBalance() {
return this._data.veQubeBalance;
}
get voteEscrow() {
return this._data.voteEscrow;
}
decodeTransactionEvents(transaction) {
return VoteEscrowAccount.Utils.decodeTransactionEvents(this._connection, this.address, transaction);
}
}
exports.VoteEscrowAccount = VoteEscrowAccount;
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", Promise)
], VoteEscrowAccount.prototype, "sync", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Function]),
__metadata("design:returntype", Promise)
], VoteEscrowAccount.prototype, "watch", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", Promise)
], VoteEscrowAccount.prototype, "unwatch", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object]),
__metadata("design:returntype", Promise)
], VoteEscrowAccount.prototype, "tryUnlockCastedVotes", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object]),
__metadata("design:returntype", Promise)
], VoteEscrowAccount.prototype, "tryUnlockVoteTokens", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object]),
__metadata("design:returntype", Promise)
], VoteEscrowAccount.prototype, "castVote", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object]),
__metadata("design:returntype", Promise)
], VoteEscrowAccount.prototype, "castVoteWithReason", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", Promise)
], VoteEscrowAccount.prototype, "calculateMinGas", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", Promise)
], VoteEscrowAccount.prototype, "calculateVeAverage", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowAccount.prototype, "activeDeposits", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowAccount.prototype, "castedVotes", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowAccount.prototype, "createdProposals", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowAccount.prototype, "currentVersion", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowAccount.prototype, "lastEpochVoted", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowAccount.prototype, "lastUpdateTime", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowAccount.prototype, "lockedTokens", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowAccount.prototype, "qubeBalance", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowAccount.prototype, "unlockedQubes", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowAccount.prototype, "user", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowAccount.prototype, "veQubeAverage", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowAccount.prototype, "veQubeAveragePeriod", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowAccount.prototype, "veQubeBalance", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowAccount.prototype, "voteEscrow", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", Promise)
], VoteEscrowAccount.prototype, "decodeTransactionEvents", null);