Skip to content

Commit

Permalink
Merge pull request #2701 from w3f/will-v3.1.3
Browse files Browse the repository at this point in the history
add tests, update swagger endpoints, use enums
  • Loading branch information
wpank committed Mar 5, 2024
2 parents 59ac1da + 4d2bd34 commit 352f574
Show file tree
Hide file tree
Showing 33 changed files with 758 additions and 406 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@
"typedoc-plugin-markdown": "^3.17.1"
},
"dependencies": {
"@polkadot/api": "^10.11.2",
"@polkadot/rpc-provider": "^10.11.2",
"@polkadot/api": "^10.12.1",
"@polkadot/rpc-provider": "^10.12.1",
"@types/ws": "^8.5.10",
"axios": "^1.6.7",
"chalk": "4.1.2",
Expand Down
5 changes: 2 additions & 3 deletions packages/common/src/chaindata/queries/Era.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,13 +208,12 @@ export const findEraBlockHash = async (
return ["", "API at block hash is null"];
}

const testEra = await apiAt.query.staking.activeEra();
const testEra = await apiAt.query.staking.currentEra();
if (testEra && testEra.isEmpty) {
logger.info(`Test era is empty: ${JSON.stringify(testEra)}`);
return ["", "Test era is none"];
}
const testEraJSON = testEra.toJSON() as { index: string; start: string };
const testIndex = testEraJSON.index ? Number(testEraJSON.index) : 0;
const testIndex = testEra.unwrap().toNumber();
if (era == testIndex) {
return [blockHash.toString(), null];
}
Expand Down
6 changes: 6 additions & 0 deletions packages/common/src/db/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,12 @@ export const CandidateSchema = new Schema({

export const CandidateModel = mongoose.model("Candidate", CandidateSchema);

export interface Era {
lastNominatedEraIndex: string;
nextNomination: number;
when: number;
}

export const EraSchema = new Schema({
// The last era a nomination took place
lastNominatedEraIndex: { type: String, default: "0" },
Expand Down
2 changes: 1 addition & 1 deletion packages/common/src/db/queries/Candidate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ export const getIdentityName = async (
.lean<Identity>()
.select({ name: 1 });

return identity?.name;
return identity?.name || null;
}
};

Expand Down
52 changes: 29 additions & 23 deletions packages/common/src/db/queries/Era.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,39 @@
import { EraModel } from "../models";
import { Era, EraModel } from "../models";
import logger from "../../logger";

export const setLastNominatedEraIndex = async (
index: number,
): Promise<boolean> => {
const data = await EraModel.findOne({}).lean();
if (!data) {
const eraIndex = new EraModel({
lastNominatedEraIndex: index.toString(),
when: Date.now(),
});
await eraIndex.save();
return true;
}

await EraModel.findOneAndUpdate(
{ lastNominatedEraIndex: /.*/ },
{
$set: {
try {
const data = await EraModel.findOne({}).lean();
if (!data) {
const eraIndex = new EraModel({
lastNominatedEraIndex: index.toString(),
when: Date.now(),
nextNomination: Date.now() + 86400000,
});
await eraIndex.save();
return true;
}

await EraModel.findOneAndUpdate(
{ lastNominatedEraIndex: /.*/ },
{
$set: {
lastNominatedEraIndex: index.toString(),
when: Date.now(),
nextNomination: Date.now() + 86400000,
},
},
},
).exec();
return true;
).exec();
return true;
} catch (e) {
logger.error(
`Error setting last nominated era index: ${JSON.stringify(e)}`,
);
return false;
}
};

export const getLastNominatedEraIndex = async (): Promise<any> => {
return EraModel.findOne({ lastNominatedEraIndex: /[0-9]+/ })
.lean()
.exec();
export const getLastNominatedEraIndex = async (): Promise<Era | null> => {
return EraModel.findOne({ lastNominatedEraIndex: /[0-9]+/ }).lean<Era>();
};
2 changes: 1 addition & 1 deletion packages/common/src/db/queries/ValidatorScore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export const getValidatorScore = async (

export const getLatestValidatorScore = async (
address: string,
): Promise<ValidatorScore> => {
): Promise<ValidatorScore | null> => {
return ValidatorScoreModel.findOne({ address: address }, { _id: 0, __v: 0 })
.sort({ session: -1 })
.limit(1)
Expand Down
5 changes: 1 addition & 4 deletions packages/common/src/db/queries/Validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,7 @@ export const getLatestValidatorSet = async (): Promise<ValidatorSet | null> => {
};

export const getAllValidatorSets = async (): Promise<ValidatorSet[]> => {
return ValidatorSetModel.find({})
.sort({ era: -1 })
.lean<ValidatorSet[]>()
.exec();
return ValidatorSetModel.find({}).sort({ era: -1 }).lean<ValidatorSet[]>();
};

export const validatorSetExistsForEra = async (
Expand Down
24 changes: 13 additions & 11 deletions packages/common/src/nominator/NominatorChainInfo.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import Nominator from "./nominator";
import { queries } from "../index";
import { NOMINATOR_SHOULD_NOMINATE_ERAS_THRESHOLD } from "../constants";
import { NominatorState } from "../types";

// Query on-chain info for a nominator
export const getNominatorChainInfo = async (nominator: Nominator) => {
const stash = await nominator.stash();
const isBonded = await nominator.chaindata.isBonded(stash);
const [bonded, err] = await nominator.chaindata.getDenomBondedAmount(stash);
const currentBlock = await nominator.chaindata.getLatestBlock();
const currentBlock = (await nominator.chaindata.getLatestBlock()) || 0;

const currentEra = (await nominator.chaindata.getCurrentEra()) || 0;
const lastNominationEra =
Expand All @@ -20,16 +21,17 @@ export const getNominatorChainInfo = async (nominator: Nominator) => {
const kyc = await queries.isKYC(target);
let name = await queries.getIdentityName(target);
if (!name) {
name = (await nominator.chaindata.getFormattedIdentity(target))?.name;
name =
(await nominator.chaindata.getFormattedIdentity(target))?.name || "";
}

const scoreResult = await queries.getLatestValidatorScore(target);
const score = scoreResult && scoreResult.total ? scoreResult.total : 0;

return {
stash: target,
name: name,
kyc: kyc,
name: name || "",
kyc: kyc || false,
score: score,
};
}),
Expand All @@ -49,7 +51,7 @@ export const getNominatorChainInfo = async (nominator: Nominator) => {
if (!name) {
const formattedIdentity =
await nominator.chaindata.getFormattedIdentity(target);
name = formattedIdentity?.name;
name = formattedIdentity?.name || "";
}

const scoreResult = await queries.getLatestValidatorScore(target);
Expand All @@ -58,8 +60,8 @@ export const getNominatorChainInfo = async (nominator: Nominator) => {

return {
stash: target,
name: name,
kyc: kyc,
name: name || "",
kyc: kyc || false,
score: score,
};
}),
Expand Down Expand Up @@ -95,13 +97,13 @@ export const getNominatorChainInfo = async (nominator: Nominator) => {

let state;
if (shouldNominate) {
state = "Ready to Nominate";
state = NominatorState.ReadyToNominate;
} else if (namedProxyTargets.length > 0) {
state = "Awaiting Proxy Execution";
state = NominatorState.AwaitingProxyExecution;
} else if (lastNominationEra == 0) {
state = "Not Nominating";
state = NominatorState.NotNominating;
} else if (namedProxyTargets.length == 0 && lastNominationEra > 0) {
status = "Nominated";
state = NominatorState.Nominated;
}

const stale =
Expand Down
20 changes: 12 additions & 8 deletions packages/common/src/nominator/NominatorTx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import logger from "../logger";
import { blake2AsHex } from "@polkadot/util-crypto";
import { DelayedTx } from "../db";
import { ChainData, queries } from "../index";
import Nominator, { nominatorLabel } from "./nominator";
import { ApiPromise } from "@polkadot/api";
import MatrixBot from "../matrix";
import Nominator, { nominatorLabel } from "./nominator";
import { NominatorState } from "../types";

// Sends a Proxy Delay Nominate Tx for a given nominator
// TODO: unit tests
Expand All @@ -21,7 +22,7 @@ export const sendProxyDelayTx = async (
nominatorLabel,
);
await nominator.updateNominatorStatus({
state: "Nominating",
state: NominatorState.Nominating,
status: `[noninate] starting proxy delay tx`,
updated: Date.now(),
stale: false,
Expand Down Expand Up @@ -57,7 +58,7 @@ export const sendProxyDelayTx = async (
};
await queries.addDelayedTx(delayedTx);
await nominator.updateNominatorStatus({
state: "Nominating",
state: NominatorState.Nominating,
status: `[noninate] tx: ${JSON.stringify(delayedTx)}`,
updated: Date.now(),
stale: false,
Expand All @@ -67,7 +68,7 @@ export const sendProxyDelayTx = async (

const didSend = await nominator.signAndSendTx(tx);
await nominator.updateNominatorStatus({
state: "Awaiting Proxy Execution",
state: NominatorState.AwaitingProxyExecution,
status: `Announced Proxy Tx: ${didSend}`,
nextTargets: targets,
updated: Date.now(),
Expand Down Expand Up @@ -147,17 +148,20 @@ export const sendProxyTx = async (
targets.map(async (val) => {
const name = await queries.getIdentityName(val);
const kyc = await queries.isKYC(val);
const scoreResult = await queries.getLatestValidatorScore(val);
const score = scoreResult && scoreResult.total ? scoreResult.total : 0;
return {
address: val,
name: name,
kyc: kyc,
name: name || "",
kyc: kyc || false,
score: score,
};
}),
);
const currentEra = await chaindata.getCurrentEra();
const currentEra = (await chaindata.getCurrentEra()) || 0;

await nominator.updateNominatorStatus({
state: "Awaiting Proxy Execution",
state: NominatorState.AwaitingProxyExecution,
status: "Submitted Proxy Tx",
currentTargets: namedTargets,
updated: Date.now(),
Expand Down
4 changes: 4 additions & 0 deletions packages/common/src/nominator/__mocks__/nominator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,10 @@ class NominatorMock {
async sendStakingTx(tx: any, targets: string[]): Promise<boolean> {
return true;
}

async updateNominatorStatus(): Promise<boolean> {
return true;
}
}

export default NominatorMock;
Loading

0 comments on commit 352f574

Please sign in to comment.