This repository has been archived by the owner on Apr 21, 2023. It is now read-only.
forked from SpiderBTT/NanoWallet-1
-
Notifications
You must be signed in to change notification settings - Fork 13
[node-rewards-program] task: add service to communicate with API #679
Merged
AnthonyLaw
merged 12 commits into
node-rewards-program
from
feat/init-node-rewards-program-service
Jun 28, 2022
Merged
Changes from 11 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
153f5d8
[node-rewards-program] task: add service
OlegMakarenko 2abefc0
[node-rewards-program] fix: typo in error message
OlegMakarenko 53fe266
[node-rewards-program] fix: typo in class name
OlegMakarenko 040a98e
[node-rewards-program] task: add tests
OlegMakarenko 763769e
[node-rewards-program] fix: fetch mock, improve prepareEnrollTransact…
OlegMakarenko e08e6c5
[node-rewards-program] feat: add getNodePayouts() and getNodeInfo() m…
OlegMakarenko 1f1ba29
[node-rewards-program] fix: typo in jsdoc
OlegMakarenko cd63ec3
[node-rewards-program] fix: test comments
OlegMakarenko 6cef4de
[node-rewards-program] fix: remove whitespaces
OlegMakarenko 90991f3
[node-rewards-program] task: refactor fetch requests
OlegMakarenko 75927ff
[node-rewards-program] task: refactor the enrollment and error tests,…
OlegMakarenko d9baab0
[node-rewards-program] task: update codeword test, fix runPromiseErro…
OlegMakarenko 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
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,168 @@ | ||
import nem from 'nem-sdk'; | ||
|
||
const NODE_REWARDS_PROGRAM_API_BASE_URL = 'https://supernodesapi.nem.io'; | ||
|
||
/** Service to enroll in the Node Rewards Program and to get the status related information */ | ||
class NodeRewardsProgram { | ||
|
||
/** | ||
* Initialize dependencies and properties. | ||
* | ||
* @params {services} - Angular services to inject | ||
*/ | ||
constructor($localStorage, $filter, Wallet) { | ||
'ngInject'; | ||
|
||
// Service dependencies region // | ||
|
||
this._storage = $localStorage; | ||
this._$filter = $filter; | ||
this._Wallet = Wallet; | ||
|
||
// End dependencies region // | ||
|
||
// Service properties region // | ||
|
||
this.apiBaseUrl = NODE_REWARDS_PROGRAM_API_BASE_URL; | ||
this.common = nem.model.objects.get('common'); | ||
|
||
// End properties region // | ||
} | ||
|
||
// Service methods region // | ||
|
||
/** | ||
* Make get request. | ||
* | ||
* @param {string} url - URL of the resource to fetch. | ||
* @param {string} errorMessage - Description of the error that will be thrown in case of an unsuccessful request. | ||
* | ||
* @return {Promise<object>} - Response. | ||
*/ | ||
async _get(url, errorMessage) { | ||
const response = await fetch(url); | ||
|
||
if (!response.ok) { | ||
throw Error(errorMessage); | ||
} | ||
|
||
return response; | ||
} | ||
|
||
/** | ||
* Prepare the enroll transaction. | ||
* | ||
* @param {string} mainPublicKey - Delegated harvesting public key. | ||
* @param {string} host - IP or domain of the node. | ||
* @param {string} enrollmentAddress - Node Rewards Program enrollment address. | ||
* @param {string} [multisigAccountAddress] - Multisig account address. For multisig enrollment only. | ||
* | ||
* @return {Promise<object>} - Prepared enroll transaction. | ||
*/ | ||
async prepareEnrollTransaction(mainPublicKey, host, enrollmentAddress, multisigAccountAddress) { | ||
// Create a new transaction object | ||
const transferTransaction = nem.model.objects.get('transferTransaction'); | ||
|
||
// Set enrollment address as recipient | ||
transferTransaction.recipient = enrollmentAddress.toUpperCase().replace(/-/g, ''); | ||
|
||
// Set multisig, if selected | ||
if (multisigAccountAddress) { | ||
transferTransaction.isMultisig = true; | ||
transferTransaction.multisigAccount = multisigAccountAddress.toUpperCase().replace(/-/g, ''); | ||
} | ||
|
||
// Set the message | ||
const hash = await this.getCodewordHash(mainPublicKey); | ||
transferTransaction.message = `enroll ${host} ${hash}`; | ||
|
||
// Set no mosaics | ||
transferTransaction.mosaics = null; | ||
|
||
return nem.model.transactions.prepare('transferTransaction')(this.common, transferTransaction, this._Wallet.network); | ||
} | ||
|
||
/** | ||
* Checks if an address is the current enrollment address. | ||
* | ||
* @param {string} address - Address to check. | ||
* | ||
* @return {Promise<boolean>} - If the address to check matches the current enrollment address. | ||
*/ | ||
async checkEnrollmentAddress(address) { | ||
const response = await this._get(`${this.apiBaseUrl}/enrollment/check/address/${address}`, 'failed_to_validate_enroll_address'); | ||
const status = await response.text(); | ||
|
||
return status === 'true'; | ||
} | ||
|
||
/** | ||
* Checks if a signer public key is enrolled in the current period. | ||
* | ||
* @param {string} publicKey - Delegated harvesting public key to check. | ||
* | ||
* @return {Promise<boolean>} - If the public key is enrolled in the current period. | ||
*/ | ||
async checkEnrollmentStatus(publicKey) { | ||
const successEnrollmentResponse = await this._get(`${this.apiBaseUrl}/enrollment/successes/${publicKey}?count=1`, 'failed_to_get_success_enrollments'); | ||
const successEnrollments = await successEnrollmentResponse.json(); | ||
|
||
if (successEnrollments.length === 0) { | ||
return false; | ||
} | ||
|
||
const latestSuccessEnrollment = successEnrollments[0]; | ||
const enrollAddress = latestSuccessEnrollment.recipientAddress; | ||
|
||
return this.checkEnrollmentAddress(enrollAddress); | ||
AnthonyLaw marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
/** | ||
* Gets codeword dependent hash for the current period given a public key. | ||
* | ||
* @param {string} publicKey - Signer public key to use in hash calculation. | ||
* | ||
* @return {Promise<string>} - The codeword hex string, which should be used in enrollment messages. | ||
*/ | ||
async getCodewordHash(publicKey) { | ||
const response = await this._get(`${this.apiBaseUrl}/codeword/${publicKey}`, 'failed_to_get_codeword_hash'); | ||
|
||
return response.text(); | ||
} | ||
|
||
/** | ||
* Gets payout information for a single node. | ||
* | ||
* @param {string} nodeId - Id of the node to search. | ||
* @param {number} pageNumber - Page number to return. | ||
* | ||
* @return {Promise<Array<object>>} - List of payouts. | ||
*/ | ||
async getNodePayouts(nodeId, pageNumber) { | ||
const count = 15; | ||
const offset = count * pageNumber; | ||
const response = await this._get(`${this.apiBaseUrl}/node/${nodeId}/payouts?count=${count}&offset=${offset}`, 'failed_to_get_payouts_page'); | ||
|
||
return response.json(); | ||
} | ||
|
||
/** | ||
* Gets detailed information about a single node. | ||
* | ||
* @param {string} nodeId - Id of the node to search. Can be one of: | ||
* - Database node id | ||
* - Hex encoded node main public key | ||
* - Node IP (or host) | ||
* | ||
* @return {Promise<object>} - Node info. | ||
*/ | ||
async getNodeInfo(nodeId) { | ||
const response = await this._get(`${this.apiBaseUrl}/node/${nodeId}`, 'failed_to_get_node_info'); | ||
|
||
return response.json(); | ||
} | ||
|
||
// End methods region // | ||
} | ||
|
||
export default NodeRewardsProgram; |
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,17 @@ | ||
/** | ||
* Tests promise to throw given error. | ||
* | ||
* @param {Promise} promiseToTest - Promise to be tested. | ||
* @param {any} expectedError - Error to be thrown. | ||
*/ | ||
export const runPromiseErrorTest = async (promiseToTest, expectedError) => { | ||
// Act: | ||
try { | ||
await promiseToTest; | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. you should add assert here too to make sure test fails if exception isn't thrown There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Updated. Moved assert from the |
||
catch (error) { | ||
// Assert: | ||
expect(error instanceof expectedError.constructor).toBe(true); | ||
expect(error.message).toBe(expectedError.message); | ||
} | ||
}; |
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.
why square brackets?
[multisigAccountAddress]
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.
This is an optional parameter, according to the JSDoc syntax.