@broxus/js-core
Version:
MobX-based JavaScript Core library
483 lines (482 loc) • 18.7 kB
JavaScript
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 { VoteEscrowProposalUtils, } from '../../models/vote-escrow-proposal/VoteEscrowProposalUtils';
import { areAddressesEqual, contractStateChangeDebugMessage, getRandomInt, ProviderNotDefinedError, subscribeDebugMessage, syncErrorMessage, unsubscribeDebugMessage, unsubscribeErrorMessage, } from '../../utils';
export class VoteEscrowProposal extends SmartContractModel {
_connection;
options;
_provider;
static Utils = VoteEscrowProposalUtils;
/**
* @param {ProviderRpcClient} _connection
* Standalone RPC client that doesn't require connection to the TVM wallet provider
* @param {Address | string} address
* VoteEscrowProposal root address
* @param {Readonly<VoteEscrowProposalCtorParams>} [options]
* VoteEscrowProposal Smart Contract Model options
* @param {ProviderRpcClient} [_provider]
* 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(() => ({
evmActions: [],
tvmActions: [],
}));
makeObservable(this);
}
/**
* @param {ProviderRpcClient} connection
* Standalone RPC client that doesn't require connection to the TVM wallet provider
* @param {Address | string} address
* VoteEscrowProposal root address
* @param {Readonly<VoteEscrowProposalCreateOptions>} [options]
* VoteEscrowProposal Smart Contract Model options
* @param {ProviderRpcClient} [provider]
* RPC provider that require connection to the TVM wallet
*/
static async create(connection, address, options, provider) {
const { sync = true, watch, watchCallback, ...restOptions } = { ...options };
const proposal = new VoteEscrowProposal(connection, address, restOptions, provider);
if (sync) {
await proposal.sync({ force: false });
}
if (watch) {
await proposal.watch(watchCallback);
}
return proposal;
}
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 });
if (!this.isDeployed) {
throwException('VoteEscrowProposal is not deployed');
}
const [actions, configs, overview] = await Promise.all([
VoteEscrowProposal.Utils.getActions(this._connection, this.address, state),
VoteEscrowProposal.Utils.getConfig(this._connection, this.address, state),
VoteEscrowProposal.Utils.getOverview(this._connection, this.address, state),
]);
this.setData({ ...actions, ...configs, ...overview });
}
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 cancel(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 VoteEscrowProposal.Utils.cancel(this._provider, this.address, 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 === 'Canceled');
if (!event) {
return undefined;
}
if (process.env.NODE_ENV !== 'production') {
debug(`%c${this.constructor.name}%c %cCanceled%c event was captured`, successLabelStyle, inheritTextStyle, successTextStyle, inheritTextStyle, event);
}
await params.onTransactionSuccess?.({
callId,
input: undefined,
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 Unsubscribed from the proposal canceling stream`, warningLabelStyle, inheritTextStyle);
}
await subscriber?.unsubscribe();
}
}
async execute(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 VoteEscrowProposal.Utils.execute(this._provider, this.address, 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 === 'Executed');
if (!event) {
return undefined;
}
if (process.env.NODE_ENV !== 'production') {
debug(`%c${this.constructor.name}%c %cExecuted%c event was captured`, successLabelStyle, inheritTextStyle, successTextStyle, inheritTextStyle, event);
}
await params.onTransactionSuccess?.({
callId,
input: undefined,
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 Unsubscribed from the proposal executing stream`, warningLabelStyle, inheritTextStyle);
}
await subscriber?.unsubscribe();
}
}
async queue(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 VoteEscrowProposal.Utils.queue(this._provider, this.address, 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 === 'Queued');
if (!event) {
return undefined;
}
if (process.env.NODE_ENV !== 'production') {
debug(`%c${this.constructor.name}%c %cQueued%c event was captured`, successLabelStyle, inheritTextStyle, successTextStyle, inheritTextStyle, event);
}
await params.onTransactionSuccess?.({
callId,
input: { executionTime: Number(event.data.executionTime) },
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 Unsubscribed from the proposal queueing stream`, warningLabelStyle, inheritTextStyle);
}
await subscriber?.unsubscribe();
}
}
get evmActions() {
return this._data.evmActions;
}
get tvmActions() {
return this._data.tvmActions;
}
get gracePeriod() {
return this._data.gracePeriod;
}
get quorumVotes() {
return this._data.quorumVotes;
}
get threshold() {
return this._data.threshold;
}
get timeLock() {
return this._data.timeLock;
}
get votingDelay() {
return this._data.votingDelay;
}
get votingPeriod() {
return this._data.votingPeriod;
}
get againstVotes() {
return this._data.againstVotes;
}
get description() {
return this._data.description;
}
get endTime() {
return this._data.endTime;
}
get executionTime() {
return this._data.executionTime;
}
get forVotes() {
return this._data.forVotes;
}
get proposer() {
return this._data.proposer;
}
get startTime() {
return this._data.startTime;
}
get state() {
return this._data.state;
}
decodeTransaction(args) {
return VoteEscrowProposal.Utils.decodeTransaction(this._connection, this.address, args);
}
decodeTransactionEvents(transaction) {
return VoteEscrowProposal.Utils.decodeTransactionEvents(this._connection, this.address, transaction);
}
}
__decorate([
action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", Promise)
], VoteEscrowProposal.prototype, "sync", null);
__decorate([
action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Function]),
__metadata("design:returntype", Promise)
], VoteEscrowProposal.prototype, "watch", null);
__decorate([
action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", Promise)
], VoteEscrowProposal.prototype, "unwatch", null);
__decorate([
action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object]),
__metadata("design:returntype", Promise)
], VoteEscrowProposal.prototype, "cancel", null);
__decorate([
action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object]),
__metadata("design:returntype", Promise)
], VoteEscrowProposal.prototype, "execute", null);
__decorate([
action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object]),
__metadata("design:returntype", Promise)
], VoteEscrowProposal.prototype, "queue", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowProposal.prototype, "evmActions", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowProposal.prototype, "tvmActions", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowProposal.prototype, "gracePeriod", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowProposal.prototype, "quorumVotes", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowProposal.prototype, "threshold", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowProposal.prototype, "timeLock", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowProposal.prototype, "votingDelay", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowProposal.prototype, "votingPeriod", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowProposal.prototype, "againstVotes", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowProposal.prototype, "description", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowProposal.prototype, "endTime", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowProposal.prototype, "executionTime", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowProposal.prototype, "forVotes", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowProposal.prototype, "proposer", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowProposal.prototype, "startTime", null);
__decorate([
computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], VoteEscrowProposal.prototype, "state", null);
__decorate([
action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", Promise)
], VoteEscrowProposal.prototype, "decodeTransaction", null);
__decorate([
action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", Promise)
], VoteEscrowProposal.prototype, "decodeTransactionEvents", null);