Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement script repeating self nomination #71

Merged
merged 2 commits into from
Jun 20, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions auto-self-nominate/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[**.{ts,tsx,json,js,jsx}]
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 4
8 changes: 8 additions & 0 deletions auto-self-nominate/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# IDEs
.idea
.vscode

lib
*.log
node_modules/
build/
4 changes: 4 additions & 0 deletions auto-self-nominate/.prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"printWidth": 100,
"trailingComma": "all"
}
172 changes: 172 additions & 0 deletions auto-self-nominate/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import { U64 } from "codechain-primitives/lib";
import { SDK } from "codechain-sdk";
import { PlatformAddress } from "codechain-sdk/lib/core/classes";
import { Custom } from "codechain-sdk/lib/core/transaction/Custom";

const RLP = require("rlp");

const ACTION_TAG_SELF_NOMINATE = 4;
const STAKE_ACTION_HANDLER_ID = 2;

interface CandidatesInfo {
[key: string]: [number, number];
}

function getConfig(field: string, defaultVal?: string): string {
const c = process.env[field];
if (c == null) {
if (defaultVal == null) {
throw new Error(`${field} is not specified`);
}
return defaultVal;
}
return c;
}

const networkId = getConfig("NETWORK_ID");
const rpcUrl = getConfig("RPC_URL");
const needNominationUnderTermLeft = parseInt(getConfig("NEED_NOMINATION_UNDER_TERM_LEFT", "2"), 10);

const sdk = (() => {
console.log(`sdk ${networkId} ${rpcUrl}`);
return new SDK({
server: networkId,
networkId: rpcUrl,
});
})();

function decodePlatformAddressFromPubkey(buffer: Buffer): PlatformAddress {
const pubkey = buffer.toString("hex");
return PlatformAddress.fromPublic(pubkey, {
networkId: sdk.networkId,
});
}

function decodeNumber(buffer: Buffer): number {
return parseInt(buffer.toString("hex"), 16);
}

async function getCurrentTermId(bestBlockNumber: number): Promise<number | null> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not a comment about this commit, but please make a commit that adds this to SDK.

return new Promise((resolve, reject) => {
sdk.rpc
.sendRpcRequest("chain_getTermMetadata", [bestBlockNumber])
.then(result => {
if (result === null) {
resolve(null);
}
const [prevTermLastBlockNumber, currentTermId] = result;
if (
typeof prevTermLastBlockNumber === "number" &&
typeof currentTermId === "number"
) {
resolve(currentTermId);
}
reject(
Error(
`Expected getTermMetadata to return [number, number] | null but it returned ${result}`,
),
);
})
.catch(reject);
});
}

async function sendSelfNominateTransaction(
accountInfo: { account: string; passphrase: string },
params: { deposit: U64; metadata: string },
) {
const tx = createSelfNomination(params);
const { account, passphrase } = accountInfo;
await sdk.rpc.account.sendTransaction({
tx,
account,
passphrase,
});
}

function createSelfNomination(params: { deposit: U64; metadata: string }): Custom {
const { deposit, metadata } = params;
const handlerId = new U64(STAKE_ACTION_HANDLER_ID);
const actionTag = ACTION_TAG_SELF_NOMINATE;
const bytes = RLP.encode([actionTag, deposit, metadata]);
return new Custom(
{
handlerId,
bytes,
},
networkId,
);
}

async function getCandidatesInfo(bestBlockNumber: number): Promise<CandidatesInfo> {
const retval: CandidatesInfo = {};
const data = (await sdk.rpc.engine.getCustomActionData(2, ["Candidates"], bestBlockNumber))!;
const list: Buffer[][] = RLP.decode(Buffer.from(data, "hex"));
list.forEach(
([encodedPubkey, encodedDeposit, encodedNominationEnd]) =>
(retval[decodePlatformAddressFromPubkey(encodedPubkey).value] = [
decodeNumber(encodedNominationEnd),
decodeNumber(encodedDeposit),
]),
);
return retval;
}

async function needsNomination(
info: CandidatesInfo,
bestBlockNumber: number,
address: string,
): Promise<boolean> {
if (!info.hasOwnProperty(address)) {
throw new Error(`SelfNominate first with specific deposit vakue before repeating`);
}
const [, nominationEndAt] = info[address];
const currentTermId = (await getCurrentTermId(bestBlockNumber))!;
return nominationEndAt - currentTermId < needNominationUnderTermLeft;
}

function supplementaryDeposit(
info: CandidatesInfo,
address: string,
targetDeposit: number,
): number {
if (!info.hasOwnProperty(address)) {
throw new Error(`SelfNominate first with specific deposit vakue before repeating`);
}
const [deposit] = info[address];
if (deposit < targetDeposit) {
return targetDeposit - deposit;
} else {
return 0;
}
}

async function main() {
const accountAddress = getConfig("ACCOUNT_ADDRESS");
const passphrase = getConfig("PASSPHRASE");
const metadata = getConfig("METADATA");
const targetDeposit = parseInt(getConfig("TARGET_DEPOSIT"), 10);

setInterval(async () => {
const bestBlockNumber = await sdk.rpc.chain.getBestBlockNumber()!;
const info = await getCandidatesInfo(bestBlockNumber);
if (await needsNomination(info, bestBlockNumber, accountAddress)) {
const supplement = await supplementaryDeposit(info, accountAddress, targetDeposit);
await sendSelfNominateTransaction(
{
account: accountAddress,
passphrase,
},
{
deposit: new U64(supplement),
metadata,
},
);
}
}, 600_000); // 10 minutes interval
}

main().catch(error => {
console.log({ error });
throw error;
});
21 changes: 21 additions & 0 deletions auto-self-nominate/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "auto-self-nominator",
"version": "1.0.0",
"main": "src/index.ts",
"license": "ISC",
"scripts": {
"build": "tsc -p .",
"lint": "tslint -p . && prettier '**/*.ts' -l",
"fmt": "tslint -p . --fix && prettier '**/*ts' --write"
},
"dependencies": {
"codechain-sdk": "^1.2.0"
},
"devDependencies": {
"prettier": "^1.18.2",
"ts-node": "^8.2.0",
"tslint": "^5.17.0",
"tslint-config-prettier": "^1.18.0",
"typescript": "^3.5.2"
}
}
14 changes: 14 additions & 0 deletions auto-self-nominate/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "es2018",
"types": ["node"],
"module": "commonjs",
"declaration": true,
"outDir": "build",
"strict": true,
"noImplicitAny": true,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"include": ["**/*.ts"]
}
26 changes: 26 additions & 0 deletions auto-self-nominate/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"extends": ["tslint:recommended", "tslint-config-prettier"],
"rules": {
"strict-boolean-expressions": true,
"interface-name": false,
"no-console": false,
"object-literal-sort-keys": false,
"no-var-requires": false,
"array-type": false,
"variable-name": [
true,
"check-format",
"allow-leading-underscore",
"allow-pascal-case"
],
"max-classes-per-file": true,
"no-bitwise": false
},
"jsRules": {
"no-console": false,
"object-literal-sort-keys": false
},
"linterOptions": {
"exclude": ["node_modules/**/*.ts", "/build/*"]
}
}
Loading