-
Notifications
You must be signed in to change notification settings - Fork 8
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
sgkim126
merged 2 commits into
CodeChain-io:master
from
HoOngEe:feature/self-nomination-script
Jun 20, 2019
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
# IDEs | ||
.idea | ||
.vscode | ||
|
||
lib | ||
*.log | ||
node_modules/ | ||
build/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
{ | ||
"printWidth": 100, | ||
"trailingComma": "all" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> { | ||
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 { | ||
sgkim126 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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; | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/*"] | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.