Skip to content

Commit

Permalink
Merge branch 'dev' into 'master'
Browse files Browse the repository at this point in the history
Release 4.0.0

See merge request ergo/rosen-bridge/watcher!308
  • Loading branch information
vorujack committed Oct 15, 2024
2 parents 013ffd9 + 18a9777 commit abd48e1
Show file tree
Hide file tree
Showing 31 changed files with 451 additions and 128 deletions.
2 changes: 2 additions & 0 deletions .changeset/witty-maps-camp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
# @rosen-bridge/watcher

## 4.0.0

### Major Changes

- Support contract and tokensMap version and update info controller for version configs
- Update watcher regarding to decimal drop refactor

### Minor Changes

- Add warn level to logger health parameter and tune the thresholds
- Add ethereum health check parameters
- Integrate Ethereum network

### Patch Changes

- Update scanner packages
- Always check ergo node sync status as a health parameter
- Log current watcher version
- Update significant decimal for tokens that are already stored in db
- Fix watcher network switch in scanner init

## 3.2.2

### Patch Changes
Expand Down
26 changes: 19 additions & 7 deletions config/default.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
network: '' # which scanner network used in this watcher ergo/cardano/bitcoin
network: '' # which scanner network used in this watcher ergo/cardano/bitcoin/ethereum
observation:
confirmation: 60 # number of required block confirmations to create the commitment after observing an event
validThreshold: 12960 # observations that have not been triggered won't be processed after this period (in blocks)
Expand Down Expand Up @@ -35,6 +35,14 @@ cardano:
projectId: '' # blockfrost project Id
timeout: 10 # blockfrost request timeout
interval: 20 # blockfrost check timeout
ethereum:
type: '' # options: rpc
initial:
height: -1 # initial height of scanning
rpc:
url: '' # rpc url
interval: 20 # rpc scanning interval (in seconds)
timeout: 10 # rpc request timeout (in seconds)
ergo:
network: 'Mainnet' # ergo network type. testnet or mainnet
type: 'node' # ergo scanner type. options: node, explorer
Expand Down Expand Up @@ -93,11 +101,11 @@ healthCheck:
ergWarnThreshold: 1000000000 # minimum recommended erg balance
ergCriticalThreshold: 100000000 # minimum required erg balance
ergoScanner:
warnDifference: 2 # warning difference between existing and scanned blocks height
criticalDifference: 10 # critical difference between existing and scanned blocks height
warnDifference: 5 # warning difference between existing and scanned blocks height
criticalDifference: 20 # critical difference between existing and scanned blocks height
ergoNode:
maxHeightDifference: 2 # maximum difference between header height and full height
maxBlockTime: 30 # maximum time to see a new block in minutes
maxBlockTime: 30 # maximum time to see a new block in minutes
minPeerCount: 10 # minimum recommended peers
maxPeerHeightDifference: 2 # maximum difference between peers and our node
cardanoScanner:
Expand All @@ -106,12 +114,16 @@ healthCheck:
bitcoinScanner:
warnDifference: 2 # warning difference between existing and scanned blocks height
criticalDifference: 10 # critical difference between existing and scanned blocks height
ethereumScanner:
warnDifference: 40 # warning difference between existing and scanned blocks height
criticalDifference: 160 # critical difference between existing and scanned blocks height
permit:
warnCommitmentCount: 4 # warning remaining permits for creating commitment
criticalCommitmentCount: 0 # critical remaining permits for creating commitment
errorLog:
maxAllowedCount: 2 # maximum allowed error log lines
duration: 100000 # error log duration time check in milliseconds
logs:
duration: 600 # log duration time check (in seconds)
maxAllowedErrorCount: 1 # maximum allowed error log lines
maxAllowedWarnCount: 10 # maximum allowed warn log lines
redeemSwapEnabled: true # if set true when no permit left, system automatically redeem new commitments and commit again for old observations
rewardCollection:
threshold: 100000 # RSN threshold for reward collection
Expand Down
3 changes: 3 additions & 0 deletions docker/custom-environment-variables.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,7 @@ cardano:
authToken: 'KOIOS_AUTH_TOKEN'
blockfrost:
projectId: 'BLOCKFROST_PROJECT_ID'
ethereum:
rpc:
authToken: 'ETHEREUM_RPC_AUTH_TOKEN'
overrideLokiBasicAuth: 'OVERRIDE_LOKI_BASIC_AUTH'
33 changes: 31 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@rosen-bridge/watcher",
"version": "3.2.2",
"version": "4.0.0",
"description": "Rosen bridge Watcher service",
"main": "index.js",
"type": "module",
Expand Down Expand Up @@ -81,6 +81,8 @@
"@rosen-bridge/bitcoin-observation-extractor": "^4.0.7",
"@rosen-bridge/bitcoin-rpc-scanner": "^0.2.8",
"@rosen-bridge/discord-notification": "^0.1.3",
"@rosen-bridge/evm-observation-extractor": "^3.0.5",
"@rosen-bridge/evm-rpc-scanner": "^1.0.4",
"@rosen-bridge/health-check": "6.0.3",
"@rosen-bridge/log-level-check": "^1.0.3",
"@rosen-bridge/minimum-fee": "^2.1.0",
Expand Down
33 changes: 27 additions & 6 deletions src/api/Transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import { AddressBalance } from '../ergo/interfaces';
import { ChangeBoxCreationError, NoWID, NotEnoughFund } from '../errors/errors';
import { DetachWID } from '../transactions/detachWID';
import {
ERGO_CHAIN_NAME,
ERGO_NATIVE_ASSET,
WID_LOCK_COUNT,
WID_MINT_COUNT,
WID_UNLOCK_COUNT,
Expand Down Expand Up @@ -112,6 +114,7 @@ export class Transaction {

/**
* Get required permit count
* returns the wrapped amount
*/
getRequiredPermitsCountPerEvent = async () => {
const configBox = await Transaction.boxes.getRepoConfigBox();
Expand All @@ -127,6 +130,7 @@ export class Transaction {

/**
* calculate total permit for current user
* returns the wrap amount
* @returns
*/
getTotalPermit = async (): Promise<bigint> => {
Expand Down Expand Up @@ -165,8 +169,13 @@ export class Transaction {
throw Error('one of registers (4, 5) of repo box is not set');
}

const tokenMap = getConfig().token.tokenMap;
const collateralBox = await Transaction.boxes.getCollateralBox(wid);
const totalRwt = BigInt(collateralBox.register_value(5)!.to_i64().to_str());
const totalRwt = tokenMap.unwrapAmount(
getConfig().rosen.RWTId,
BigInt(collateralBox.register_value(5)!.to_i64().to_str()),
ERGO_CHAIN_NAME
).amount;
const completeReturn = totalRwt == RWTCount;

const inputBoxes = [repoBox, collateralBox, permitBoxes[0], widBox];
Expand Down Expand Up @@ -506,6 +515,7 @@ export class Transaction {

/**
* get Erg and RSN collateral
* returns the wrapped amount
* CAUTION: this function removed in watcher refactor
*/
getCollateral = async () => {
Expand Down Expand Up @@ -555,9 +565,18 @@ export class Transaction {
status: 500,
};
}
const tokenMap = getConfig().token.tokenMap;
const collateral = await this.getCollateral();
const ErgCollateral = collateral.erg;
const RSNCollateral = collateral.rsn;
const ErgCollateral = tokenMap.unwrapAmount(
ERGO_NATIVE_ASSET,
collateral.erg,
ERGO_CHAIN_NAME
).amount;
const RSNCollateral = tokenMap.unwrapAmount(
getConfig().rosen.RSN,
collateral.rsn,
ERGO_CHAIN_NAME
).amount;

const inputBoxes = [repoBox];
const RSNTokenId = Transaction.RSN.to_str();
Expand Down Expand Up @@ -650,9 +669,11 @@ export class Transaction {
)
);
} else {
const collateralRwtCount = BigInt(
collateralBox!.register_value(5)!.to_i64().to_str()
);
const collateralRwtCount = tokenMap.unwrapAmount(
getConfig().rosen.RWTId,
BigInt(collateralBox!.register_value(5)!.to_i64().to_str()),
ERGO_CHAIN_NAME
).amount;
const rsnCollateral = ErgoUtils.getBoxAssetsSum([collateralBox!]).filter(
(token) => token.tokenId == getConfig().rosen.RSN
);
Expand Down
26 changes: 18 additions & 8 deletions src/api/address.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import express, { Request, Response } from 'express';
import { getConfig } from '../config/config';
import { validationResult, check } from 'express-validator';
import { validationResult } from 'express-validator';
import { generateSK } from '../utils/utils';
import { ErgoUtils } from '../ergo/utils';
import { JsonBI } from '../ergo/network/parser';
import {
ERGO_DECIMALS,
ERGO_NATIVE_ASSET,
ERGO_NATIVE_ASSET_NAME,
} from '../config/constants';
import { ERGO_CHAIN_NAME, ERGO_NATIVE_ASSET } from '../config/constants';
import WinstonLogger from '@rosen-bridge/winston-logger';

const logger = WinstonLogger.getInstance().getLogger(import.meta.url);
Expand Down Expand Up @@ -49,10 +45,24 @@ addressRouter.get('/assets', async (req: Request, res: Response) => {
tokens.push({
amount: balance.nanoErgs,
tokenId: ERGO_NATIVE_ASSET,
decimals: ERGO_DECIMALS,
name: ERGO_NATIVE_ASSET_NAME,
name: ERGO_NATIVE_ASSET,
isNativeToken: true,
});
const tokenMap = getConfig().token.tokenMap;
tokens = tokens.map((token) => {
const wrappedToken = tokenMap.wrapAmount(
token.tokenId,
token.amount,
ERGO_CHAIN_NAME
);
const significantDecimal = tokenMap.getSignificantDecimals(token.tokenId);
return {
...token,
amount: wrappedToken.amount,
decimals:
significantDecimal != undefined ? significantDecimal : token.decimals,
};
});
const { tokenId, tokenName, sortByAmount } = req.query;
if (tokenId) {
tokens = tokens.filter((token) => token.tokenId === (tokenId as string));
Expand Down
26 changes: 22 additions & 4 deletions src/api/general.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,16 @@ import { HealthCheckSingleton } from '../../src/utils/healthCheck';
import { Transaction } from './Transaction';
import WinstonLogger from '@rosen-bridge/winston-logger';
import packageJson from '../../package.json' assert { type: 'json' };
import { ERGO_CHAIN_NAME, ERGO_NATIVE_ASSET } from '../config/constants';

const logger = WinstonLogger.getInstance().getLogger(import.meta.url);

interface GeneralInfo {
version: string;
versions: {
app: string;
contract: string;
tokensMap: string;
};
currentBalance: bigint;
network: string;
permitsPerEvent: bigint;
Expand Down Expand Up @@ -38,15 +43,28 @@ const generalRouter = express.Router();
*/
generalRouter.get('/', async (req: Request, res: Response) => {
try {
const tokenMap = getConfig().token.tokenMap;
const collateral = await Transaction.getInstance().getCollateral();
const info: GeneralInfo = {
version: packageJson.version,
currentBalance: (await ErgoUtils.getWatcherBalance()).nanoErgs,
versions: {
app: packageJson.version,
contract: getConfig().rosen.contractVersion,
tokensMap: getConfig().token.version,
},
currentBalance: tokenMap.wrapAmount(
ERGO_NATIVE_ASSET,
(await ErgoUtils.getWatcherBalance()).nanoErgs,
ERGO_CHAIN_NAME
).amount,
network: getConfig().general.networkWatcher,
permitsPerEvent:
await Transaction.getInstance().getRequiredPermitsCountPerEvent(),
permitCount: {
active: await ErgoUtils.getPermitCount(getConfig().rosen.RWTId),
active: tokenMap.wrapAmount(
getConfig().rosen.RWTId,
await ErgoUtils.getPermitCount(getConfig().rosen.RWTId),
ERGO_CHAIN_NAME
).amount,
total: await Transaction.getInstance().getTotalPermit(),
},
health: {
Expand Down
20 changes: 16 additions & 4 deletions src/api/permit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { ApiResponse, Transaction } from './Transaction';
import { body, validationResult } from 'express-validator';
import WinstonLogger from '@rosen-bridge/winston-logger';
import { authenticateKey } from './authentication';
import { getConfig } from '../config/config';
import { ERGO_CHAIN_NAME } from '../config/constants';

const logger = WinstonLogger.getInstance().getLogger(import.meta.url);

Expand All @@ -22,10 +24,15 @@ permitRouter.post(
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const RSNCount = req.body.count;
const tokenMap = getConfig().token.tokenMap;
const RSNCount = tokenMap.unwrapAmount(
getConfig().rosen.RSN,
BigInt(req.body.count),
ERGO_CHAIN_NAME
).amount;
const watcherTransaction = Transaction.getInstance();
const response: ApiResponse = await watcherTransaction.getPermit(
BigInt(RSNCount)
RSNCount
);
if (response.status === 200) {
res.status(200).send({ txId: response.response });
Expand Down Expand Up @@ -53,10 +60,15 @@ permitRouter.post(
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const RWTCount = req.body.count;
const tokenMap = getConfig().token.tokenMap;
const RWTCount = tokenMap.unwrapAmount(
getConfig().rosen.RWTId,
BigInt(req.body.count),
ERGO_CHAIN_NAME
).amount;
const watcherTransaction = Transaction.getInstance();
const response: ApiResponse = await watcherTransaction.returnPermit(
BigInt(RWTCount)
RWTCount
);
if (response.status === 200) {
res.status(200).send({ txId: response.response });
Expand Down
Loading

0 comments on commit abd48e1

Please sign in to comment.