@broxus/js-core
Version:
MobX-based JavaScript Core library
482 lines (481 loc) • 20.3 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.Dex = void 0;
const js_utils_1 = require("@broxus/js-utils");
const mobx_1 = require("mobx");
const console_1 = require("../../console");
const constants_1 = require("../../constants");
const core_1 = require("../../core");
const dex_pair_1 = require("../../models/dex-pair");
const dex_stable_pool_1 = require("../../models/dex-stable-pool");
const DexUtils_1 = require("../../models/dex/DexUtils");
const utils_1 = require("../../utils");
class Dex extends core_1.SmartContractModel {
_connection;
options;
_provider;
static Utils = DexUtils_1.DexUtils;
/**
* @param {ProviderRpcClient} _connection
* Standalone RPC client that doesn't require connection to the TVM wallet provider
* @param {Address | string} address
* DexRoot root address
* @param {Readonly<DexCtorOptions>} [options]
* (optional) DexRoot 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;
(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
* DexRoot root address
* @param {Readonly<DexCreateOptions>} [options]
* (optional) DexRoot 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 dex = new Dex(connection, address, restOptions, provider);
if (sync) {
await dex.sync({ force: false, ttl: options?.ttl });
}
if (watch) {
await dex.watch(watchCallback);
}
return dex;
}
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,
ttl: options?.ttl || constants_1.SECONDS_IN_HOUR * 1000,
});
if (!this.isDeployed) {
await this.syncComputedStorageData();
(0, js_utils_1.throwException)('Dex is not deployed');
}
const [manager, owner, vault] = await Promise.all([
Dex.Utils.getManager(this._connection, this.address, state),
Dex.Utils.getOwner(this._connection, this.address, state),
Dex.Utils.getVault(this._connection, this.address, state),
]);
this.setData({ manager, owner, vault });
}
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() {
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 deployAccount(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 expectedAddress = await this.getExpectedAccountAddress({ ownerAddress: params.ownerAddress });
const message = await Dex.Utils.deployAccount(this._provider, this.address, params, 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, expectedAddress)) {
return undefined;
}
const state = await (0, utils_1.getFullContractState)(this._connection, expectedAddress, { force: true });
if (!state?.isDeployed) {
return undefined;
}
await params.onTransactionSuccess?.({
callId,
input: {
callId,
dexAccountAddress: expectedAddress,
},
transaction: tx,
});
return tx.account;
})
.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 DexAccount deploying stream`, console_1.warningLabelStyle, console_1.inheritTextStyle);
}
await subscriber?.unsubscribe();
}
}
/**
* Stream-based **DexPair** deployment request
* @param {DexDeployPairParams} params
* @param {Partial<SendInternalParams>} args
* @return {Promise<Transaction | undefined>}
*/
async deployPair(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 Dex.Utils.deployPair(this._provider, this.address, {
leftRootAddress: params.leftRootAddress,
rightRootAddress: params.rightRootAddress,
sendGasTo: params.sendGasTo,
}, { bounce: true, ...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;
}
try {
const events = await this.decodeTransactionEvents(tx);
if (events.length === 0) {
return undefined;
}
const event = events.find(e => e.event === 'NewPoolCreated');
if (!event) {
return undefined;
}
const [leftRootAddress, rightRootAddress] = event.data.roots;
const address = await this.getExpectedPairAddress({ leftRootAddress, rightRootAddress });
if (!(0, utils_1.areAddressesEqual)(params.expectedAddress, address)) {
return undefined;
}
const isActive = await dex_pair_1.DexPair.Utils.isActive(this._connection, address);
if (isActive) {
if (process.env.NODE_ENV !== 'production') {
(0, js_utils_1.debug)(`%c${this.constructor.name}%c %cNewPoolCreated%c event was captured`, console_1.successLabelStyle, console_1.inheritTextStyle, console_1.successTextStyle, console_1.inheritTextStyle, event);
}
await params.onTransactionSuccess?.({
callId,
input: {
leftRootAddress,
pairAddress: address,
poolType: event.data.poolType,
rightRootAddress,
},
transaction: tx,
});
return event;
}
return undefined;
}
catch (e) {
(0, js_utils_1.error)('NewPoolCreated event captured with an error', e);
await params.onTransactionFailure?.({
callId,
error: e,
transaction: tx,
});
return null;
}
})
.delayed(s => s.first());
await stream();
return transaction;
}
catch (e) {
params.onTransactionFailure?.({
callId,
error: e,
});
throw e;
}
finally {
if (process.env.NODE_ENV !== 'production') {
(0, js_utils_1.debug)(`%c${this.constructor.name}%c Unsubscribe from DexPair creating stream`, console_1.warningLabelStyle, console_1.inheritTextStyle);
}
await subscriber?.unsubscribe();
}
}
/**
* Stream-based **DexStablePool** deployment request
* @param {DexDeployPoolParams} params
* @param {Partial<SendInternalParams>} args
* @return {Promise<Transaction | undefined>}
*/
async deployStablePool(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 Dex.Utils.deployStablePool(this._provider, this.address, {
roots: params.roots,
sendGasTo: params.sendGasTo,
}, { bounce: true, ...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;
}
try {
const events = await this.decodeTransactionEvents(tx);
if (events.length === 0) {
return undefined;
}
const event = events.find(e => e.event === 'NewPoolCreated');
if (!event) {
return undefined;
}
const address = await this.getExpectedPoolAddress({ roots: event.data.roots });
if (!(0, utils_1.areAddressesEqual)(params.expectedAddress, address)) {
return undefined;
}
const isActive = await dex_stable_pool_1.DexStablePool.Utils.isActive(this._connection, address);
if (isActive) {
if (process.env.NODE_ENV !== 'production') {
(0, js_utils_1.debug)(`%c${this.constructor.name}%c %cNewPoolCreated%c event was captured`, console_1.successLabelStyle, console_1.inheritTextStyle, console_1.successTextStyle, console_1.inheritTextStyle, event);
}
await params.onTransactionSuccess?.({
callId,
input: {
poolAddress: address,
poolType: event.data.poolType,
roots: event.data.roots,
},
transaction: tx,
});
return event;
}
return undefined;
}
catch (e) {
(0, js_utils_1.error)('NewPoolCreated event captured with an error', e);
await params.onTransactionFailure?.({
callId,
error: e,
transaction: tx,
});
return null;
}
})
.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 StablePool creating stream`, console_1.warningLabelStyle, console_1.inheritTextStyle);
}
await subscriber?.unsubscribe();
}
}
getExpectedAccountAddress(params) {
return Dex.Utils.getExpectedAccountAddress(this._connection, this.address, params, this.contractState);
}
getExpectedPairAddress(params) {
return Dex.Utils.getExpectedPairAddress(this._connection, this.address, params, this.contractState);
}
getExpectedPoolAddress(params) {
return Dex.Utils.getExpectedPoolAddress(this._connection, this.address, params, this.contractState);
}
get manager() {
return this._data.manager;
}
get owner() {
return this._data.owner;
}
get vault() {
return this._data.vault;
}
decodeEvent(args) {
return Dex.Utils.decodeEvent(this._connection, this.address, args);
}
decodeTransaction(args) {
return Dex.Utils.decodeTransaction(this._connection, this.address, args);
}
decodeTransactionEvents(transaction) {
return Dex.Utils.decodeTransactionEvents(this._connection, this.address, transaction);
}
}
exports.Dex = Dex;
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", Promise)
], Dex.prototype, "sync", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Function]),
__metadata("design:returntype", Promise)
], Dex.prototype, "watch", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", Promise)
], Dex.prototype, "unwatch", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object]),
__metadata("design:returntype", Promise)
], Dex.prototype, "deployAccount", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object]),
__metadata("design:returntype", Promise)
], Dex.prototype, "deployPair", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object]),
__metadata("design:returntype", Promise)
], Dex.prototype, "deployStablePool", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", Promise)
], Dex.prototype, "getExpectedAccountAddress", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", Promise)
], Dex.prototype, "getExpectedPairAddress", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", Promise)
], Dex.prototype, "getExpectedPoolAddress", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], Dex.prototype, "manager", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], Dex.prototype, "owner", null);
__decorate([
mobx_1.computed,
__metadata("design:type", Object),
__metadata("design:paramtypes", [])
], Dex.prototype, "vault", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", Promise)
], Dex.prototype, "decodeEvent", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", Promise)
], Dex.prototype, "decodeTransaction", null);
__decorate([
mobx_1.action.bound,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", Promise)
], Dex.prototype, "decodeTransactionEvents", null);