UNPKG

@broxus/js-core

Version:

MobX-based JavaScript Core library

548 lines (547 loc) 22.1 kB
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); }; import { debounce, debug, throwException } from '@broxus/js-utils'; import { action, computed, makeObservable } from 'mobx'; import { inheritTextStyle, successLabelStyle, successTextStyle, warningLabelStyle } from '../../console'; import { SmartContractModel } from '../../core'; import { VoteEscrow } from '../../models/vote-escrow'; import { VoteEscrowAccountUtils, } from '../../models/vote-escrow-account/VoteEscrowAccountUtils'; import { areAddressesEqual, contractStateChangeDebugMessage, getRandomInt, ProviderNotDefinedError, subscribeDebugMessage, syncErrorMessage, unsubscribeDebugMessage, unsubscribeErrorMessage, } from '../../utils'; export class VoteEscrowAccount extends SmartContractModel { _connection; options; _provider; static Utils = 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: [], })); 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) { 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(); 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') { subscribeDebugMessage(this.constructor.name, this.address); } return stream.on(debounce(async (event) => { if (process.env.NODE_ENV !== 'production') { const state = await this._connection.getProviderState(); contractStateChangeDebugMessage(this.constructor.name, this.address, event, state.networkId.toString()); } if (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') { unsubscribeDebugMessage(this.constructor.name, this.address); } } catch (e) { if (process.env.NODE_ENV !== 'production') { const state = await this._connection.getProviderState(); unsubscribeErrorMessage(this.constructor.name, this.address, e, state.networkId.toString()); } } } async tryUnlockCastedVotes(params, args) { if (!this._provider) { throw new ProviderNotDefinedError(this.constructor.name); } const callId = params.callId ?? getRandomInt(); const subscriber = new this._connection.Subscriber(); let transaction; try { const message = await 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 (!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') { debug(`%c${this.constructor.name}%c %cUnlockCastedVotes%c event was captured`, successLabelStyle, inheritTextStyle, successTextStyle, 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') { debug(`%c${this.constructor.name}%c Unsubscribe from VoteEscrowAccount unlock casted votes stream`, warningLabelStyle, inheritTextStyle); } await subscriber?.unsubscribe(); } } async tryUnlockVoteTokens(params, args) { if (!this._provider) { throw new ProviderNotDefinedError(this.constructor.name); } const callId = params.callId ?? getRandomInt(); const subscriber = new this._connection.Subscriber(); let transaction; try { const message = await 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 (!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') { debug(`%c${this.constructor.name}%c %cUnlockVotes%c event was captured`, successLabelStyle, inheritTextStyle, successTextStyle, 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') { debug(`%c${this.constructor.name}%c Unsubscribe from VoteEscrowAccount unlock vote tokens stream`, warningLabelStyle, inheritTextStyle); } await subscriber?.unsubscribe(); } } async castVote(params, args) { if (!this._provider) { throw new ProviderNotDefinedError(this.constructor.name); } const callId = params.callId ?? getRandomInt(); const subscriber = new this._connection.Subscriber(); let transaction; try { const message = await 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 (!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') { debug(`%c${this.constructor.name}%c %cVoteCast%c event was captured`, successLabelStyle, inheritTextStyle, successTextStyle, 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') { debug(`%c${this.constructor.name}%c Unsubscribe from VoteEscrowAccount unlock vote tokens stream`, warningLabelStyle, inheritTextStyle); } await subscriber?.unsubscribe(); } } async castVoteWithReason(params, args) { if (!this._provider) { throw new ProviderNotDefinedError(this.constructor.name); } const callId = params.callId ?? getRandomInt(); const subscriber = new this._connection.Subscriber(); let transaction; try { const message = await 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 (!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') { debug(`%c${this.constructor.name}%c %cVoteCast%c event was captured`, successLabelStyle, inheritTextStyle, successTextStyle, 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') { debug(`%c${this.constructor.name}%c Unsubscribe from VoteEscrowAccount unlock vote tokens stream`, warningLabelStyle, 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); } } __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], VoteEscrowAccount.prototype, "sync", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Function]), __metadata("design:returntype", Promise) ], VoteEscrowAccount.prototype, "watch", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", Promise) ], VoteEscrowAccount.prototype, "unwatch", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], VoteEscrowAccount.prototype, "tryUnlockCastedVotes", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], VoteEscrowAccount.prototype, "tryUnlockVoteTokens", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], VoteEscrowAccount.prototype, "castVote", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], VoteEscrowAccount.prototype, "castVoteWithReason", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", Promise) ], VoteEscrowAccount.prototype, "calculateMinGas", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", Promise) ], VoteEscrowAccount.prototype, "calculateVeAverage", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], VoteEscrowAccount.prototype, "activeDeposits", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], VoteEscrowAccount.prototype, "castedVotes", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], VoteEscrowAccount.prototype, "createdProposals", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], VoteEscrowAccount.prototype, "currentVersion", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], VoteEscrowAccount.prototype, "lastEpochVoted", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], VoteEscrowAccount.prototype, "lastUpdateTime", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], VoteEscrowAccount.prototype, "lockedTokens", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], VoteEscrowAccount.prototype, "qubeBalance", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], VoteEscrowAccount.prototype, "unlockedQubes", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], VoteEscrowAccount.prototype, "user", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], VoteEscrowAccount.prototype, "veQubeAverage", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], VoteEscrowAccount.prototype, "veQubeAveragePeriod", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], VoteEscrowAccount.prototype, "veQubeBalance", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], VoteEscrowAccount.prototype, "voteEscrow", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], VoteEscrowAccount.prototype, "decodeTransactionEvents", null);