From 4ff8ee64e0def90e7d2f961e24af9afd2593a674 Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Tue, 12 Sep 2023 14:38:40 +0900 Subject: [PATCH 01/30] Use a better theme for typedoc --- package.json | 3 ++- yarn.lock | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 747fdee..e9e83e8 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "test_ain_raw": "jest ain_raw.test.ts", "test_he": "jest he.test.ts", "test_em": "jest event_manager.test.ts", - "docs": "yarn build && typedoc --out docs" + "docs": "yarn build && typedoc --plugin @mxssfd/typedoc-theme --theme my-theme --out docs" }, "engines": { "node": ">=16" @@ -38,6 +38,7 @@ "lib/**/*" ], "devDependencies": { + "@mxssfd/typedoc-theme": "^1.1.3", "@types/jest": "^27.0.2", "@types/ws": "^8.5.3", "jest": "^27.3.1", diff --git a/yarn.lock b/yarn.lock index 9b4f8d3..8d7d0ce 100644 --- a/yarn.lock +++ b/yarn.lock @@ -727,6 +727,11 @@ "@jridgewell/resolve-uri" "^3.0.3" "@jridgewell/sourcemap-codec" "^1.4.10" +"@mxssfd/typedoc-theme@^1.1.3": + version "1.1.3" + resolved "https://registry.yarnpkg.com/@mxssfd/typedoc-theme/-/typedoc-theme-1.1.3.tgz#ca1f20aeee08fad19cc6b71111ac09fc330c219c" + integrity sha512-/yP5rqhvibMpzXpmw0YLLRCpoj3uVWWlwyJseZXzGxTfiA6/fd1uubUqNoQAi2U19atMDonq8mQc+hlVctrX4g== + "@sinonjs/commons@^1.7.0": version "1.8.3" resolved "https://registry.yarnpkg.com/@sinonjs/commons/-/commons-1.8.3.tgz#3802ddd21a50a949b6721ddd72da36e67e7f1b2d" From cc78ef4b3ff930894d950de8d1872f32aae0e4a3 Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Tue, 12 Sep 2023 14:39:29 +0900 Subject: [PATCH 02/30] Update README.md for typedoc gh pages --- README.md | 261 +----------------------------------------------------- 1 file changed, 3 insertions(+), 258 deletions(-) diff --git a/README.md b/README.md index c86b45f..20ab923 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # ain-js -AI Network Client Library for Node.js +AI Network Blockchain SDK for javascript (or typescript). ## Installation @@ -52,264 +52,9 @@ yarn run test_snapshot # update test snapshot files ``` -## API - -### Ain -`constructor(provideUrl: string, chainId?: number)` -- Constructs Ain. -- Usage : `const ain = new Ain('http://node.ainetwork.ai:8080/');` - -`setProvider(providerUrl: string, chainId?: number)` -- Sets a new provider. - -`getBlock(blockHashOrBlockNumber: string | number, returnTransactionObjects?: boolean): Promise` -- A promise returns a block with the given hash or block number. - -`getProposer(blockHashOrBlockNumber: string | number): Promise` -- A promise returns the address of the forger of given block. - -`getValidators(blockHashOrBlockNumber: string | number): Promise` -- A promise returns the list of validators for a given block. - -`getTransaction(transactionHash: string): Promise` -- Returns the transaction with the given transaction hash. - -`getStateUsage(appName: string): Promise` -- Returns the state usage information with the given app name. - -`async validateAppName(appName: string): Promise` -- Validates an app name. - -`async sendTransaction(transactionObject: TransactionInput): Promise` -- Signs and sends a transaction to the network. - -`async sendSignedTransaction(signature: string, txBody: TransactionBody): Promise` -- Sends a signed transaction to the network. - -`async sendTransactionBatch(transactionObjects: TransactionInput[]): Promise` -- Sends signed transactions to the network. - -`depositConsensusStake(transactionObject: ValueOnlyTransactionInput): Promise` -- Sends a transaction that deposits AIN for consensus staking. - -`withdrawConsensusStake(transactionObject: ValueOnlyTransactionInput): Promise` -- Sends a transaction that withdraws AIN for consensus staking. - -`getConsensusStakeAmount(account?: string): Promise` -- Gets the amount of AIN currently staked for participating in consensus protocol. - -`getNonce(args: {address?: string, from?: string}): Promise` -- Returns the current transaction count of account, which is the nonce of the account. - -`async buildTransactionBody(transactionInput: TransactionInput): Promise` -- Builds a transaction body from transaction input. - -`static get utils()` -- Getter for ain-util library. - -`static instanceofTransactionBody(object: any): object is TransactionBody` -- Checks whether a given object is an instance of TransactionBody interface. - -### Ain.Provider - -`sync send(rpcMethod: string, params?: any): Promise` -- Creates the JSON-RPC payload and sends it to the node. - -`setDefaultTimeoutMs(time: number)` -- Sets the httpClient's default timeout time. - -### Ain.Database - -`ref(path?: string): Reference` -- Returns a reference instance of the given path. - -#### Ain.Database.Reference - -`setIsGlobal(isGlobal: boolean)` -- Sets the global path flag. - -`get numberOfListeners(): number` -- A getter for number of listeners. - -`push(value?: any): Promise | Reference` -- If value is given, it sets the value at a new child of this.path. Otherwise, it creates a key for a new child but doesn't set any values. - -`getValue(path?: string): Promise` -- Returns the value at the path. - -`getRule(path?: string): Promise` -- Returns the rule at the path. - -`getOwner(path?: string): Promise` -- Returns the owner config at the path. - -`getFunction(path?: string): Promise` -- Returns the function config at the path. - -`get(gets: GetOperation[]): Promise` -- Returns the value / write rule / owner rule / function hash at multiple paths. - -`deleteValue(transactionInput?: ValueOnlyTransactionInput): Promise` -- Deletes a value. - -`setFunction(transactionInput: ValueOnlyTransactionInput): Promise` -- Sets a function config. - -`setOwner(transactionInput: ValueOnlyTransactionInput): Promise` -- Sets the owner rule. - -`setRule(transactionInput: ValueOnlyTransactionInput): Promise` -- Sets the write rule. - -`setValue(transactionInput: ValueOnlyTransactionInput): Promise` -- Sets a value. - -`incrementValue(transactionInput: ValueOnlyTransactionInput): Promise` -- Increments the value. - -`decrementValue(transactionInput: ValueOnlyTransactionInput): Promise` -- Decrements the value. - -`set(transactionInput: SetMultiTransactionInput): Promise` -- Processes multiple set operations. - -`evalRule(params: EvalRuleInput): Promise` -- Returns the rule evaluation result. True if the params satisfy the write rule false if not. - -`evalOwner(params: EvalOwnerInput): Promise` -- Returns the owner evaluation result. - -`matchFunction(params?: MatchInput): Promise` -- Returns the function configs that are related to the input ref. - -`matchRule(params?: MatchInput): Promise` -- Returns the rule configs that are related to the input ref. - -`matchOwner(params?: MatchInput): Promise` -- Returns the owner configs that are related to the input ref. - -`static buildGetRequest(type: GetOperationType, ref: string)` -- Builds a get request. - -`static extendPath(basePath?: string, extension?: string): string` -- Returns a path that is the basePath extended with extension. - -`static extendSetTransactionInput(input: ValueOnlyTransactionInput, ref: string, type: SetOperationType, isGlobal: boolean): TransactionInput` -- Decorates a transaction input with an appropriate type, ref and value. - -`static extendSetMultiTransactionInput(input: SetMultiTransactionInput, ref: string): TransactionInput` -- Decorates a transaction input with an appropriate type and op_list. - -`static sanitizeRef(ref?: string): string` -- Returns a sanitized ref. If should have a slash at the beginning and no slash at the end. - -### Ain.net - -`isListening(): Promise` -- Returns whether the node is listening for network connections. - -`getNetworkId(): Promise` -- Returns the id of the network the node is connected to. - -`async checkProtocolVersion(): Promise` -- Checks the protocol version - -`getProtocolVersion(): Promise` -- Returns the protocol version of the node. - -`getPeerCount(): Promise` -- Returns the number of peers the provider node is connected to. - -`isSyncing(): Promise` -- Returns whether the node is syncing with the network or not. - -### Ain.wallet -`get length()` -- Getter for the number of accounts in the wallet. - -`setChainId(chainId: number)` -- Sets the chain ID. - -`getPublicKey(address: string): string` -- Returns the full public key of the given address. - -`create(numberOfAccounts: number): Array` -- Creates {numberOfAccounts} new accounts and add them to the wallet. - -`isAdded(address: string): boolean` -- Returns whether the address has already been added to the wallet. - -`add(privateKey: string): string` -- Adds a new account from the given private key. - -`addAndSetDefaultAccount(privateKey: string): string` -- Adds a new account from the given private key and sets the new account as the default account. - -`addFromHDWallet(seedPhrase: string, index: number = 0): string` -- Adds an account from a seed phrase. Only the account at the given index (default = 0) will be added. - -`addFromV3Keystore(v3Keystore: V3Keystore | string, password: string): string` -- Adds an account from a V3 Keystore. - -`remove(address: string)` -- Removes an account - -`setDefaultAccount(address: string)` -- Sets the default account as {address}. The account should be already added in the wallet. - -`removeDefaultAccount()` -- Removes a default account (sets it to null). - -`clear()` -- Clears the wallet (remove all account information). - -`getImpliedAddress(inputAddress?: string)` -- Returns the "implied" address. If address is not given, it returns the defaultAccount. It throws an error if an address is not given and defaultAccount is not set, or the specified address is not added to the wallet. - -`getBalance(address?: string): Promise` -- Returns the AIN balance of the address. - -`transfer(input: {to: string, value: number, from?: string, nonce?: number}): Promise` -- Sends a transfer transaction to the network. - -`sign(data: string, address?: string): string` -- Signs a string data with the private key of the given address. It will use the defaultAccount if an address is not provided. - -`signTransaction(tx: TransactionBody, address?: string): string` -- Signs a transaction data with the private key of the given address. It will use the defaultAccount if an address is not provided. - -`getHashStrFromSig(signature: string): string` -- Gets the hash from the signature. - -`recover(signature: string): string` -- Recovers an address of the account that was used to create the signature. - -`verifySignature(data: any, signature: string, address: string): boolean` -- Verifies if the signature is valid and was signed by the address. - -`toV3Keystore(password: string, options: V3KeystoreOptions = {}): V3Keystore[]` -- Save the accounts in the wallet as V3 Keystores, locking them with the password. - -`accountToV3Keystore(address: string, password: string, options: V3KeystoreOptions = {}): V3Keystore` -- Converts an account into a V3 Keystore and encrypts it with a password. - -`static fromPrivateKey(privateKey: Buffer): Account` -- Imports an account from a private key. - -### Ain.eh -`connect(connectionOption?: EventChannelConnectionOption, disconnectCallback?: DisconnectCallback)` -- Connect to event handler node. Must be called before subscribing. - -`disconnect()` -- Disconnect from the event handler node and unsubscribe all subscriptions. - -`subscribe(eventTypeStr: string, config: EventConfigType, -eventCallback?: BlockchainEventCallback, errorCallback?: (error: any) => void): string` -- Subscribe to specific blockchain events in the blockchain. - -`unsubscribe(filterId: string, callback: ErrorFirstCallback)` -- Unsubscribe from a previously subscribed event. +## API Documentation +API documentation is available at https://ainblockchain.github.io/ain-js/. ## LICENSE From 6a864ba3ad70bb418f42f917aedca5a5a7632e31 Mon Sep 17 00:00:00 2001 From: hyeonwoong Date: Wed, 13 Sep 2023 15:23:52 +0900 Subject: [PATCH 03/30] feat: add sendTransaction to signer interface & fix: move some functions --- src/ain.ts | 88 ++----------------- src/signer/ain-wallet-signer.ts | 19 +++++ src/signer/default-signer.ts | 147 ++++++++++++++++++++++++++++++++ src/signer/signer.ts | 86 ++++++++----------- 4 files changed, 207 insertions(+), 133 deletions(-) create mode 100644 src/signer/default-signer.ts diff --git a/src/ain.ts b/src/ain.ts index 5f24cdb..81073bd 100755 --- a/src/ain.ts +++ b/src/ain.ts @@ -1,8 +1,6 @@ -import * as EventEmitter from 'eventemitter3' import * as AinUtil from "@ainblockchain/ain-util"; import { AxiosRequestConfig } from 'axios'; -import request from './request'; import { AinOptions, Block, TransactionInfo, TransactionBody, TransactionResult, SetOperationType, SetOperation, TransactionInput, ValueOnlyTransactionInput, StateUsageInfo, AppNameValidationInfo, @@ -14,7 +12,8 @@ import Wallet from './wallet'; import Network from './net'; import EventManager from './event-manager'; import HomomorphicEncryption from './he'; -import { DefaultSigner, Signer } from "./signer/signer"; +import { Signer } from "./signer/signer"; +import { DefaultSigner } from './signer/default-signer'; export default class Ain { public axiosConfig: AxiosRequestConfig | undefined; @@ -42,7 +41,7 @@ export default class Ain { this.db = new Database(this, this.provider); this.he = new HomomorphicEncryption(); this.em = new EventManager(this); - this.signer = new DefaultSigner(this.wallet); + this.signer = new DefaultSigner(this.wallet, this.provider); } /** @@ -150,9 +149,7 @@ export default class Ain { * @return {Promise} */ async sendTransaction(transactionObject: TransactionInput, isDryrun: boolean = false): Promise { - const txBody = await this.buildTransactionBody(transactionObject); - const signature = await this.signer.signMessage(txBody, transactionObject.address); - return await this.sendSignedTransaction(signature, txBody, isDryrun); + return this.signer.sendTransaction(transactionObject, isDryrun); } /** @@ -163,12 +160,7 @@ export default class Ain { * @return {Promise} */ async sendSignedTransaction(signature: string, txBody: TransactionBody, isDryrun: boolean = false): Promise { - const method = isDryrun ? 'ain_sendSignedTransactionDryrun' : 'ain_sendSignedTransaction'; - let result = await this.provider.send(method, { signature, tx_body: txBody }); - if (!result || typeof result !== 'object') { - result = { result }; - } - return result; + return this.signer.sendSignedTransaction(signature, txBody, isDryrun); } /** @@ -176,35 +168,7 @@ export default class Ain { * @param {TransactionInput[]} transactionObjects */ async sendTransactionBatch(transactionObjects: TransactionInput[]): Promise { - let promises: Promise[] = []; - for (let tx of transactionObjects) { - promises.push(this.buildTransactionBody(tx).then(async (txBody) => { - if (tx.nonce === undefined) { - // Batch transactions' nonces should be specified. - // If they're not, they default to un-nonced (nonce = -1). - txBody.nonce = -1; - } - const signature = await this.signer.signMessage(txBody, tx.address); - return { signature, tx_body: txBody }; - })); - } - return Promise.all(promises).then(async (tx_list) => { - const resultList = await this.provider.send('ain_sendSignedTransactionBatch', { tx_list }); - if (!Array.isArray(resultList)) { - return resultList; - } - const len = resultList.length; - if (len !== tx_list.length) { - return resultList; - } else { - for (let i = 0; i < len; i++) { - if (!resultList[i] || typeof resultList[i] !== 'object') { - resultList[i] = { result: resultList[i] }; - } - } - return resultList; - } - }) + return this.signer.sendTransactionBatch(transactionObjects); } /** @@ -236,46 +200,6 @@ export default class Ain { return this.db.ref(`/deposit_accounts/consensus/${address}`).getValue(); } - /** - * Returns the current transaction count of account, which is the nonce of the account. - * @param {object} args - May contain a string 'address' and a string 'from' values. - * The 'address' indicates the address of the account to get the - * nonce of, and the 'from' indicates where to get the nonce from. - * It could be either the pending transaction pool ("pending") or - * the committed blocks ("committed"). The default value is "committed". - * @return {Promise} - */ - getNonce(args: {address?: string, from?: string}): Promise { - if (!args) { args = {}; } - const address = args.address ? Ain.utils.toChecksumAddress(args.address) - : this.signer.getAddress(args.address); - if (args.from !== undefined && args.from !== 'pending' && args.from !== 'committed') { - throw Error("'from' should be either 'pending' or 'committed'"); - } - return this.provider.send('ain_getNonce', { address, from: args.from }) - } - - /** - * Builds a transaction body from transaction input. - * @param {TransactionInput} transactionInput - * @return {Promise} - */ - async buildTransactionBody(transactionInput: TransactionInput): Promise { - const address = this.signer.getAddress(transactionInput.address); - let tx = { - operation: transactionInput.operation, - parent_tx_hash: transactionInput.parent_tx_hash - } - let nonce = transactionInput.nonce; - if (nonce === undefined) { - nonce = await this.getNonce({address, from: "pending"}); - } - const timestamp = transactionInput.timestamp ? transactionInput.timestamp : Date.now(); - const gasPrice = transactionInput.gas_price || 0; - const billing = transactionInput.billing; - return Object.assign(tx, { nonce, timestamp, gas_price: gasPrice, billing }); - } - /** * Getter for ain-util library */ diff --git a/src/signer/ain-wallet-signer.ts b/src/signer/ain-wallet-signer.ts index 4b9401d..fab29c0 100644 --- a/src/signer/ain-wallet-signer.ts +++ b/src/signer/ain-wallet-signer.ts @@ -1,3 +1,4 @@ +import { TransactionBody, TransactionInput } from "../types"; import { Signer } from "./signer"; /** @@ -36,4 +37,22 @@ export class AinWalletSigner implements Signer { signMessage(message: any, address?: string): Promise | string { return this.ainetwork.signMessage(message, address); } + + /** + * Signs and sends a transaction to the network + * @param {TransactionInput} transactionObject + * @param {boolean} isDryrun - dryrun option. + * @return {Promise} + */ + sendTransaction(transactionObject: TransactionInput) { + return this.ainetwork.sendTransaction(transactionObject); + } + + sendTransactionBatch(transactionObjects: TransactionInput[]): Promise { + throw new Error("Method not implemented."); + } + + sendSignedTransaction(signature: string, txBody: TransactionBody, isDryrun?: boolean | undefined): Promise { + throw new Error("Method not implemented."); + } } \ No newline at end of file diff --git a/src/signer/default-signer.ts b/src/signer/default-signer.ts new file mode 100644 index 0000000..9f06e0d --- /dev/null +++ b/src/signer/default-signer.ts @@ -0,0 +1,147 @@ +import { TransactionBody } from "@ainblockchain/ain-util"; +import Provider from "../provider"; +import Wallet from "../wallet"; +import { Signer } from "./signer"; +import { TransactionInput } from "../types"; +import Ain from "../ain"; + +/** + * The default class of Signer interface implemented using Wallet class. + * When Ain class is initialized, DefaultSigner is set as its signer. + */ +export class DefaultSigner implements Signer { + readonly wallet: Wallet; + readonly provider: Provider; + + /** + * Initializes the class. + * @param {Wallet} wallet - The wallet to initialize with. + */ + constructor(wallet: Wallet, provider: Provider) { + this.wallet = wallet; + this.provider = provider; + } + + /** + * Returns the checksum address to sign messages with. + * If the address is not given, the default address of the wallet is used. + * @param {string} address - The address of the account to sign the message with. + */ + getAddress(address?: string): string { + return this.wallet.getImpliedAddress(address); + } + + /** + * Signs a message with the private key of the given address. + * If an address is not given, the default address of the wallet is used. + * @param {string} message - The message to sign. + * @param {string} address - The address of the account to sign the message with. + */ + signMessage(message: string, address?: string): Promise | string { + return this.wallet.sign(message, address); + } + + /** + * Signs and sends a transaction to the network + * @param {TransactionInput} transactionObject + * @param {boolean} isDryrun - dryrun option. + * @return {Promise} + */ + async sendTransaction(transactionObject: TransactionInput, isDryrun: boolean = false) { + const txBody = await this.buildTransactionBody(transactionObject); + const signature = await this.wallet.signTransaction(txBody, transactionObject.address); + return await this.sendSignedTransaction(signature, txBody, isDryrun); + } + + /** + * Sends signed transactions to the network. + * @param {TransactionInput[]} transactionObjects + */ + async sendTransactionBatch(transactionObjects: TransactionInput[]): Promise { + let promises: Promise[] = []; + for (let tx of transactionObjects) { + promises.push(this.buildTransactionBody(tx).then(async (txBody) => { + if (tx.nonce === undefined) { + // Batch transactions' nonces should be specified. + // If they're not, they default to un-nonced (nonce = -1). + txBody.nonce = -1; + } + const signature = await this.wallet.signTransaction(txBody, tx.address); + return { signature, tx_body: txBody }; + })); + } + return Promise.all(promises).then(async (tx_list) => { + const resultList = await this.provider.send('ain_sendSignedTransactionBatch', { tx_list }); + if (!Array.isArray(resultList)) { + return resultList; + } + const len = resultList.length; + if (len !== tx_list.length) { + return resultList; + } else { + for (let i = 0; i < len; i++) { + if (!resultList[i] || typeof resultList[i] !== 'object') { + resultList[i] = { result: resultList[i] }; + } + } + return resultList; + } + }) + } + + /** + * Sends a signed transaction to the network + * @param {string} signature + * @param {TransactionBody} txBody + * @param {boolean} isDryrun - dryrun option. + * @return {Promise} + */ + async sendSignedTransaction(signature: string, txBody: TransactionBody, isDryrun: boolean = false): Promise { + const method = isDryrun ? 'ain_sendSignedTransactionDryrun' : 'ain_sendSignedTransaction'; + let result = await this.provider.send(method, { signature, tx_body: txBody }); + if (!result || typeof result !== 'object') { + result = { result }; + } + return result; + } + + /** + * Builds a transaction body from transaction input. + * @param {TransactionInput} transactionInput + * @return {Promise} + */ + async buildTransactionBody(transactionInput: TransactionInput): Promise { + const address = this.getAddress(transactionInput.address); + let tx = { + operation: transactionInput.operation, + parent_tx_hash: transactionInput.parent_tx_hash + } + let nonce = transactionInput.nonce; + if (nonce === undefined) { + nonce = await this.getNonce({ address, from: "pending" }); + } + const timestamp = transactionInput.timestamp ? transactionInput.timestamp : Date.now(); + const gasPrice = transactionInput.gas_price || 0; + const billing = transactionInput.billing; + return Object.assign(tx, { nonce, timestamp, gas_price: gasPrice, billing }); + } + + /** + * Returns the current transaction count of account, which is the nonce of the account. + * @param {object} args - May contain a string 'address' and a string 'from' values. + * The 'address' indicates the address of the account to get the + * nonce of, and the 'from' indicates where to get the nonce from. + * It could be either the pending transaction pool ("pending") or + * the committed blocks ("committed"). The default value is "committed". + * @return {Promise} + */ + getNonce(args: { address?: string, from?: string }): Promise { + if (!args) { args = {}; } + const address = args.address ? Ain.utils.toChecksumAddress(args.address) + : this.getAddress(args.address); + if (args.from !== undefined && args.from !== 'pending' && args.from !== 'committed') { + throw Error("'from' should be either 'pending' or 'committed'"); + } + return this.provider.send('ain_getNonce', { address, from: args.from }) + } +} \ No newline at end of file diff --git a/src/signer/signer.ts b/src/signer/signer.ts index 57b5b19..cca7a18 100644 --- a/src/signer/signer.ts +++ b/src/signer/signer.ts @@ -1,60 +1,44 @@ -import Wallet from "../wallet"; +import { TransactionBody, TransactionInput } from "../types"; /** * An interface for signing messages and transactions. */ export interface Signer { - /** - * Returns the checksum address to sign messages with. - * If the address is not given, the default address of the signer is used. - * @param {string} address - The address of the account to sign the message with. - */ - getAddress(address?: string): string; + /** + * Returns the checksum address to sign messages with. + * If the address is not given, the default address of the signer is used. + * @param {string} address - The address of the account to sign the message with. + */ + getAddress(address?: string): string; - /** - * Signs a message with the private key of the given address. - * If an address is not given, the default address of the signer is used. - * @param {any} message - The message to sign. - * @param {string} address - The address of the account to sign the message with. - */ - signMessage(message: any, address?: string): Promise | string; -} + /** + * Signs a message with the private key of the given address. + * If an address is not given, the default address of the signer is used. + * @param {string} message - The message to sign. + * @param {string} address - The address of the account to sign the message with. + */ + signMessage(message: string, address?: string): Promise | string; -/** - * The default class of Signer interface implemented using Wallet class. - * When Ain class is initialized, DefaultSigner is set as its signer. - */ -export class DefaultSigner implements Signer { - readonly wallet: Wallet; + /** + * Signs and sends a transaction to the network + * @param {TransactionInput} transactionObject + * @param {boolean} isDryrun - dryrun option. + * @return {Promise} + */ + sendTransaction(transactionObject: TransactionInput, isDryrun?: boolean); - /** - * Initializes the class. - * @param {Wallet} wallet - The wallet to initialize with. - */ - constructor(wallet: Wallet) { - this.wallet = wallet; - } + /** + * Sends signed transactions to the network. + * @param {TransactionInput[]} transactionObjects + */ + sendTransactionBatch(transactionObjects: TransactionInput[]): Promise - /** - * Returns the checksum address to sign messages with. - * If the address is not given, the default address of the wallet is used. - * @param {string} address - The address of the account to sign the message with. - */ - getAddress(address?: string): string { - return this.wallet.getImpliedAddress(address); - } - - /** - * Signs a message with the private key of the given address. - * If an address is not given, the default address of the wallet is used. - * @param {any} message - The message to sign. - * @param {string} address - The address of the account to sign the message with. - */ - signMessage(message: any, address?: string): Promise | string { - if (typeof message === 'string') { - return this.wallet.sign(message, address); - } else { - return this.wallet.signTransaction(message, address); - } - } -} \ No newline at end of file + /** + * Sends a signed transaction to the network + * @param {string} signature + * @param {TransactionBody} txBody + * @param {boolean} isDryrun - dryrun option. + * @return {Promise} + */ + sendSignedTransaction(signature: string, txBody: TransactionBody, isDryrun?: boolean): Promise +} From 5c8999bd4527e393dba8dce7663dd492d5c13819 Mon Sep 17 00:00:00 2001 From: hyeonwoong Date: Thu, 14 Sep 2023 10:09:48 +0900 Subject: [PATCH 04/30] comment: add period mark --- src/signer/ain-wallet-signer.ts | 2 +- src/signer/default-signer.ts | 2 +- src/signer/signer.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/signer/ain-wallet-signer.ts b/src/signer/ain-wallet-signer.ts index fab29c0..b174286 100644 --- a/src/signer/ain-wallet-signer.ts +++ b/src/signer/ain-wallet-signer.ts @@ -39,7 +39,7 @@ export class AinWalletSigner implements Signer { } /** - * Signs and sends a transaction to the network + * Signs and sends a transaction to the network. * @param {TransactionInput} transactionObject * @param {boolean} isDryrun - dryrun option. * @return {Promise} diff --git a/src/signer/default-signer.ts b/src/signer/default-signer.ts index 9f06e0d..0bc527d 100644 --- a/src/signer/default-signer.ts +++ b/src/signer/default-signer.ts @@ -42,7 +42,7 @@ export class DefaultSigner implements Signer { } /** - * Signs and sends a transaction to the network + * Signs and sends a transaction to the network. * @param {TransactionInput} transactionObject * @param {boolean} isDryrun - dryrun option. * @return {Promise} diff --git a/src/signer/signer.ts b/src/signer/signer.ts index cca7a18..90c4173 100644 --- a/src/signer/signer.ts +++ b/src/signer/signer.ts @@ -20,7 +20,7 @@ export interface Signer { signMessage(message: string, address?: string): Promise | string; /** - * Signs and sends a transaction to the network + * Signs and sends a transaction to the network. * @param {TransactionInput} transactionObject * @param {boolean} isDryrun - dryrun option. * @return {Promise} From 39879de070cb1fdc01f93d0028b3f05341a8355c Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Fri, 15 Sep 2023 16:03:42 +0900 Subject: [PATCH 05/30] Improve the typedoc comments of the Ain class --- src/ain.ts | 101 +++++++++++++++++++++++++++++------------------------ 1 file changed, 55 insertions(+), 46 deletions(-) diff --git a/src/ain.ts b/src/ain.ts index 81073bd..d64a84e 100755 --- a/src/ain.ts +++ b/src/ain.ts @@ -16,19 +16,32 @@ import { Signer } from "./signer/signer"; import { DefaultSigner } from './signer/default-signer'; export default class Ain { + /** The axios request config object. */ public axiosConfig: AxiosRequestConfig | undefined; + /** The chain ID of the blockchain network. */ public chainId: number; + /** The network provider object. */ public provider: Provider; + /** The raw result mode option. */ public rawResultMode: boolean; + /** The database object. */ public db: Database; + /** The network object. */ public net: Network; + /** The wallet object. */ public wallet: Wallet; + /** The homorphic encryption object. */ public he: HomomorphicEncryption; + /** The event manager object. */ public em: EventManager; + /** The signer object. */ public signer: Signer; /** - * @param {string} providerUrl + * Creates a new Ain object. + * @param {string} providerUrl The endpoint URL of the network provider. + * @param {number} chainId The chain ID of the blockchain network. + * @param {AinOptions} ainOptions The options of the class. * @constructor */ constructor(providerUrl: string, chainId?: number, ainOptions?: AinOptions) { @@ -45,8 +58,10 @@ export default class Ain { } /** - * Sets a new provider - * @param {string} providerUrl + * Sets a new provider. + * @param {string} providerUrl The endpoint URL of the network provider. + * @param {number} chainId The chain ID of the blockchain network. + * @param {AxiosRequestConfig} axiosConfig The axios request config. */ setProvider(providerUrl: string, chainId?: number, axiosConfig?: AxiosRequestConfig | undefined) { if (axiosConfig) { @@ -60,18 +75,18 @@ export default class Ain { } /** - * Sets a new signer - * @param {Signer} signer + * Sets a new signer. + * @param {Signer} signer The signer to set. */ setSigner(signer: Signer) { this.signer = signer; } /** - * A promise returns a block with the given hash or block number. - * @param {string | number} blockHashOrBlockNumber - * @param {boolean} returnTransactionObjects - If true, returns the full transaction objects; - * otherwise, returns only the transaction hashes + * Fetches a block with a block hash or block number. + * @param {string | number} blockHashOrBlockNumber The block hash or block number. + * @param {boolean} returnTransactionObjects If it's true, returns a block with full transaction objects. + * Otherwise, returns a block with only transaction hashes. * @return {Promise} */ getBlock(blockHashOrBlockNumber: string | number, returnTransactionObjects?: boolean): Promise { @@ -84,8 +99,8 @@ export default class Ain { } /** - * A promise returns the address of the forger of given block - * @param {string | number} blockHashOrBlockNumber + * Fetches the forger's address of a block with a block hash or block number. + * @param {string | number} blockHashOrBlockNumber The block hash or block number. * @return {Promise} */ getProposer(blockHashOrBlockNumber: string | number): Promise { @@ -96,8 +111,8 @@ export default class Ain { } /** - * A promise returns the list of validators for a given block - * @param {string | number} blockHashOrBlockNumber + * Fetches the validator list of a block with a block hash or block number. + * @param {string | number} blockHashOrBlockNumber The block hash or block number. * @return {Promise} */ getValidators(blockHashOrBlockNumber: string | number): Promise { @@ -108,8 +123,8 @@ export default class Ain { } /** - * Returns the transaction with the given transaction hash. - * @param {string} transactionHash + * Fetches the information of a transaction with a transaction hash. + * @param {string} transactionHash The transaction hash. * @return {Promise} */ getTransaction(transactionHash: string): Promise { @@ -117,8 +132,8 @@ export default class Ain { } /** - * Returns the state usage information with the given app name. - * @param {string} appName + * Fetches the state usage information of a blockchain app. + * @param {string} appName The blockchain app name. * @return {Promise} */ getStateUsage(appName: string): Promise { @@ -126,16 +141,8 @@ export default class Ain { } /** - * Returns the result of the transaction with the given transaaction hash. - * @param {string} transactionHash - * @return {Promise} - */ - // TODO(liayoo): implement this function. - // getTransactionResult(transactionHash: string): Promise {} - - /** - * Validate the given app name. - * @param {string} appName + * Validates a blockchain app name. + * @param {string} appName The blockchain app name. * @return {Promise} */ validateAppName(appName: string): Promise { @@ -143,9 +150,9 @@ export default class Ain { } /** - * Signs and sends a transaction to the network - * @param {TransactionInput} transactionObject - * @param {boolean} isDryrun - dryrun option. + * Signs and sends a transaction to the network. + * @param {TransactionInput} transactionObject The transaction input object. + * @param {boolean} isDryrun The dryrun option. * @return {Promise} */ async sendTransaction(transactionObject: TransactionInput, isDryrun: boolean = false): Promise { @@ -153,10 +160,10 @@ export default class Ain { } /** - * Sends a signed transaction to the network - * @param {string} signature - * @param {TransactionBody} txBody - * @param {boolean} isDryrun - dryrun option. + * Sends a signed transaction to the network. + * @param {string} signature The signature of the transaction. + * @param {TransactionBody} txBody The transaction body. + * @param {boolean} isDryrun The dryrun option. * @return {Promise} */ async sendSignedTransaction(signature: string, txBody: TransactionBody, isDryrun: boolean = false): Promise { @@ -164,8 +171,9 @@ export default class Ain { } /** - * Sends signed transactions to the network. - * @param {TransactionInput[]} transactionObjects + * Sends signed multiple transactions in a batch to the network. + * @param {TransactionInput[]} transactionObjects The list of the transaction input objects. + * @return {Promise} */ async sendTransactionBatch(transactionObjects: TransactionInput[]): Promise { return this.signer.sendTransactionBatch(transactionObjects); @@ -173,7 +181,7 @@ export default class Ain { /** * Sends a transaction that deposits AIN for consensus staking. - * @param {ValueOnlyTransactionInput} transactionObject + * @param {ValueOnlyTransactionInput} transactionObject The transaction input object. * @return {Promise} */ depositConsensusStake(transactionObject: ValueOnlyTransactionInput): Promise { @@ -182,7 +190,7 @@ export default class Ain { /** * Sends a transaction that withdraws AIN for consensus staking. - * @param {ValueOnlyTransactionInput} transactionObject + * @param {ValueOnlyTransactionInput} transactionObject The transaction input object. * @return {Promise} */ withdrawConsensusStake(transactionObject: ValueOnlyTransactionInput): Promise { @@ -190,8 +198,9 @@ export default class Ain { } /** - * Gets the amount of AIN currently staked for participating in consensus protocol. - * @param {string} account - If not specified, will try to use the defaultAccount value. + * Fetches the amount of AIN currently staked for participating in consensus protocol. + * @param {string} account The account to fetch the value with. If not specified, + * the default account of the signer is used. * @return {Promise} */ getConsensusStakeAmount(account?: string): Promise { @@ -201,15 +210,15 @@ export default class Ain { } /** - * Getter for ain-util library + * Getter for ain-util library. */ static get utils() { return AinUtil; } /** - * Checks whether a given object is an instance of TransactionBody interface. - * @param {string} account + * Checks whether an object is an instance of the TransactionBody interface. + * @param {any} object The object to check. * @return {boolean} */ static instanceofTransactionBody(object: any): object is TransactionBody { @@ -220,9 +229,9 @@ export default class Ain { /** * A base function for all staking related database changes. It builds a * deposit/withdraw transaction and sends the transaction by calling sendTransaction(). - * @param {string} path - * @param {ValueOnlyTransactionInput} transactionObject - * @param {boolean} isDryrun - dryrun option. + * @param {string} path The path to set a value. + * @param {ValueOnlyTransactionInput} transactionObject The transaction input object. + * @param {boolean} isDryrun The dryrun option. * @return {Promise} */ private stakeFunction(path: string, transactionObject: ValueOnlyTransactionInput, isDryrun: boolean = false): Promise { From 065432a64b16e306291515aab8a35d9ae15c2c2b Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Fri, 15 Sep 2023 16:13:01 +0900 Subject: [PATCH 06/30] Add typedoc comments for BlockchainError class --- src/ain.ts | 3 +++ src/errors.ts | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/src/ain.ts b/src/ain.ts index d64a84e..a1fa1ba 100755 --- a/src/ain.ts +++ b/src/ain.ts @@ -15,6 +15,9 @@ import HomomorphicEncryption from './he'; import { Signer } from "./signer/signer"; import { DefaultSigner } from './signer/default-signer'; +/** + * The main class of the ain-js SDK library. + */ export default class Ain { /** The axios request config object. */ public axiosConfig: AxiosRequestConfig | undefined; diff --git a/src/errors.ts b/src/errors.ts index dfeab7e..ba0c98e 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -1,6 +1,15 @@ +/** + * A class for blockchain errors. + */ export class BlockchainError extends Error { + /** The error code. */ public code: number; + /** + * Creates a new BlockchainError object. + * @param {number} code The error code. + * @param {string} message The error message. + */ constructor(code: number, message: string) { super(message); // NOTE(platfowner): https://stackoverflow.com/questions/68899615/how-to-expect-a-custom-error-to-be-thrown-with-jest From 3f76665448212fe0206e63ace8ec4d68bd67b5ea Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Fri, 15 Sep 2023 16:26:58 +0900 Subject: [PATCH 07/30] Improve the typedoc comments of Network class --- src/net.ts | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/net.ts b/src/net.ts index d24e9a1..691529c 100755 --- a/src/net.ts +++ b/src/net.ts @@ -2,12 +2,16 @@ import * as semver from 'semver'; import Provider from './provider'; import { BLOCKCHAIN_PROTOCOL_VERSION } from './constants'; +/** + * A class for checking the blockchain node status. + */ export default class Network { public provider: Provider; public protoVer: string; /** - * @param {Provider} provider + * Creates a new Network object. + * @param {Provider} provider The network provider. * @constructor */ constructor (provider: Provider) { @@ -16,7 +20,7 @@ export default class Network { } /** - * Returns whether the node is listening for network connections. + * Checks whether the blockchain node is listening for network connections. * @return {Promise} */ isListening(): Promise { @@ -24,28 +28,28 @@ export default class Network { } /** - * Returns the id of the network the node is connected to. + * Fetches the ID of the network the blokchain node is connected to. */ getNetworkId(): Promise { return this.provider.send('net_getNetworkId'); } /** - * Checks the protocol version. + * Checks the protocol version compatibility with the blockchain node. */ async checkProtocolVersion(): Promise { return this.provider.send('ain_checkProtocolVersion'); } /** - * Returns the protocol version of the node. + * Fetches the protocol version of the blockchain node. */ getProtocolVersion(): Promise { return this.provider.send('ain_getProtocolVersion'); } /** - * Returns the number of peers the provider node is connected to. + * Fetches the number of the peers the blockchain node is connected to. * @return {Promise} */ getPeerCount(): Promise { @@ -53,7 +57,7 @@ export default class Network { } /** - * Returns whether the node is syncing with the network or not. + * Checks whether the blockchain node is syncing with the network or not. * @return {Promise} */ isSyncing(): Promise { @@ -61,7 +65,7 @@ export default class Network { } /** - * Returns the event handler network information. + * Fetches the event handler network information. */ getEventHandlerNetworkInfo(): Promise { return this.provider.send('net_getEventHandlerNetworkInfo'); From ec089f63c53b8c61a2936940bb68c15508461dc1 Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Fri, 15 Sep 2023 17:28:24 +0900 Subject: [PATCH 08/30] Add typedoc comments for PromiEvent class --- src/ain.ts | 1 - src/net.ts | 3 ++- src/promi-event.ts | 17 ++++++++++++++++- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/ain.ts b/src/ain.ts index a1fa1ba..925f79b 100755 --- a/src/ain.ts +++ b/src/ain.ts @@ -45,7 +45,6 @@ export default class Ain { * @param {string} providerUrl The endpoint URL of the network provider. * @param {number} chainId The chain ID of the blockchain network. * @param {AinOptions} ainOptions The options of the class. - * @constructor */ constructor(providerUrl: string, chainId?: number, ainOptions?: AinOptions) { this.axiosConfig = ainOptions?.axiosConfig; diff --git a/src/net.ts b/src/net.ts index 691529c..61c24c3 100755 --- a/src/net.ts +++ b/src/net.ts @@ -6,13 +6,14 @@ import { BLOCKCHAIN_PROTOCOL_VERSION } from './constants'; * A class for checking the blockchain node status. */ export default class Network { + /** The network provider. */ public provider: Provider; + /** The protocol version. */ public protoVer: string; /** * Creates a new Network object. * @param {Provider} provider The network provider. - * @constructor */ constructor (provider: Provider) { this.provider = provider; diff --git a/src/promi-event.ts b/src/promi-event.ts index 9cda7b8..53973f5 100644 --- a/src/promi-event.ts +++ b/src/promi-event.ts @@ -1,16 +1,24 @@ import * as EventEmitter from 'eventemitter3'; /** - * A combination of a promise and an event emitter. + * A class that combines the Promise interface and the EventEmitter class. * @implements {Promise} */ export class PromiEvent implements Promise { + /** The event emitter. */ public eventEmitter: EventEmitter; + /** The promise. */ public promise: Promise + /** The value for toString(). */ public [Symbol.toStringTag]; + /** The resolve function. */ private _resolve; + /** The reject function. */ private _reject; + /** + * Creates a new PromiEvent object. + */ constructor() { this.promise = new Promise((resolve, reject) => { this._resolve = resolve; @@ -21,6 +29,7 @@ export class PromiEvent implements Promise { this[Symbol.toStringTag] = 'Promise'; } + /** The then method. */ then( onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, @@ -30,6 +39,7 @@ export class PromiEvent implements Promise { return this.promise.then(onfulfilled, onrejected) } + /** The catch method. */ catch( onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null @@ -37,18 +47,23 @@ export class PromiEvent implements Promise { return this.promise.then(onrejected) } + /** The finally method. */ finally(onfinally?: (() => void) | undefined | null): Promise { return this.promise; } + /** The resolve method. */ resolve(val:T) { this._resolve(val) } + /** The reject method. */ reject(reason:any) { this._reject(reason) } + /** The once method. */ once(type: string, handler: (res: any) => void): PromiEvent { this.eventEmitter.once(type, handler); return this; }; + /** The on method. */ on(type: string, handler: (res: any) => void): PromiEvent { this.eventEmitter.on(type, handler); return this; From 6daf7ec805da2aa864f95bbedd4ff6034fb1a8c7 Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Mon, 18 Sep 2023 10:28:55 +0900 Subject: [PATCH 09/30] Improve the typedoc comments of Provider class --- src/provider.ts | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/provider.ts b/src/provider.ts index ff2c306..fb0093d 100644 --- a/src/provider.ts +++ b/src/provider.ts @@ -6,15 +6,24 @@ import { BlockchainError } from './errors'; const JSON_RPC_ENDPOINT = 'json-rpc'; +/** + * A class for providing JSON-RPC channels with blockchain node endpoints. + */ export default class Provider { + /** The blockchain node endpoint. */ public endpoint: string; + /** The blockchain node JSON-RPC endpoint. */ public apiEndpoint: string; + /** The Ain object. */ private ain: Ain; + /** The axios http client object. */ private httpClient: AxiosInstance; /** - * @param {String} endpoint - * @constructor + * Creates a new Provider object. + * @param {Ain} ain The Ain object. + * @param {string} endpoint The blockchain node endpoint. + * @param {AxiosRequestConfig} axiosConfig The axios request config object. */ constructor(ain: Ain, endpoint: string, axiosConfig: AxiosRequestConfig | undefined) { this.ain = ain; @@ -29,9 +38,9 @@ export default class Provider { } /** - * Creates the JSON-RPC payload and sends it to the node. - * @param {string} rpcMethod - * @param {any} params + * Creates a JSON-RPC payload and sends it to the network. + * @param {string} rpcMethod The JSON-RPC method. + * @param {any} params The JSON-RPC parameters. * @return {Promise} */ async send(rpcMethod: string, params?: any): Promise { @@ -53,8 +62,8 @@ export default class Provider { } /** - * Sets the httpClient's default timeout time - * @param {number} time (in milliseconds) + * Sets the http client's default timeout value. + * @param {number} time The timeout value (in milliseconds). */ setDefaultTimeoutMs(time: number) { this.httpClient.defaults.timeout = time; From b282fd433c2e421f87774921048650a1da76b292 Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Mon, 18 Sep 2023 10:39:54 +0900 Subject: [PATCH 10/30] Remove a deprecated file --- src/request.ts | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 src/request.ts diff --git a/src/request.ts b/src/request.ts deleted file mode 100644 index 6619fc2..0000000 --- a/src/request.ts +++ /dev/null @@ -1,9 +0,0 @@ -// This is a mock module for sending requests and having delays. -export default function request(url: string) { - return new Promise(resolve => { - process.nextTick(() => { - if (url.includes("Count") || url.includes("Amount")) resolve(31); - resolve('test_string'); - }); - }); -} From 9d526b91bebd3e5d507023cfa17c9a021f6d192d Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Mon, 18 Sep 2023 13:17:39 +0900 Subject: [PATCH 11/30] Add typedoc comments for types and interfaces --- src/types.ts | 171 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 164 insertions(+), 7 deletions(-) diff --git a/src/types.ts b/src/types.ts index fc665b5..f6d79fd 100755 --- a/src/types.ts +++ b/src/types.ts @@ -7,14 +7,26 @@ declare global { } } +/** + * An interface for account. + */ export interface Account { + /** The address. */ address: string; + /** The private key. */ private_key: string; + /** The public key. */ public_key: string; } +/** + * An interface for account list. + */ export interface Accounts {[address: string]: Account} +/** + * The key derivation function parameters. + */ export interface KdfParams { dklen: number; salt: string; @@ -25,6 +37,9 @@ export interface KdfParams { p?: number; } +/** + * An interface for V3Keystore options. + */ export interface V3KeystoreOptions { salt?: string; iv?: Buffer; @@ -39,6 +54,9 @@ export interface V3KeystoreOptions { uuid?: Buffer; } +/** + * An interface for keystore files in Ethereum wallet format version 3. + */ export interface V3Keystore { version: 3; id: string; @@ -55,23 +73,41 @@ export interface V3Keystore { }; } +/** + * A type for Ain options. + */ export type AinOptions = { + /** The raw result mode option. */ rawResultMode?: boolean; + /** The axios request config object. */ axiosConfig?: AxiosRequestConfig | undefined; } // export type EventType = "value" | "child_added" | "child_changed" | "child_removed"; +/** + * A type for multi-set (SET) operation type value. + */ export type SetMultiOperationType = "SET"; -export type GetMultiOperationType = "GET"; - +/** + * A type for set operation type values. + */ export type SetOperationType = "SET_VALUE" | "INC_VALUE" | "DEC_VALUE" | "SET_RULE" | "SET_OWNER" | "SET_FUNCTION"; +/** + * A type for get operation type values. + */ export type GetOperationType = "GET_VALUE" | "GET_RULE" | "GET_OWNER" | "GET_FUNCTION"; +/** + * A type for owner permission values. + */ export type OwnerPermission = "branch_owner" | "write_function" | "write_owner" | "write_rule"; +/** + * A type for blockchain get API options. + */ export type GetOptions = { is_global?: boolean; is_final?: boolean; @@ -81,6 +117,9 @@ export type GetOptions = { include_proof?: boolean; } +/** + * An interface for blockchain set operation. + */ export interface SetOperation { type: SetOperationType; ref: string; @@ -88,26 +127,33 @@ export interface SetOperation { is_global?: boolean; } +/** + * An interface for blockchain multi-set (SET) operation. + */ export interface SetMultiOperation { type: SetMultiOperationType; op_list: SetOperation[]; } +/** + * An interface for blockchain get operation. + */ export interface GetOperation extends GetOptions { type: GetOperationType; ref?: string; } -export interface GetMultiOperation { - type: GetMultiOperationType; - op_list: GetOperation[]; -} - +/** + * An interface for transactions body base. + */ export interface TransactionBodyBase { parent_tx_hash?: string; operation: SetOperation | SetMultiOperation; } +/** + * An interface for value-only transaction body base. + */ export interface ValueOnlyTransactionBodyBase { parent_tx_hash?: string; value?: any; @@ -115,6 +161,9 @@ export interface ValueOnlyTransactionBodyBase { is_global?: boolean; } +/** + * An interface for transaction input base. + */ export interface TransactionInputBase { nonce?: number; address?: string; @@ -123,6 +172,9 @@ export interface TransactionInputBase { billing?: string; } +/** + * An interface for transaction body. + */ export interface TransactionBody extends TransactionBodyBase { nonce: number; timestamp: number; @@ -130,15 +182,27 @@ export interface TransactionBody extends TransactionBodyBase { billing?: string; } +/** + * An interface for transaction input. + */ export interface TransactionInput extends TransactionBodyBase, TransactionInputBase {} +/** + * An interface for value-only transaction input. + */ export interface ValueOnlyTransactionInput extends ValueOnlyTransactionBodyBase, TransactionInputBase {} +/** + * An interface for multi-set (SET) transaction input. + */ export interface SetMultiTransactionInput extends TransactionInputBase { parent_tx_hash?: string; op_list?: SetOperation[]; } +/** + * An interface for transaction. + */ export interface Transaction { tx_body: TransactionBody; signature: string; @@ -146,6 +210,9 @@ export interface Transaction { address: string; } +/** + * An interface for transaction information. + */ export interface TransactionInfo { transaction: Transaction; status: string; @@ -156,6 +223,9 @@ export interface TransactionInfo { finalized_at: number; } +/** + * An interface for transaction result. + */ export interface TransactionResult { status: boolean; block_hash?: string; @@ -166,6 +236,9 @@ export interface TransactionResult { parent_tx_hash?: string; } +/** + * An interface for blockchain block. + */ export interface Block { number: number; epoch: number; @@ -182,10 +255,16 @@ export interface Block { transactions_hash: string; } +/** + * An interface for listener map. + */ export interface ListenerMap { [key: string]: Function[]; } +/** + * An interface for eval rule (EVAL_RULE) input. + */ export interface EvalRuleInput { value: any; ref?: string; @@ -194,6 +273,9 @@ export interface EvalRuleInput { is_global?: boolean; } +/** + * An interface for eval owner (EVAL_RULE) input. + */ export interface EvalOwnerInput { ref?: string; address?: string; @@ -201,33 +283,51 @@ export interface EvalOwnerInput { is_global?: boolean; } +/** + * An interface for match input. + */ export interface MatchInput { ref?: string; is_global?: boolean; } +/** + * An interface for state usage information. + */ export interface StateUsageInfo { tree_height?: number; tree_size?: number; tree_bytes?: number; } +/** + * An interface for app name validation information. + */ export interface AppNameValidationInfo { is_valid: boolean; code: number; message?: string; } +/** + * A type for homomorphic encryption (HE) parameters. + */ export type HomomorphicEncryptionParams = { polyModulusDegree: number; coeffModulusArray: Int32Array; scaleBit: number; } +/** + * A type for homomorphic encryption (HE) secret key. + */ export type HomomorphicEncryptionSecretKey = { secretKey: string; } +/** + * Blockchain event types for blockchain event handler. + */ export enum BlockchainEventTypes { BLOCK_FINALIZED = 'BLOCK_FINALIZED', VALUE_CHANGED = 'VALUE_CHANGED', @@ -235,6 +335,9 @@ export enum BlockchainEventTypes { FILTER_DELETED = 'FILTER_DELETED', } +/** + * Event channel message types for blockchain event handler. + */ export enum EventChannelMessageTypes { REGISTER_FILTER = 'REGISTER_FILTER', DEREGISTER_FILTER = 'DEREGISTER_FILTER', @@ -242,48 +345,81 @@ export enum EventChannelMessageTypes { EMIT_ERROR = 'EMIT_ERROR', } +/** + * An interface for event channel message (blockchain event handler). + */ export interface EventChannelMessage { type: EventChannelMessageTypes; data: any; } +/** + * An interface for block-finalized event configuration (blockchain event handler). + */ export interface BlockFinalizedEventConfig { block_number: number | null; } +/** + * A type for value changed event source (blockchain event handler). + */ export type ValueChangedEventSource = 'BLOCK' | 'USER'; +/** + * An interface for value-changed event configuraiton (blockchain event handler). + */ export interface ValueChangedEventConfig { path: string; event_source: ValueChangedEventSource | null; } +/** + * An interface for transaction-state-changed event configuration (blockchain event handler). + */ export interface TxStateChangedEventConfig { tx_hash: string; } +/** + * A type for event configuration (blockchain event handler). + */ export type EventConfigType = BlockFinalizedEventConfig | ValueChangedEventConfig | TxStateChangedEventConfig; +/** + * An interface for event-channel-connection option (blockchain event handler). + */ export interface EventChannelConnectionOption { handshakeTimeout?: number; heartbeatIntervalMs?: number; } +/** + * An interface for error handling (blockchain event handler). + */ export interface ErrorFirstCallback { (err: any, result?: undefined | null): void; (err: undefined | null, result: T): void; } +/** + * An interface for block-finalized event (blockchain event handler). + */ export interface BlockFinalizedEvent { block_number: number; block_hash: string; } +/** + * An interface for value-changed event authentication (blockchain event handler). + */ export interface ValueChangedEventAuth { addr?: string; fid?: string; } +/** + * An interface for value-changed event (blockchain event handler). + */ export interface ValueChangedEvent { filter_path: string; matched_path: string; @@ -297,6 +433,9 @@ export interface ValueChangedEvent { }; } +/** + * Transaction states for transaction-state-changed event (blockchain event handler). + */ export enum TransactionStates { FINALIZED = 'FINALIZED', REVERTED = 'REVERTED', // Failed but included in a block @@ -307,6 +446,9 @@ export enum TransactionStates { TIMED_OUT = 'TIMED_OUT', }; +/** + * An interface for transaction-state-changed event (blockchain event handler). + */ export interface TxStateChangedEvent { transaction: Transaction; tx_state: { @@ -315,22 +457,37 @@ export interface TxStateChangedEvent { }; } +/** + * Filter deletion reasons (blockchain event handler). + */ export enum FilterDeletionReasons { FILTER_TIMEOUT = 'FILTER_TIMEOUT', END_STATE_REACHED = 'END_STATE_REACHED', } +/** + * An interface for filter-deleted event (blockchain event handler). + */ export interface FilterDeletedEvent { filter_id: string; reason: FilterDeletionReasons; } +/** + * An interface for blockchain event callback (blockchain event handler). + */ export interface BlockchainEventCallback { (event: BlockFinalizedEvent): void; (event: ValueChangedEvent): void; (event: TxStateChangedEvent): void; } +/** + * A type for filter-deleted event callback (blockchain event handler). + */ export type FilterDeletedEventCallback = (event: FilterDeletedEvent) => void; +/** + * A type for disconnected callback (blockchain event handler). + */ export type DisconnectCallback = (webSocket) => void; From d666a87bc79e01c1953ab731259b12516a1025e6 Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Mon, 18 Sep 2023 13:18:47 +0900 Subject: [PATCH 12/30] Comment out typedoc comments for commented functions --- src/ain-db/ref.ts | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/ain-db/ref.ts b/src/ain-db/ref.ts index 68f4de1..01020ef 100755 --- a/src/ain-db/ref.ts +++ b/src/ain-db/ref.ts @@ -324,12 +324,12 @@ export default class Reference { return this._ain.provider.send('ain_matchOwner', request); } - /** - * TODO(liayoo): Add this function. - * Attaches an listener for database events. - * @param {EventType} event - A type of event. - * @param {Function} callback function to be executed when an event occurs. - */ + // TODO(liayoo): Add this function. + ///** + // * Attaches an listener for database events. + // * @param {EventType} event - A type of event. + // * @param {Function} callback function to be executed when an event occurs. + // */ // on(event: EventType, callback: Function) { // if (this._isRootReference) { // throw new Error('[ain-js.Reference.on] Cannot attach an on() listener to a root node'); @@ -349,12 +349,12 @@ export default class Reference { // }, 1000); // } - /** - * TODO (liayoo): Add this function - * Removes a database event listener. - * @param {EventType} event - A type of event. - * @param {Function} callback - A callback function to dettach from the event. - */ + // TODO(liayoo): Add this function. + ///** + // * Removes a database event listener. + // * @param {EventType} event - A type of event. + // * @param {Function} callback - A callback function to dettach from the event. + // */ // off(event?: EventType, callback?: Function) { // if (!event && !callback) { // this._listeners = {}; From 0e0488af7689759e38b7042d101586735f585d7a Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Mon, 18 Sep 2023 19:47:26 +0900 Subject: [PATCH 13/30] Add typedoc comments for Wallet class --- src/wallet.ts | 114 ++++++++++++++++++++++++++++---------------------- 1 file changed, 64 insertions(+), 50 deletions(-) diff --git a/src/wallet.ts b/src/wallet.ts index 7178f78..b517b50 100755 --- a/src/wallet.ts +++ b/src/wallet.ts @@ -1,18 +1,28 @@ -import { Accounts, Account, TransactionBody, V3Keystore, V3KeystoreOptions, KdfParams } from './types'; +import { Accounts, Account, TransactionBody, V3Keystore, V3KeystoreOptions } from './types'; import Ain from './ain'; import { validateMnemonic, mnemonicToSeedSync } from 'bip39'; import Reference from './ain-db/ref'; const AIN_HD_DERIVATION_PATH = "m/44'/412'/0'/0/"; /* default wallet address for AIN */ +/** + * A class for AI Network wallets. + */ export default class Wallet { + /** The default account. */ public defaultAccount: Account | null; + /** The list of accounts. */ public accounts: Accounts; + /** The number of accounts. */ public _length: number; + /** The Ain object. */ public ain: Ain; + /** The chain ID of the blockchain. */ public chainId: number; /** - * @constructor + * Creates a new Wallet object. + * @param {Ain} ain The Ain object. + * @param {number} chainId The chain ID. */ constructor(ain: Ain, chainId: number) { this.defaultAccount = null; @@ -49,8 +59,9 @@ export default class Wallet { } /** - * Creates {numberOfAccounts} new accounts and add them to the wallet. + * Creates {numberOfAccounts} new accounts and adds them to the wallet. * @param {number} numberOfAccounts + * @return {Array} The created new accounts. */ create(numberOfAccounts: number): Array { if (numberOfAccounts <= 0) throw Error("numberOfAccounts should be greater than 0."); @@ -67,7 +78,7 @@ export default class Wallet { /** * Returns whether the address has already been added to the wallet. - * @param {string} address + * @param {string} address The address to check. * @return {boolean} */ isAdded(address: string): boolean { @@ -76,7 +87,8 @@ export default class Wallet { /** * Adds a new account from the given private key. - * @param {string} privateKey + * @param {string} privateKey The private key. + * @return {string} The address of the newly added account. */ add(privateKey: string): string { let newAccount = Wallet.fromPrivateKey(Buffer.from(privateKey, 'hex')); @@ -87,8 +99,8 @@ export default class Wallet { /** * Adds a new account from the given private key and sets the new account as the default account. - * @param {string} privateKey - * @return {string} address + * @param {string} privateKey The private key. + * @return {string} The address of the newly added account. */ addAndSetDefaultAccount(privateKey: string): string { const address = this.add(privateKey); @@ -99,9 +111,9 @@ export default class Wallet { /** * Adds an account from a seed phrase. Only the account at the given * index (default = 0) will be added. - * @param {string} seedPhrase - * @param {number} index - * @return {string} - The address of the newly added account. + * @param {string} seedPhrase The seed phrase. + * @param {number} index The index of the account. + * @return {string} The address of the newly added account. */ addFromHDWallet(seedPhrase: string, index: number = 0): string { if (index < 0) { @@ -128,9 +140,9 @@ export default class Wallet { /** * Adds an account from a V3 Keystore. - * @param {V3Keystore | string} v3Keystore - * @param {string} [password] - * @return {string} - The address of the newly added account. + * @param {V3Keystore | string} v3Keystore The v3 keystore. + * @param {string} [password] The password of the v3 keystore. + * @return {string} The address of the newly added account. */ addFromV3Keystore(v3Keystore: V3Keystore | string, password: string): string { const privateKey = Ain.utils.v3KeystoreToPrivate(v3Keystore, password); @@ -139,8 +151,8 @@ export default class Wallet { } /** - * Removes an account - * @param {string} address + * Removes an account from the wallet. + * @param {string} address The address of the account to be removed. */ remove(address: string) { let addressToRemove = Ain.utils.toChecksumAddress(address); @@ -158,7 +170,7 @@ export default class Wallet { /** * Sets the default account as {address}. The account should be already added * in the wallet. - * @param {string} address + * @param {string} address The address of the account. */ setDefaultAccount(address: string) { const checksummed = Ain.utils.toChecksumAddress(address); @@ -190,7 +202,7 @@ export default class Wallet { * it returns the defaultAccount. It throws an error if * an address is not given and defaultAccount is not set, or * the specified address is not added to the wallet. - * @param {string} address + * @param {string} address The address of the account. */ getImpliedAddress(inputAddress?: string) { const address = inputAddress || (this.defaultAccount ? this.defaultAccount.address : null); @@ -205,8 +217,9 @@ export default class Wallet { } /** - * Returns the AIN balance of the address. - * @param {string} address - Defaults to the defaultAccount. + * Fetches the AIN balance of the address. + * @param {string} address The address of the account. It defaults to the default account of the wallet. + * @returns {Promise} The AIN balance of the account. */ getBalance(address?: string): Promise { const addr = address ? Ain.utils.toChecksumAddress(address) @@ -216,8 +229,9 @@ export default class Wallet { /** * Sends a transfer transaction to the network. - * @param input - * @param {boolean} isDryrun - dryrun option. + * @param {{to: string, value: number, from?: string, nonce?: number, gas_price?: number}} input The input parameters of the transaction. + * @param {boolean} isDryrun The dryrun option. + * @returns {Promise} The return value of the blockchain API. */ transfer(input: {to: string, value: number, from?: string, nonce?: number, gas_price?: number}, isDryrun: boolean = false): Promise { const address = this.getImpliedAddress(input.from); @@ -229,10 +243,10 @@ export default class Wallet { /** * Signs a string data with the private key of the given address. It will use - * the defaultAccount if an address is not provided. - * @param {string} data - * @param {string} address - * @return {string} - signature + * the default account if an address is not provided. + * @param {string} data The data to sign. + * @param {string} address The address of the account. It defaults to the default account of the wallet. + * @return {string} The signature. */ sign(data: string, address?: string): string { const addr = this.getImpliedAddress(address); @@ -240,20 +254,21 @@ export default class Wallet { } /** - * Signs a transaction data with the private key of the given address. It will use - * the defaultAccount if an address is not provided. - * @param {TransactionBody} data - * @param {string} address - * @return {string} - signature + * Signs a transaction body with the private key of the given address. It will use + * the default account if an address is not provided. + * @param {TransactionBody} txBody The transaction body. + * @param {string} address The address of the account. It defaults to the adefault account of the wallet.. + * @return {string} The signature. */ - signTransaction(tx: TransactionBody, address?: string): string { + signTransaction(txBody: TransactionBody, address?: string): string { const addr = this.getImpliedAddress(address); - return Ain.utils.ecSignTransaction(tx, Buffer.from(this.accounts[addr].private_key, 'hex'), this.chainId); + return Ain.utils.ecSignTransaction(txBody, Buffer.from(this.accounts[addr].private_key, 'hex'), this.chainId); } /** * Gets the hash from the signature. - * @param {string} signature + * @param {string} signature The signature. + * @returns {string} The hash of the signature. */ getHashStrFromSig(signature: string): string { const sigBuffer = Ain.utils.toBuffer(signature); @@ -265,8 +280,8 @@ export default class Wallet { /** * Recovers an address of the account that was used to create the signature. - * @param {string} signature - * @return {string} - address + * @param {string} signature The signature. + * @return {string} The address recovered. */ recover(signature: string): string { const sigBuffer = Ain.utils.toBuffer(signature); @@ -281,9 +296,9 @@ export default class Wallet { /** * Verifies if the signature is valid and was signed by the address. - * @param {any} data - * @param {string} signature - * @param {string} address + * @param {any} data The data used in the signing. + * @param {string} signature The signature to verify. + * @param {string} address The address to verify. * @return {boolean} */ verifySignature(data: any, signature: string, address: string): boolean { @@ -291,10 +306,10 @@ export default class Wallet { } /** - * Save the accounts in the wallet as V3 Keystores, locking them with the password. - * @param {string} password - * @param {V3KeystoreOptions} options - * @return {V3Keystore[]} + * Saves the accounts in the wallet as V3 Keystores, locking them with the password. + * @param {string} password The password. + * @param {V3KeystoreOptions} options The v3 keystore options. + * @return {V3Keystore[]} The v3 keystores. */ toV3Keystore(password: string, options: V3KeystoreOptions = {}): V3Keystore[] { let V3KeystoreArr: V3Keystore[] = []; @@ -306,12 +321,11 @@ export default class Wallet { } /** - * Converts an account into a V3 Keystore and encrypts it with a password. - * @param {TransactionBody} data - * @param {string} address - * @param {string} password - * @param {V3KeystoreOptions} options - * @return {V3Keystore} + * Converts an account into a v3 keystore and encrypts it with a password. + * @param {string} address The address of the account. + * @param {string} password The password. + * @param {V3KeystoreOptions} options The v3 keystore options. + * @return {V3Keystore} The v3 keystore. */ accountToV3Keystore( address: string, @@ -327,8 +341,8 @@ export default class Wallet { /** * Imports an account from a private key. - * @param {Buffer} privateKey - * @return {Account} + * @param {Buffer} privateKey The private key. + * @return {Account} The account. */ static fromPrivateKey(privateKey: Buffer): Account { let publicKey = Ain.utils.privateToPublic(privateKey); From b13987b3c80dff0e7d5d37a40834bf8180302059 Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Tue, 19 Sep 2023 11:10:43 +0900 Subject: [PATCH 14/30] Tweak some comments --- src/ain.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ain.ts b/src/ain.ts index 925f79b..c909fc0 100755 --- a/src/ain.ts +++ b/src/ain.ts @@ -173,7 +173,7 @@ export default class Ain { } /** - * Sends signed multiple transactions in a batch to the network. + * Signs and sends multiple transactions in a batch to the network. * @param {TransactionInput[]} transactionObjects The list of the transaction input objects. * @return {Promise} */ From 0feecd1b81430b683d55b7c64da77e72c719d077 Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Tue, 19 Sep 2023 11:42:24 +0900 Subject: [PATCH 15/30] Tweak typedoc comments --- src/ain.ts | 10 +++++----- src/types.ts | 10 +++++----- src/wallet.ts | 10 +++++----- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/ain.ts b/src/ain.ts index c909fc0..5ba52ab 100755 --- a/src/ain.ts +++ b/src/ain.ts @@ -125,7 +125,7 @@ export default class Ain { } /** - * Fetches the information of a transaction with a transaction hash. + * Fetches a transaction's information with a transaction hash. * @param {string} transactionHash The transaction hash. * @return {Promise} */ @@ -134,7 +134,7 @@ export default class Ain { } /** - * Fetches the state usage information of a blockchain app. + * Fetches a blockchain app's state usage information with an app name. * @param {string} appName The blockchain app name. * @return {Promise} */ @@ -143,7 +143,7 @@ export default class Ain { } /** - * Validates a blockchain app name. + * Validates a blockchain app's name. * @param {string} appName The blockchain app name. * @return {Promise} */ @@ -219,7 +219,7 @@ export default class Ain { } /** - * Checks whether an object is an instance of the TransactionBody interface. + * Checks whether an object is an instance of TransactionBody interface. * @param {any} object The object to check. * @return {boolean} */ @@ -231,7 +231,7 @@ export default class Ain { /** * A base function for all staking related database changes. It builds a * deposit/withdraw transaction and sends the transaction by calling sendTransaction(). - * @param {string} path The path to set a value. + * @param {string} path The path to set a value with. * @param {ValueOnlyTransactionInput} transactionObject The transaction input object. * @param {boolean} isDryrun The dryrun option. * @return {Promise} diff --git a/src/types.ts b/src/types.ts index f6d79fd..23caa4f 100755 --- a/src/types.ts +++ b/src/types.ts @@ -25,7 +25,7 @@ export interface Account { export interface Accounts {[address: string]: Account} /** - * The key derivation function parameters. + * An interface for key derivation function parameters. */ export interface KdfParams { dklen: number; @@ -144,7 +144,7 @@ export interface GetOperation extends GetOptions { } /** - * An interface for transactions body base. + * An interface for transaction body base. */ export interface TransactionBodyBase { parent_tx_hash?: string; @@ -274,7 +274,7 @@ export interface EvalRuleInput { } /** - * An interface for eval owner (EVAL_RULE) input. + * An interface for eval owner (EVAL_OWNER) input. */ export interface EvalOwnerInput { ref?: string; @@ -361,7 +361,7 @@ export interface BlockFinalizedEventConfig { } /** - * A type for value changed event source (blockchain event handler). + * A type for value-changed event source (blockchain event handler). */ export type ValueChangedEventSource = 'BLOCK' | 'USER'; @@ -394,7 +394,7 @@ export interface EventChannelConnectionOption { } /** - * An interface for error handling (blockchain event handler). + * An interface for error handling callbacks (blockchain event handler). */ export interface ErrorFirstCallback { (err: any, result?: undefined | null): void; diff --git a/src/wallet.ts b/src/wallet.ts index b517b50..72e527d 100755 --- a/src/wallet.ts +++ b/src/wallet.ts @@ -59,9 +59,9 @@ export default class Wallet { } /** - * Creates {numberOfAccounts} new accounts and adds them to the wallet. - * @param {number} numberOfAccounts - * @return {Array} The created new accounts. + * Creates new accounts and adds them to the wallet. + * @param {number} numberOfAccounts The number of accounts to create. + * @return {Array} The newly created accounts. */ create(numberOfAccounts: number): Array { if (numberOfAccounts <= 0) throw Error("numberOfAccounts should be greater than 0."); @@ -139,7 +139,7 @@ export default class Wallet { } /** - * Adds an account from a V3 Keystore. + * Adds an account from a v3 keystore. * @param {V3Keystore | string} v3Keystore The v3 keystore. * @param {string} [password] The password of the v3 keystore. * @return {string} The address of the newly added account. @@ -306,7 +306,7 @@ export default class Wallet { } /** - * Saves the accounts in the wallet as V3 Keystores, locking them with the password. + * Saves the accounts in the wallet as v3 keystores, locking them with the password. * @param {string} password The password. * @param {V3KeystoreOptions} options The v3 keystore options. * @return {V3Keystore[]} The v3 keystores. From 314bcb57f0198d3af33500642333d4f65211b0fd Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Tue, 19 Sep 2023 11:55:04 +0900 Subject: [PATCH 16/30] Rename EventChannelConnectionOptions --- src/event-manager/event-channel-client.ts | 4 ++-- src/event-manager/index.ts | 4 ++-- src/types.ts | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/event-manager/event-channel-client.ts b/src/event-manager/event-channel-client.ts index b239481..a5998eb 100644 --- a/src/event-manager/event-channel-client.ts +++ b/src/event-manager/event-channel-client.ts @@ -4,7 +4,7 @@ import { EventChannelMessageTypes, EventChannelMessage, BlockchainEventTypes, - EventChannelConnectionOption, + EventChannelConnectionOptions, DisconnectCallback, } from '../types'; import EventFilter from './event-filter'; @@ -34,7 +34,7 @@ export default class EventChannelClient { return this._isConnected; } - connect(connectionOption: EventChannelConnectionOption, disconnectCallback?: DisconnectCallback) { + connect(connectionOption: EventChannelConnectionOptions, disconnectCallback?: DisconnectCallback) { return new Promise(async (resolve, reject) => { if (this.isConnected) { reject(new Error(`Can't connect multiple channels`)); diff --git a/src/event-manager/index.ts b/src/event-manager/index.ts index 5724b67..4045451 100644 --- a/src/event-manager/index.ts +++ b/src/event-manager/index.ts @@ -2,7 +2,7 @@ import Ain from '../ain'; import { BlockFinalizedEventConfig, BlockFinalizedEvent, ErrorFirstCallback, - EventChannelConnectionOption, + EventChannelConnectionOptions, EventConfigType, BlockchainEventCallback, TxStateChangedEventConfig, TxStateChangedEvent, ValueChangedEventConfig, ValueChangedEvent, DisconnectCallback, FilterDeletedEventCallback, @@ -22,7 +22,7 @@ export default class EventManager { this._eventChannelClient = new EventChannelClient(ain, this._eventCallbackManager); } - async connect(connectionOption?: EventChannelConnectionOption, disconnectCallback?: DisconnectCallback) { + async connect(connectionOption?: EventChannelConnectionOptions, disconnectCallback?: DisconnectCallback) { await this._eventChannelClient.connect(connectionOption || {}, disconnectCallback); } diff --git a/src/types.ts b/src/types.ts index 23caa4f..a8da388 100755 --- a/src/types.ts +++ b/src/types.ts @@ -38,7 +38,7 @@ export interface KdfParams { } /** - * An interface for V3Keystore options. + * An interface for v3 keystore options. */ export interface V3KeystoreOptions { salt?: string; @@ -386,9 +386,9 @@ export interface TxStateChangedEventConfig { export type EventConfigType = BlockFinalizedEventConfig | ValueChangedEventConfig | TxStateChangedEventConfig; /** - * An interface for event-channel-connection option (blockchain event handler). + * An interface for event-channel-connection options (blockchain event handler). */ -export interface EventChannelConnectionOption { +export interface EventChannelConnectionOptions { handshakeTimeout?: number; heartbeatIntervalMs?: number; } From 36122d10bd9fefe1d7f2eaf4035b8d380d1f6088 Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Tue, 19 Sep 2023 15:58:20 +0900 Subject: [PATCH 17/30] Add typedoc comments for Database class --- src/ain-db/db.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/ain-db/db.ts b/src/ain-db/db.ts index d2f3d60..be1aa62 100755 --- a/src/ain-db/db.ts +++ b/src/ain-db/db.ts @@ -2,15 +2,19 @@ import Reference from './ref'; import Ain from '../ain'; import Provider from '../provider'; +/** + * A class for managing blockchain database states. + */ export default class Database { + /** The network provider object. */ public provider: Provider; + /** The Ain object. */ private _ain: Ain; /** - * @param {Ain} ain - * @param {Provider} provider - * - * @constructor + * Creates a new Database object. + * @param {Ain} ain The Ain object. + * @param {Provider} provider The network provider object. */ constructor(ain: Ain, provider: Provider) { this.provider = provider; @@ -19,7 +23,7 @@ export default class Database { /** * Returns a reference instance of the given path. - * @param {String} path + * @param {String} path The path to refer to. * @return {Reference} A reference instance of the given path. */ ref(path?: string): Reference { From 8694f5a28e123af095c9c0d8943887d256a706dc Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Tue, 19 Sep 2023 17:41:39 +0900 Subject: [PATCH 18/30] Add typedoc comments for Reference class --- src/ain-db/ref.ts | 193 ++++++++++++++++++++++++++-------------------- 1 file changed, 111 insertions(+), 82 deletions(-) diff --git a/src/ain-db/ref.ts b/src/ain-db/ref.ts index 01020ef..e769764 100755 --- a/src/ain-db/ref.ts +++ b/src/ain-db/ref.ts @@ -4,7 +4,6 @@ import { ListenerMap, SetOperationType, GetOperationType, - SetMultiOperationType, SetMultiOperation, TransactionInput, ValueOnlyTransactionInput, @@ -17,6 +16,9 @@ import { import Ain from '../ain'; import { PushId } from './push-id'; +/** + * A class for referencing the states of the blockchain database. + */ export default class Reference { public readonly path: string; public readonly key: string | null; @@ -27,9 +29,9 @@ export default class Reference { private _isGlobal: boolean; /** - * @param {Ain} ain An ain instance. - * @param {String} path The path in the global state tree. - * @constructor + * Creates a new Reference object. + * @param {Ain} ain The Ain object. + * @param {string} path The path to refer to in the global state tree. */ constructor(ain: Ain, path?: string) { this.path = Reference.sanitizeRef(path); @@ -51,18 +53,21 @@ export default class Reference { } /** - * A getter for number of listeners. - * @return {number} The number of listeners. + * Getter for the number of listeners. + * @returns {number} The number of listeners. */ get numberOfListeners(): number { return this._numberOfListeners; } /** - * If value is given, it sets the value at a new child of this.path; - * otherwise, it creates a key for a new child but doesn't set any values. - * @param {any} value - A value to set at the path. - * @return {Promise | Reference} A reference instance of the given path. + * Pushes a new child state to the current path of the blockchain states and + * returns the reference of the child state. + * If a value is given, it's set as the value of the newly added child + * by sending a transaction to the network. Otherwise, it creates a key locally + * for a new child but doesn't change any blockchain states. + * @param {any} value The value of the newly added child state. + * @returns {Promise | Reference} The reference of the newly added child state. */ push(value?: any): Promise | Reference { const newKey = "/" + PushId.generate(); @@ -74,8 +79,10 @@ export default class Reference { } /** - * Returns the value at the path. - * @param path + * Fetches the value of a blockchain state path. + * @param {string} path The path of the blockchain state. + * @param {GetOperation} options The get options. + * @returns {Promise} The value of the blockchain state. */ getValue(path?: string, options?: GetOptions): Promise { const req = Reference.buildGetRequest('GET_VALUE', Reference.extendPath(this.path, path), options); @@ -83,8 +90,10 @@ export default class Reference { } /** - * Returns the rule at the path. - * @param path + * Fetches the rule configuration of a blockchain state path. + * @param {string} path The path of the blockchain state. + * @param {GetOperation} options The get options. + * @returns {Promise} The rule configuration the blockchain state. */ getRule(path?: string, options?: GetOptions): Promise { const req = Reference.buildGetRequest('GET_RULE', Reference.extendPath(this.path, path), options); @@ -92,8 +101,10 @@ export default class Reference { } /** - * Returns the owner config at the path. - * @param path + * Fetches the owner configuration of a blockchain state path. + * @param {string} path The path of the blockchain state. + * @param {GetOperation} options The get options. + * @returns {Promise} The owner configuration of the blockchain state. */ getOwner(path?: string, options?: GetOptions): Promise { const req = Reference.buildGetRequest('GET_OWNER', Reference.extendPath(this.path, path), options); @@ -101,8 +112,10 @@ export default class Reference { } /** - * Returns the function config at the path. - * @param path + * Fetches the function configuration of a blockchain state path. + * @param {string} path The path of the blockchain state. + * @param {GetOperation} options The get options. + * @returns {Promise} The function configuration of the blockchain state. */ getFunction(path?: string, options?: GetOptions): Promise { const req = Reference.buildGetRequest('GET_FUNCTION', Reference.extendPath(this.path, path), options); @@ -110,10 +123,9 @@ export default class Reference { } /** - * Returns the value / write rule / owner rule / function hash at multiple paths. - * @param {Array} requests - Array of get requests - * Could be any one from "VALUE", "RULE", "OWNER", "FUNC" or a combination of them as an array. - * @return {Promise} + * Performs multiple get operations for values, rules, owners, or functions. + * @param {Array} gets The get operations. + * @returns {Promise} The results of the get operations. */ get(gets: GetOperation[]): Promise { const request = { type: 'GET', op_list: gets }; @@ -124,11 +136,11 @@ export default class Reference { } /** - * Deletes a value. - * @param {ValueOnlyTransactionInput} transactionInput - A transaction input object. + * Deletes a value from the blockchain states. + * @param {ValueOnlyTransactionInput} transactionInput The transaction input object. * Any value given will be overwritten with null. - * @param {boolean} isDryrun - dryrun option. - * @return {Promise} + * @param {boolean} isDryrun The dryrun option. + * @returns {Promise} The return value of the blockchain API. */ deleteValue(transactionInput?: ValueOnlyTransactionInput, isDryrun: boolean = false): Promise { let txInput: ValueOnlyTransactionInput = transactionInput || {}; @@ -145,9 +157,10 @@ export default class Reference { } /** - * Sets a function config. - * @param transactionInput - * @param {boolean} isDryrun - dryrun option. + * Sets a function configuration in the blockchain states. + * @param transactionInput The transaction input object. + * @param {boolean} isDryrun The dryrun option. + * @returns {Promise} The return value of the blockchain API. */ setFunction(transactionInput: ValueOnlyTransactionInput, isDryrun: boolean = false): Promise { return this._ain.sendTransaction( @@ -162,10 +175,10 @@ export default class Reference { } /** - * Sets the owner rule. - * @param {ValueOnlyTransactionInput} transactionInput - A transaction input object. - * @param {boolean} isDryrun - dryrun option. - * @return {Promise} + * Sets a owner configuration in the blockchain states. + * @param transactionInput The transaction input object. + * @param {boolean} isDryrun The dryrun option. + * @returns {Promise} The return value of the blockchain API. */ setOwner(transactionInput: ValueOnlyTransactionInput, isDryrun: boolean = false): Promise { return this._ain.sendTransaction( @@ -180,10 +193,10 @@ export default class Reference { } /** - * Sets the write rule. - * @param {ValueOnlyTransactionInput} transactionInput - A transaction input object. - * @param {boolean} isDryrun - dryrun option. - * @return {Promise} + * Sets a rule configuration in the blockchain states. + * @param transactionInput The transaction input object. + * @param {boolean} isDryrun The dryrun option. + * @returns {Promise} The return value of the blockchain API. */ setRule(transactionInput: ValueOnlyTransactionInput, isDryrun: boolean = false): Promise { return this._ain.sendTransaction( @@ -198,10 +211,10 @@ export default class Reference { } /** - * Sets a value. - * @param {ValueOnlyTransactionInput} transactionInput - A transaction input object. - * @param {boolean} isDryrun - dryrun option. - * @return {Promise} + * Sets a value in the blockchain states. + * @param transactionInput The transaction input object. + * @param {boolean} isDryrun The dryrun option. + * @returns {Promise} The return value of the blockchain API. */ setValue(transactionInput: ValueOnlyTransactionInput, isDryrun: boolean = false): Promise { return this._ain.sendTransaction( @@ -216,10 +229,10 @@ export default class Reference { } /** - * Increments the value. - * @param {ValueOnlyTransactionInput} transactionInput - A transaction input object. - * @param {boolean} isDryrun - dryrun option. - * @return {Promise} + * Increments a value in the blockchain states. + * @param transactionInput The transaction input object. + * @param {boolean} isDryrun The dryrun option. + * @returns {Promise} The return value of the blockchain API. */ incrementValue(transactionInput: ValueOnlyTransactionInput, isDryrun: boolean = false): Promise { return this._ain.sendTransaction( @@ -234,10 +247,10 @@ export default class Reference { } /** - * Decrements the value. - * @param {ValueOnlyTransactionInput} transactionInput - A transaction input object. - * @param {boolean} isDryrun - dryrun option. - * @return {Promise} + * Decrements a value in the blockchain states. + * @param transactionInput The transaction input object. + * @param {boolean} isDryrun The dryrun option. + * @returns {Promise} The return value of the blockchain API. */ decrementValue(transactionInput: ValueOnlyTransactionInput, isDryrun: boolean = false): Promise { return this._ain.sendTransaction( @@ -252,10 +265,10 @@ export default class Reference { } /** - * Processes multiple set operations. - * @param {SetMultiTransactionInput} transactionInput - A transaction input object. - * @param {boolean} isDryrun - dryrun option. - * @return {Promise} + * Sends a transaction of multi-set (SET) operation to the network. + * @param transactionInput The multi-set (SET) transaction input object. + * @param {boolean} isDryrun The dryrun option. + * @returns {Promise} The return value of the blockchain API. */ set(transactionInput: SetMultiTransactionInput, isDryrun: boolean = false): Promise { return this._ain.sendTransaction( @@ -263,9 +276,12 @@ export default class Reference { } /** - * Returns the rule evaluation result. True if the params satisfy the write rule, - * false if not. - * @param params + * Requests an eval-rule (EVAL_RULE) operation to the network. + * If it returns true, it means that the input operation satisfies the write rule + * in the blockchain states. + * @param transactionInput The multi-set (SET) transaction input object. + * @param {boolean} isDryrun The dryrun option. + * @returns {Promise} The return value of the blockchain API. */ evalRule(params: EvalRuleInput): Promise { const address = this._ain.signer.getAddress(params.address); @@ -279,8 +295,12 @@ export default class Reference { } /** - * Returns the owner evaluation result. - * @param params + * Requests an eval-owner (EVAL_OWNER) operation to the network. + * If it returns true, it means that the input operation satisfies the owner permissions + * in the blockchain states. + * @param transactionInput The multi-set (SET) transaction input object. + * @param {boolean} isDryrun The dryrun option. + * @returns {Promise} The return value of the blockchain API. */ evalOwner(params: EvalOwnerInput): Promise { const request = { @@ -292,8 +312,9 @@ export default class Reference { } /** - * Returns the function configs that are related to the input ref. - * @param params + * Fetches the function configurations matched to the input reference (blockchain state path). + * @param {MatchInput} params The match input object. + * @returns {Promise} The return value of the blockchain API. */ matchFunction(params?: MatchInput): Promise { const request = { @@ -303,8 +324,9 @@ export default class Reference { } /** - * Returns the rule configs that are related to the input ref. - * @param params + * Fetches the rule configurations matched to the input reference (blockchain state path). + * @param {MatchInput} params The match input object. + * @returns {Promise} The return value of the blockchain API. */ matchRule(params?: MatchInput): Promise { const request = { @@ -314,8 +336,9 @@ export default class Reference { } /** - * Returns the owner configs that are related to the input ref. - * @param params + * Fetches the owner configurations matched to the input reference (blockchain state path). + * @param {MatchInput} params The match input object. + * @returns {Promise} The return value of the blockchain API. */ matchOwner(params?: MatchInput): Promise { const request = { @@ -376,10 +399,12 @@ export default class Reference { /** * Builds a get request. - * @param type - * @param ref + * @param {GetOperationType} type The get operations type. + * @param {string} ref The blockchain state reference (path). + * @param {GetOptions} options The get options. + * @returns {any} The request built. */ - static buildGetRequest(type: GetOperationType, ref: string, options?: GetOptions) { + static buildGetRequest(type: GetOperationType, ref: string, options?: GetOptions): any { const request = { type, ref: Reference.sanitizeRef(ref) }; if (options) { Object.assign(request, options); @@ -388,9 +413,10 @@ export default class Reference { } /** - * Returns a path that is the basePath extended with extension. - * @param basePath - * @param extension + * Extends a base path with an extension. + * @param {string} basePath The base path. + * @param {string} extension The extension. + * @returns {string} The extended path. */ static extendPath(basePath?: string, extension?: string): string { const sanitizedBase = Reference.sanitizeRef(basePath); @@ -405,11 +431,12 @@ export default class Reference { } /** - * Decorates a transaction input with an appropriate type, ref and value. - * @param {ValueOnlyTransactionInput} input - A transaction input object - * @param {string} ref - The path at which set operations will take place - * @param {SetOperationType} type - A type of set operations - * @return {TransactionInput} + * Builds a transaction input object from a value-only transaction input object + * and additional parameters. + * @param {ValueOnlyTransactionInput} input The value-only transaction input object. + * @param {string} ref The blockchain state reference (path). + * @param {SetOperationType} type The set operation type. + * @returns {TransactionInput} The transaction input built. */ static extendSetTransactionInput( input: ValueOnlyTransactionInput, @@ -429,11 +456,12 @@ export default class Reference { } /** - * Decorates a transaction input with an appropriate type and op_list. - * @param {SetMultiTransactionInput} input - A transaction input object - * @param {string} ref - The path at which set operations will take place - * @param {SetMultiOperationType} type - A type of set operations - * @return {TransactionInput} + * Builds a transaction input object from a multi-set (SET) transaction input object + * and additional parameters. + * @param {ValueOnlyTransactionInput} input The multi-set (SET) transaction input object. + * @param {string} ref The blockchain state reference (path). + * @param {SetOperationType} type The set operation type. + * @returns {TransactionInput} The transaction input built. */ static extendSetMultiTransactionInput( input: SetMultiTransactionInput, @@ -451,9 +479,10 @@ export default class Reference { } /** - * Returns a sanitized ref. If should have a slash at the + * Returns a sanitized blockchain state reference (path). It should have a slash at the * beginning and no slash at the end. - * @param ref + * @param {string} ref The blockchain state reference (path). + * @returns {string} The blockchain state reference sanitized. */ static sanitizeRef(ref?: string): string { if (!ref) return '/'; From 23e01b5dd8528b6f1e4b3bfd2d7dadde390cdc6e Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Tue, 19 Sep 2023 17:42:17 +0900 Subject: [PATCH 19/30] Change to @returns --- src/ain-db/db.ts | 4 ++-- src/ain.ts | 28 ++++++++++++++-------------- src/net.ts | 6 +++--- src/provider.ts | 2 +- src/signer/ain-wallet-signer.ts | 2 +- src/signer/default-signer.ts | 8 ++++---- src/signer/signer.ts | 4 ++-- src/wallet.ts | 28 ++++++++++++++-------------- 8 files changed, 41 insertions(+), 41 deletions(-) diff --git a/src/ain-db/db.ts b/src/ain-db/db.ts index be1aa62..d41c6c8 100755 --- a/src/ain-db/db.ts +++ b/src/ain-db/db.ts @@ -3,7 +3,7 @@ import Ain from '../ain'; import Provider from '../provider'; /** - * A class for managing blockchain database states. + * A class for managing the states of the blockchain database. */ export default class Database { /** The network provider object. */ @@ -24,7 +24,7 @@ export default class Database { /** * Returns a reference instance of the given path. * @param {String} path The path to refer to. - * @return {Reference} A reference instance of the given path. + * @returns {Reference} A reference instance of the given path. */ ref(path?: string): Reference { return new Reference(this._ain, path); diff --git a/src/ain.ts b/src/ain.ts index 5ba52ab..05b69c2 100755 --- a/src/ain.ts +++ b/src/ain.ts @@ -89,7 +89,7 @@ export default class Ain { * @param {string | number} blockHashOrBlockNumber The block hash or block number. * @param {boolean} returnTransactionObjects If it's true, returns a block with full transaction objects. * Otherwise, returns a block with only transaction hashes. - * @return {Promise} + * @returns {Promise} */ getBlock(blockHashOrBlockNumber: string | number, returnTransactionObjects?: boolean): Promise { const byHash = typeof blockHashOrBlockNumber === 'string' @@ -103,7 +103,7 @@ export default class Ain { /** * Fetches the forger's address of a block with a block hash or block number. * @param {string | number} blockHashOrBlockNumber The block hash or block number. - * @return {Promise} + * @returns {Promise} */ getProposer(blockHashOrBlockNumber: string | number): Promise { const byHash = typeof blockHashOrBlockNumber === 'string' @@ -115,7 +115,7 @@ export default class Ain { /** * Fetches the validator list of a block with a block hash or block number. * @param {string | number} blockHashOrBlockNumber The block hash or block number. - * @return {Promise} + * @returns {Promise} */ getValidators(blockHashOrBlockNumber: string | number): Promise { const byHash = typeof blockHashOrBlockNumber === 'string' @@ -127,7 +127,7 @@ export default class Ain { /** * Fetches a transaction's information with a transaction hash. * @param {string} transactionHash The transaction hash. - * @return {Promise} + * @returns {Promise} */ getTransaction(transactionHash: string): Promise { return this.provider.send('ain_getTransactionByHash', { hash: transactionHash }); @@ -136,7 +136,7 @@ export default class Ain { /** * Fetches a blockchain app's state usage information with an app name. * @param {string} appName The blockchain app name. - * @return {Promise} + * @returns {Promise} */ getStateUsage(appName: string): Promise { return this.provider.send('ain_getStateUsage', { app_name: appName }); @@ -145,7 +145,7 @@ export default class Ain { /** * Validates a blockchain app's name. * @param {string} appName The blockchain app name. - * @return {Promise} + * @returns {Promise} */ validateAppName(appName: string): Promise { return this.provider.send('ain_validateAppName', { app_name: appName }); @@ -155,7 +155,7 @@ export default class Ain { * Signs and sends a transaction to the network. * @param {TransactionInput} transactionObject The transaction input object. * @param {boolean} isDryrun The dryrun option. - * @return {Promise} + * @returns {Promise} */ async sendTransaction(transactionObject: TransactionInput, isDryrun: boolean = false): Promise { return this.signer.sendTransaction(transactionObject, isDryrun); @@ -166,7 +166,7 @@ export default class Ain { * @param {string} signature The signature of the transaction. * @param {TransactionBody} txBody The transaction body. * @param {boolean} isDryrun The dryrun option. - * @return {Promise} + * @returns {Promise} */ async sendSignedTransaction(signature: string, txBody: TransactionBody, isDryrun: boolean = false): Promise { return this.signer.sendSignedTransaction(signature, txBody, isDryrun); @@ -175,7 +175,7 @@ export default class Ain { /** * Signs and sends multiple transactions in a batch to the network. * @param {TransactionInput[]} transactionObjects The list of the transaction input objects. - * @return {Promise} + * @returns {Promise} */ async sendTransactionBatch(transactionObjects: TransactionInput[]): Promise { return this.signer.sendTransactionBatch(transactionObjects); @@ -184,7 +184,7 @@ export default class Ain { /** * Sends a transaction that deposits AIN for consensus staking. * @param {ValueOnlyTransactionInput} transactionObject The transaction input object. - * @return {Promise} + * @returns {Promise} */ depositConsensusStake(transactionObject: ValueOnlyTransactionInput): Promise { return this.stakeFunction('/deposit/consensus', transactionObject); @@ -193,7 +193,7 @@ export default class Ain { /** * Sends a transaction that withdraws AIN for consensus staking. * @param {ValueOnlyTransactionInput} transactionObject The transaction input object. - * @return {Promise} + * @returns {Promise} */ withdrawConsensusStake(transactionObject: ValueOnlyTransactionInput): Promise { return this.stakeFunction('/withdraw/consensus', transactionObject); @@ -203,7 +203,7 @@ export default class Ain { * Fetches the amount of AIN currently staked for participating in consensus protocol. * @param {string} account The account to fetch the value with. If not specified, * the default account of the signer is used. - * @return {Promise} + * @returns {Promise} */ getConsensusStakeAmount(account?: string): Promise { const address = account ? Ain.utils.toChecksumAddress(account) @@ -221,7 +221,7 @@ export default class Ain { /** * Checks whether an object is an instance of TransactionBody interface. * @param {any} object The object to check. - * @return {boolean} + * @returns {boolean} */ static instanceofTransactionBody(object: any): object is TransactionBody { return object.nonce !== undefined && object.timestamp !== undefined && @@ -234,7 +234,7 @@ export default class Ain { * @param {string} path The path to set a value with. * @param {ValueOnlyTransactionInput} transactionObject The transaction input object. * @param {boolean} isDryrun The dryrun option. - * @return {Promise} + * @returns {Promise} */ private stakeFunction(path: string, transactionObject: ValueOnlyTransactionInput, isDryrun: boolean = false): Promise { const type: SetOperationType = "SET_VALUE"; diff --git a/src/net.ts b/src/net.ts index 61c24c3..c42a9f0 100755 --- a/src/net.ts +++ b/src/net.ts @@ -22,7 +22,7 @@ export default class Network { /** * Checks whether the blockchain node is listening for network connections. - * @return {Promise} + * @returns {Promise} */ isListening(): Promise { return this.provider.send('net_listening'); @@ -51,7 +51,7 @@ export default class Network { /** * Fetches the number of the peers the blockchain node is connected to. - * @return {Promise} + * @returns {Promise} */ getPeerCount(): Promise { return this.provider.send('net_peerCount'); @@ -59,7 +59,7 @@ export default class Network { /** * Checks whether the blockchain node is syncing with the network or not. - * @return {Promise} + * @returns {Promise} */ isSyncing(): Promise { return this.provider.send('net_syncing'); diff --git a/src/provider.ts b/src/provider.ts index fb0093d..e1ec746 100644 --- a/src/provider.ts +++ b/src/provider.ts @@ -41,7 +41,7 @@ export default class Provider { * Creates a JSON-RPC payload and sends it to the network. * @param {string} rpcMethod The JSON-RPC method. * @param {any} params The JSON-RPC parameters. - * @return {Promise} + * @returns {Promise} */ async send(rpcMethod: string, params?: any): Promise { const data = { diff --git a/src/signer/ain-wallet-signer.ts b/src/signer/ain-wallet-signer.ts index b174286..8c50e54 100644 --- a/src/signer/ain-wallet-signer.ts +++ b/src/signer/ain-wallet-signer.ts @@ -42,7 +42,7 @@ export class AinWalletSigner implements Signer { * Signs and sends a transaction to the network. * @param {TransactionInput} transactionObject * @param {boolean} isDryrun - dryrun option. - * @return {Promise} + * @returns {Promise} */ sendTransaction(transactionObject: TransactionInput) { return this.ainetwork.sendTransaction(transactionObject); diff --git a/src/signer/default-signer.ts b/src/signer/default-signer.ts index 0bc527d..1ce0bf6 100644 --- a/src/signer/default-signer.ts +++ b/src/signer/default-signer.ts @@ -45,7 +45,7 @@ export class DefaultSigner implements Signer { * Signs and sends a transaction to the network. * @param {TransactionInput} transactionObject * @param {boolean} isDryrun - dryrun option. - * @return {Promise} + * @returns {Promise} */ async sendTransaction(transactionObject: TransactionInput, isDryrun: boolean = false) { const txBody = await this.buildTransactionBody(transactionObject); @@ -94,7 +94,7 @@ export class DefaultSigner implements Signer { * @param {string} signature * @param {TransactionBody} txBody * @param {boolean} isDryrun - dryrun option. - * @return {Promise} + * @returns {Promise} */ async sendSignedTransaction(signature: string, txBody: TransactionBody, isDryrun: boolean = false): Promise { const method = isDryrun ? 'ain_sendSignedTransactionDryrun' : 'ain_sendSignedTransaction'; @@ -108,7 +108,7 @@ export class DefaultSigner implements Signer { /** * Builds a transaction body from transaction input. * @param {TransactionInput} transactionInput - * @return {Promise} + * @returns {Promise} */ async buildTransactionBody(transactionInput: TransactionInput): Promise { const address = this.getAddress(transactionInput.address); @@ -133,7 +133,7 @@ export class DefaultSigner implements Signer { * nonce of, and the 'from' indicates where to get the nonce from. * It could be either the pending transaction pool ("pending") or * the committed blocks ("committed"). The default value is "committed". - * @return {Promise} + * @returns {Promise} */ getNonce(args: { address?: string, from?: string }): Promise { if (!args) { args = {}; } diff --git a/src/signer/signer.ts b/src/signer/signer.ts index 90c4173..ef6f981 100644 --- a/src/signer/signer.ts +++ b/src/signer/signer.ts @@ -23,7 +23,7 @@ export interface Signer { * Signs and sends a transaction to the network. * @param {TransactionInput} transactionObject * @param {boolean} isDryrun - dryrun option. - * @return {Promise} + * @returns {Promise} */ sendTransaction(transactionObject: TransactionInput, isDryrun?: boolean); @@ -38,7 +38,7 @@ export interface Signer { * @param {string} signature * @param {TransactionBody} txBody * @param {boolean} isDryrun - dryrun option. - * @return {Promise} + * @returns {Promise} */ sendSignedTransaction(signature: string, txBody: TransactionBody, isDryrun?: boolean): Promise } diff --git a/src/wallet.ts b/src/wallet.ts index 72e527d..fef037b 100755 --- a/src/wallet.ts +++ b/src/wallet.ts @@ -50,7 +50,7 @@ export default class Wallet { /** * Returns the full public key of the given address. * @param {string} address - * @return {string} + * @returns {string} */ getPublicKey(address: string): string { const checksummed = Ain.utils.toChecksumAddress(address); @@ -61,7 +61,7 @@ export default class Wallet { /** * Creates new accounts and adds them to the wallet. * @param {number} numberOfAccounts The number of accounts to create. - * @return {Array} The newly created accounts. + * @returns {Array} The newly created accounts. */ create(numberOfAccounts: number): Array { if (numberOfAccounts <= 0) throw Error("numberOfAccounts should be greater than 0."); @@ -79,7 +79,7 @@ export default class Wallet { /** * Returns whether the address has already been added to the wallet. * @param {string} address The address to check. - * @return {boolean} + * @returns {boolean} */ isAdded(address: string): boolean { return !!(this.accounts[Ain.utils.toChecksumAddress(address)]) @@ -88,7 +88,7 @@ export default class Wallet { /** * Adds a new account from the given private key. * @param {string} privateKey The private key. - * @return {string} The address of the newly added account. + * @returns {string} The address of the newly added account. */ add(privateKey: string): string { let newAccount = Wallet.fromPrivateKey(Buffer.from(privateKey, 'hex')); @@ -100,7 +100,7 @@ export default class Wallet { /** * Adds a new account from the given private key and sets the new account as the default account. * @param {string} privateKey The private key. - * @return {string} The address of the newly added account. + * @returns {string} The address of the newly added account. */ addAndSetDefaultAccount(privateKey: string): string { const address = this.add(privateKey); @@ -113,7 +113,7 @@ export default class Wallet { * index (default = 0) will be added. * @param {string} seedPhrase The seed phrase. * @param {number} index The index of the account. - * @return {string} The address of the newly added account. + * @returns {string} The address of the newly added account. */ addFromHDWallet(seedPhrase: string, index: number = 0): string { if (index < 0) { @@ -142,7 +142,7 @@ export default class Wallet { * Adds an account from a v3 keystore. * @param {V3Keystore | string} v3Keystore The v3 keystore. * @param {string} [password] The password of the v3 keystore. - * @return {string} The address of the newly added account. + * @returns {string} The address of the newly added account. */ addFromV3Keystore(v3Keystore: V3Keystore | string, password: string): string { const privateKey = Ain.utils.v3KeystoreToPrivate(v3Keystore, password); @@ -246,7 +246,7 @@ export default class Wallet { * the default account if an address is not provided. * @param {string} data The data to sign. * @param {string} address The address of the account. It defaults to the default account of the wallet. - * @return {string} The signature. + * @returns {string} The signature. */ sign(data: string, address?: string): string { const addr = this.getImpliedAddress(address); @@ -258,7 +258,7 @@ export default class Wallet { * the default account if an address is not provided. * @param {TransactionBody} txBody The transaction body. * @param {string} address The address of the account. It defaults to the adefault account of the wallet.. - * @return {string} The signature. + * @returns {string} The signature. */ signTransaction(txBody: TransactionBody, address?: string): string { const addr = this.getImpliedAddress(address); @@ -281,7 +281,7 @@ export default class Wallet { /** * Recovers an address of the account that was used to create the signature. * @param {string} signature The signature. - * @return {string} The address recovered. + * @returns {string} The address recovered. */ recover(signature: string): string { const sigBuffer = Ain.utils.toBuffer(signature); @@ -299,7 +299,7 @@ export default class Wallet { * @param {any} data The data used in the signing. * @param {string} signature The signature to verify. * @param {string} address The address to verify. - * @return {boolean} + * @returns {boolean} */ verifySignature(data: any, signature: string, address: string): boolean { return Ain.utils.ecVerifySig(data, signature, address, this.chainId); @@ -309,7 +309,7 @@ export default class Wallet { * Saves the accounts in the wallet as v3 keystores, locking them with the password. * @param {string} password The password. * @param {V3KeystoreOptions} options The v3 keystore options. - * @return {V3Keystore[]} The v3 keystores. + * @returns {V3Keystore[]} The v3 keystores. */ toV3Keystore(password: string, options: V3KeystoreOptions = {}): V3Keystore[] { let V3KeystoreArr: V3Keystore[] = []; @@ -325,7 +325,7 @@ export default class Wallet { * @param {string} address The address of the account. * @param {string} password The password. * @param {V3KeystoreOptions} options The v3 keystore options. - * @return {V3Keystore} The v3 keystore. + * @returns {V3Keystore} The v3 keystore. */ accountToV3Keystore( address: string, @@ -342,7 +342,7 @@ export default class Wallet { /** * Imports an account from a private key. * @param {Buffer} privateKey The private key. - * @return {Account} The account. + * @returns {Account} The account. */ static fromPrivateKey(privateKey: Buffer): Account { let publicKey = Ain.utils.privateToPublic(privateKey); From c29f3338fa3475f0de51230a3776d9966e2dbce0 Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Wed, 20 Sep 2023 14:06:12 +0900 Subject: [PATCH 20/30] Tweak typedoc comments for signers --- src/signer/ain-wallet-signer.ts | 34 +++++++++++------ src/signer/default-signer.ts | 65 ++++++++++++++++++--------------- src/signer/signer.ts | 37 ++++++++++--------- 3 files changed, 78 insertions(+), 58 deletions(-) diff --git a/src/signer/ain-wallet-signer.ts b/src/signer/ain-wallet-signer.ts index 8c50e54..ddae075 100644 --- a/src/signer/ain-wallet-signer.ts +++ b/src/signer/ain-wallet-signer.ts @@ -2,14 +2,16 @@ import { TransactionBody, TransactionInput } from "../types"; import { Signer } from "./signer"; /** - * A signer class for AIN Wallet chrome extension + * A class of Signer interface for AIN Wallet chrome extension * (https://chrome.google.com/webstore/detail/ain-wallet/hbdheoebpgogdkagfojahleegjfkhkpl). */ export class AinWalletSigner implements Signer { + /** The Ain Wallet object. */ private ainetwork: Signer; /** - * Initializes the class based on the AIN Wallet's global variable. + * Creates a new AinWalletSigner object. + * It initializes the Ain Wallet object using the global variable 'window'. */ constructor() { if (window.ainetwork) { @@ -20,19 +22,21 @@ export class AinWalletSigner implements Signer { } /** - * Returns the checksum address to sign messages with. - * If the address is not given, the default address of the wallet is used. - * @param {string} address - The address of the account to sign the message with. + * Gets an account's checksum address. + * If the address is not given, the default account of the Ain Wallet is used. + * @param {string} address The address of the account. + * @returns {string} The checksum address. */ getAddress(address?: string): string { return this.ainetwork.getAddress(address); } /** - * Signs a message with the private key of the given address. - * If an address is not given, the default address of the wallet is used. - * @param {any} message - The message to sign. - * @param {string} address - The address of the account to sign the message with. + * Signs a message using an account. + * If an address is not given, the default account of the Ain Wallet is used. + * @param {string} message The message to sign. + * @param {string} address The address of the account. + * @returns {Promise | string} The signature. */ signMessage(message: any, address?: string): Promise | string { return this.ainetwork.signMessage(message, address); @@ -40,18 +44,24 @@ export class AinWalletSigner implements Signer { /** * Signs and sends a transaction to the network. - * @param {TransactionInput} transactionObject - * @param {boolean} isDryrun - dryrun option. - * @returns {Promise} + * @param {TransactionInput} transactionObject The transaction input object. + * @param {boolean} isDryrun The dryrun option. + * @returns {Promise} The return value of the blockchain API. */ sendTransaction(transactionObject: TransactionInput) { return this.ainetwork.sendTransaction(transactionObject); } + /** + * This method is not implemented yet. + */ sendTransactionBatch(transactionObjects: TransactionInput[]): Promise { throw new Error("Method not implemented."); } + /** + * This method is not implemented yet. + */ sendSignedTransaction(signature: string, txBody: TransactionBody, isDryrun?: boolean | undefined): Promise { throw new Error("Method not implemented."); } diff --git a/src/signer/default-signer.ts b/src/signer/default-signer.ts index 1ce0bf6..cfa5a89 100644 --- a/src/signer/default-signer.ts +++ b/src/signer/default-signer.ts @@ -10,12 +10,15 @@ import Ain from "../ain"; * When Ain class is initialized, DefaultSigner is set as its signer. */ export class DefaultSigner implements Signer { + /** The wallet object. */ readonly wallet: Wallet; + /** The network provider object. */ readonly provider: Provider; /** - * Initializes the class. - * @param {Wallet} wallet - The wallet to initialize with. + * Creates a new DefaultClass object. + * @param {Wallet} wallet The wallet object. + * @param {Provider} provider The network provider object. */ constructor(wallet: Wallet, provider: Provider) { this.wallet = wallet; @@ -23,19 +26,21 @@ export class DefaultSigner implements Signer { } /** - * Returns the checksum address to sign messages with. - * If the address is not given, the default address of the wallet is used. - * @param {string} address - The address of the account to sign the message with. + * Gets an account's checksum address. + * If the address is not given, the default account of the wallet is used. + * @param {string} address The address of the account. + * @returns {string} The checksum address. */ getAddress(address?: string): string { return this.wallet.getImpliedAddress(address); } /** - * Signs a message with the private key of the given address. - * If an address is not given, the default address of the wallet is used. - * @param {string} message - The message to sign. - * @param {string} address - The address of the account to sign the message with. + * Signs a message using an account. + * If an address is not given, the default account of the wallet is used. + * @param {string} message The message to sign. + * @param {string} address The address of the account. + * @returns {Promise | string} The signature. */ signMessage(message: string, address?: string): Promise | string { return this.wallet.sign(message, address); @@ -43,9 +48,9 @@ export class DefaultSigner implements Signer { /** * Signs and sends a transaction to the network. - * @param {TransactionInput} transactionObject - * @param {boolean} isDryrun - dryrun option. - * @returns {Promise} + * @param {TransactionInput} transactionObject The transaction input object. + * @param {boolean} isDryrun The dryrun option. + * @returns {Promise} The return value of the blockchain API. */ async sendTransaction(transactionObject: TransactionInput, isDryrun: boolean = false) { const txBody = await this.buildTransactionBody(transactionObject); @@ -54,8 +59,9 @@ export class DefaultSigner implements Signer { } /** - * Sends signed transactions to the network. - * @param {TransactionInput[]} transactionObjects + * Signs and sends multiple transactions in a batch to the network. + * @param {TransactionInput[]} transactionObjects The list of the transaction input objects. + * @returns {Promise} The return value of the blockchain API. */ async sendTransactionBatch(transactionObjects: TransactionInput[]): Promise { let promises: Promise[] = []; @@ -90,11 +96,11 @@ export class DefaultSigner implements Signer { } /** - * Sends a signed transaction to the network - * @param {string} signature - * @param {TransactionBody} txBody - * @param {boolean} isDryrun - dryrun option. - * @returns {Promise} + * Sends a signed transaction to the network. + * @param {string} signature The signature. + * @param {TransactionBody} txBody The transaction body. + * @param {boolean} isDryrun The dryrun option. + * @returns {Promise} The return value of the blockchain API. */ async sendSignedTransaction(signature: string, txBody: TransactionBody, isDryrun: boolean = false): Promise { const method = isDryrun ? 'ain_sendSignedTransactionDryrun' : 'ain_sendSignedTransaction'; @@ -106,9 +112,9 @@ export class DefaultSigner implements Signer { } /** - * Builds a transaction body from transaction input. - * @param {TransactionInput} transactionInput - * @returns {Promise} + * Builds a transaction body object from a transaction input object. + * @param {TransactionInput} transactionInput The transaction input object. + * @returns {Promise} The transaction body object. */ async buildTransactionBody(transactionInput: TransactionInput): Promise { const address = this.getAddress(transactionInput.address); @@ -127,13 +133,14 @@ export class DefaultSigner implements Signer { } /** - * Returns the current transaction count of account, which is the nonce of the account. - * @param {object} args - May contain a string 'address' and a string 'from' values. - * The 'address' indicates the address of the account to get the - * nonce of, and the 'from' indicates where to get the nonce from. - * It could be either the pending transaction pool ("pending") or - * the committed blocks ("committed"). The default value is "committed". - * @returns {Promise} + * Fetches an account's nonce value, which is the current transaction count of the account. + * @param {object} args The ferch options. + * It may contain a string 'address' value and a string 'from' value. + * The 'address' is the address of the account to get the nonce of, + * and the 'from' is the source of the data. + * It could be either the pending transaction pool ("pending") or + * the committed blocks ("committed"). The default value is "committed". + * @returns {Promise} The nonce value. */ getNonce(args: { address?: string, from?: string }): Promise { if (!args) { args = {}; } diff --git a/src/signer/signer.ts b/src/signer/signer.ts index ef6f981..085e741 100644 --- a/src/signer/signer.ts +++ b/src/signer/signer.ts @@ -5,40 +5,43 @@ import { TransactionBody, TransactionInput } from "../types"; */ export interface Signer { /** - * Returns the checksum address to sign messages with. - * If the address is not given, the default address of the signer is used. - * @param {string} address - The address of the account to sign the message with. + * Gets an account's checksum address. + * If the address is not given, the default account of the signer is used. + * @param {string} address The address of the account. + * @returns {string} The checksum address. */ getAddress(address?: string): string; /** - * Signs a message with the private key of the given address. - * If an address is not given, the default address of the signer is used. - * @param {string} message - The message to sign. - * @param {string} address - The address of the account to sign the message with. + * Signs a message using an account. + * If an address is not given, the default account of the signer is used. + * @param {string} message The message to sign. + * @param {string} address The address of the account. + * @returns {Promise | string} The signature. */ signMessage(message: string, address?: string): Promise | string; /** * Signs and sends a transaction to the network. - * @param {TransactionInput} transactionObject - * @param {boolean} isDryrun - dryrun option. - * @returns {Promise} + * @param {TransactionInput} transactionObject The transaction input object. + * @param {boolean} isDryrun The dryrun option. + * @returns {Promise} The return value of the blockchain API. */ sendTransaction(transactionObject: TransactionInput, isDryrun?: boolean); /** - * Sends signed transactions to the network. - * @param {TransactionInput[]} transactionObjects + * Signs and sends multiple transactions in a batch to the network. + * @param {TransactionInput[]} transactionObjects The list of the transaction input objects. + * @returns {Promise} The return value of the blockchain API. */ sendTransactionBatch(transactionObjects: TransactionInput[]): Promise /** - * Sends a signed transaction to the network - * @param {string} signature - * @param {TransactionBody} txBody - * @param {boolean} isDryrun - dryrun option. - * @returns {Promise} + * Sends a signed transaction to the network. + * @param {string} signature The signature. + * @param {TransactionBody} txBody The transaction body. + * @param {boolean} isDryrun The dryrun option. + * @returns {Promise} The return value of the blockchain API. */ sendSignedTransaction(signature: string, txBody: TransactionBody, isDryrun?: boolean): Promise } From 2be3e5c4dbc0ecdbdfd598b49388135e51dcbdad Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Thu, 21 Sep 2023 12:00:44 +0900 Subject: [PATCH 21/30] Add typedoc comments for HE modules --- src/he/desilo.js | 51 +++++++++++++++++++++++++----------------------- src/he/index.ts | 46 +++++++++++++++++++++++++++++++++++++++---- 2 files changed, 69 insertions(+), 28 deletions(-) diff --git a/src/he/desilo.js b/src/he/desilo.js index 7688207..f477b77 100644 --- a/src/he/desilo.js +++ b/src/he/desilo.js @@ -5,9 +5,13 @@ const SEAL = require('node-seal'); /** - * wrapper Error class for DesiloSeal + * A wrapper Error class for DesiloSeal. */ class DesiloSealError extends Error { + /** + * Creates a new DesiloSealError object with an error message. + * @param {String} message The error message. + */ constructor(message) { super(message); this.name = this.constructor.name; @@ -16,12 +20,12 @@ class DesiloSealError extends Error { } /** - * node-seal wrapper class + * A wrapper class for the Desilo's HE solution. */ class DesiloSeal { /** - * Constructor + * Creates a new DesiloSeal object. * @param {Number} polyModulusDegree * @param {Int32Array} coeffModulusArray * @param {Number} scaleBits @@ -33,7 +37,7 @@ class DesiloSeal { } /** - * Initializes new SEALContext + * Initializes new SEALContext. */ async initContext() { this.seal = await SEAL(); @@ -58,9 +62,7 @@ class DesiloSeal { } /** - * Makes a new keyset - * @param {string} secretKeyStr - secret key to load - * @param {string} publicKeyStr - public key to load + * Generates a new key set. */ initKeySet() { const keyGenerator = this.seal.KeyGenerator(this.context); @@ -78,9 +80,9 @@ class DesiloSeal { } /** - * Loads secret key - * @param {string} secretKeyStr - secret key to load - * @param {string} publicKeyStr - public key to load + * Loads a key set. + * @param {string} secretKeyStr The secret key to load. + * @param {string} publicKeyStr The public key to load. */ loadKeySet(secretKeyStr, publicKeyStr = undefined) { const secretKey = this.seal.SecretKey(); @@ -104,7 +106,7 @@ class DesiloSeal { } /** - * Initialize encryptor, decryptor, evaluator + * Initializes encryptor, decryptor, and evaluator objects. */ initClasses() { this.encryptor = this.seal.Encryptor(this.context, this.keys.publicKey); @@ -113,8 +115,9 @@ class DesiloSeal { } /** - * gets entire keyset - * @returns {object} keys + * Returns the entire key set. + * It temporarily returns the secret key only due to memory issues. + * @returns {Object} The key set. */ getKeys() { // hidden for now, due to memory issue @@ -132,8 +135,8 @@ class DesiloSeal { } /** - * gets secretKey - * @returns {seal.SecretKey} secretKey + * Returns the secret key. + * @returns {any} The secret key. */ getSecretKey() { const secretKey = this.keys.secretKey ? this.keys.secretKey.save() : ''; @@ -141,9 +144,9 @@ class DesiloSeal { } /** - * encrypts a length-fixed array into a ciphertext - * @param {Float64Array} - array of length poly_mod_degree / 2 - * @returns {CipherText} + * Encrypts a length-fixed array into a ciphertext. + * @param {Float64Array} array The array of length poly_mod_degree / 2. + * @returns {CipherText} The cipertext encrypted. */ encrypt(array) { const plaintext = this.encoder.encode(array, this.scale); @@ -155,9 +158,9 @@ class DesiloSeal { } /** - * Decrypt ciphertext - * @param {string::Ciphertext} cipherStr - ciphertext string - * @returns {Float64Array} + * Decrypts a ciphertext to an float64 array. + * @param {Ciphertext} cipherStr The ciphertext. + * @returns {Float64Array} The float64 array decrypted. */ decrypt(cipherStr) { const uploadedCipherText = this.seal.CipherText(); @@ -169,9 +172,9 @@ class DesiloSeal { } /** - * Factory method for DesiloSeal class - * @param {Object} keys - object containing sk, pk, galois-key, relin-key strings - * @returns {DesiloSeal} seal - Desilo SEAL wrapper class + * A factory method for DesiloSeal class. + * @param {Object} keys The object containing sk, pk, galois-key, and relin-key strings. + * @returns {DesiloSeal} The newly created DesiloSeal object. */ async function DesiloSealFactory(keys, params) { const { polyModulusDegree, coeffModulusArray, scaleBit } = params; diff --git a/src/he/index.ts b/src/he/index.ts index 705d90f..2a28f80 100644 --- a/src/he/index.ts +++ b/src/he/index.ts @@ -7,15 +7,29 @@ const DEFAULT_PARAMS: HomomorphicEncryptionParams = { coeffModulusArray: Int32Array.from([60, 40, 40, 60]), scaleBit: 40 }; + +/** + * A class for homorphic encryption based on the Desilo's HE solution. + */ export default class HomomorphicEncryption { + /** The DesiloSeal object. */ public seal: any; + /** Whether the class is initialized or not. */ private _initialized: boolean; + /** + * Creates a new HomorphicEncryption obect. + */ constructor() { this.seal = null; this._initialized = false; } + /** + * Initializes the class with keys and parameters. + * @param {HomomorphicEncryptionSecretKey | null} keys The secret key. + * @param {HomomorphicEncryptionParams | null} params The homorphic encryption parameters. + */ async init(keys?: HomomorphicEncryptionSecretKey | null, params?: HomomorphicEncryptionParams | null) { this.seal = await DesiloSealFactory(keys, params ? params : DEFAULT_PARAMS); if (!this.seal) { @@ -31,32 +45,56 @@ export default class HomomorphicEncryption { this._initialized = true; } + /** + * Getter for _initialized. + */ get initialized() { return this._initialized; } - TEST_getKeys() { + /** + * Returns the key set currently in use. + * It temporarily returns the secret key only due to memory issues. + * This is a method for test purposes only. + * @returns {Object} The key set. + */ + TEST_getKeys(): Object { if (!this.initialized) { throw new Error('Cannot encode before initializing.'); } return this.seal.getKeys(); } - encrypt(array: Float64Array) { + /** + * Encrypts a length-fixed array into a ciphertext. + * @param {Float64Array} array The array of length poly_mod_degree / 2. + * @returns {CipherText} The cipertext encrypted. + */ + encrypt(array: Float64Array): CipherText { if (!this.initialized) { throw new Error('Cannot encrypt before initializing.'); } return this.seal.encrypt(array); } - decrypt(cipherText: CipherText) { + /** + * Decrypts a ciphertext to an float64 array. + * @param {CipherText} cipherText The ciphertext. + * @returns {Float64Array} The float64 array decrypted. + */ + decrypt(cipherText: CipherText): Float64Array { if (!this.initialized) { throw new Error('Cannot decrypt before initializing.'); } return this.seal.decrypt(cipherText); } - TEST_evaluate_double(cipherText: CipherText) { + /** + * Doubles an input cipher text and performs a homorphic calculation on it. + * This is a method for test purposes only. + * @returns {Object} The result of the homorphic calculation. + */ + TEST_evaluate_double(cipherText: CipherText): Object { if (!this.initialized) { throw new Error('Cannot evaluate before initializing.'); } From e06317666beda90e1f129e85638729b2d76e9edf Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Thu, 21 Sep 2023 15:28:28 +0900 Subject: [PATCH 22/30] Rename: EventConfigType -> BlockchainEventConfig --- src/event-manager/event-callback-manager.ts | 4 ++-- src/event-manager/event-filter.ts | 6 +++--- src/event-manager/index.ts | 4 ++-- src/types.ts | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/event-manager/event-callback-manager.ts b/src/event-manager/event-callback-manager.ts index 8a32c2c..6b63459 100644 --- a/src/event-manager/event-callback-manager.ts +++ b/src/event-manager/event-callback-manager.ts @@ -1,6 +1,6 @@ import EventFilter from './event-filter'; import Subscription from './subscription'; -import { BlockchainEventTypes, EventConfigType, BlockchainEventCallback, FilterDeletedEventCallback, FilterDeletedEvent } from '../types'; +import { BlockchainEventTypes, BlockchainEventConfig, BlockchainEventCallback, FilterDeletedEventCallback, FilterDeletedEvent } from '../types'; import { PushId } from '../ain-db/push-id'; import { FAILED_TO_REGISTER_ERROR_CODE } from '../constants'; @@ -47,7 +47,7 @@ export default class EventCallbackManager { }); } - createFilter(eventTypeStr: string, config: EventConfigType): EventFilter { + createFilter(eventTypeStr: string, config: BlockchainEventConfig): EventFilter { const eventType = eventTypeStr as BlockchainEventTypes; if (!Object.values(BlockchainEventTypes).includes(eventType) || eventType === BlockchainEventTypes.FILTER_DELETED) { diff --git a/src/event-manager/event-filter.ts b/src/event-manager/event-filter.ts index 3280176..f298df9 100644 --- a/src/event-manager/event-filter.ts +++ b/src/event-manager/event-filter.ts @@ -1,11 +1,11 @@ -import { BlockchainEventTypes, EventConfigType } from '../types'; +import { BlockchainEventTypes, BlockchainEventConfig } from '../types'; export default class EventFilter { public readonly id: string; public readonly type: BlockchainEventTypes; - public readonly config: EventConfigType; + public readonly config: BlockchainEventConfig; - constructor(id: string, type: BlockchainEventTypes, config: EventConfigType) { + constructor(id: string, type: BlockchainEventTypes, config: BlockchainEventConfig) { this.id = id; this.type = type; this.config = config; diff --git a/src/event-manager/index.ts b/src/event-manager/index.ts index 4045451..8c85100 100644 --- a/src/event-manager/index.ts +++ b/src/event-manager/index.ts @@ -3,7 +3,7 @@ import { BlockFinalizedEventConfig, BlockFinalizedEvent, ErrorFirstCallback, EventChannelConnectionOptions, - EventConfigType, BlockchainEventCallback, + BlockchainEventConfig, BlockchainEventCallback, TxStateChangedEventConfig, TxStateChangedEvent, ValueChangedEventConfig, ValueChangedEvent, DisconnectCallback, FilterDeletedEventCallback, } from '../types'; @@ -51,7 +51,7 @@ export default class EventManager { ): string; subscribe( eventTypeStr: string, - config: EventConfigType, + config: BlockchainEventConfig, eventCallback?: BlockchainEventCallback, errorCallback?: (error: any) => void, filterDeletedEventCallback?: FilterDeletedEventCallback diff --git a/src/types.ts b/src/types.ts index a8da388..b3b8f5c 100755 --- a/src/types.ts +++ b/src/types.ts @@ -383,7 +383,7 @@ export interface TxStateChangedEventConfig { /** * A type for event configuration (blockchain event handler). */ -export type EventConfigType = BlockFinalizedEventConfig | ValueChangedEventConfig | TxStateChangedEventConfig; +export type BlockchainEventConfig = BlockFinalizedEventConfig | ValueChangedEventConfig | TxStateChangedEventConfig; /** * An interface for event-channel-connection options (blockchain event handler). From 40750be970d48e838afaf908dd5a366d7265a57e Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Thu, 21 Sep 2023 15:35:00 +0900 Subject: [PATCH 23/30] Add typedoc comments to EventFilter class --- src/event-manager/event-filter.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/event-manager/event-filter.ts b/src/event-manager/event-filter.ts index f298df9..a77cb32 100644 --- a/src/event-manager/event-filter.ts +++ b/src/event-manager/event-filter.ts @@ -1,16 +1,32 @@ import { BlockchainEventTypes, BlockchainEventConfig } from '../types'; +/** + * A class for filtering blockchain events. + */ export default class EventFilter { + /** The event filter ID. */ public readonly id: string; + /** The blockchain event type. */ public readonly type: BlockchainEventTypes; + /** The blockchain event configuration. */ public readonly config: BlockchainEventConfig; + /** + * Creates a new EventFilter object. + * @param {string} id The event filter ID object. + * @param {BlockchainEventTypes} type The blockchain event type value. + * @param {BlockchainEventConfig} config The blockchain event configuration object. + */ constructor(id: string, type: BlockchainEventTypes, config: BlockchainEventConfig) { this.id = id; this.type = type; this.config = config; } + /** + * Converts to a javascript object. + * @returns {Object} The javascript object. + */ toObject() { return { id: this.id, From 99b3b69e662384b85d3db33b8e7cf28584a522f8 Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Thu, 21 Sep 2023 15:38:23 +0900 Subject: [PATCH 24/30] Add typedoc comments for Subscription class --- src/event-manager/subscription.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/event-manager/subscription.ts b/src/event-manager/subscription.ts index 442ed1c..fa5b9bf 100644 --- a/src/event-manager/subscription.ts +++ b/src/event-manager/subscription.ts @@ -1,14 +1,25 @@ import { EventEmitter } from 'events'; import EventFilter from './event-filter'; +/** + * A class for subscribing to blockchain events based on EventEmitter class. + */ export default class Subscription extends EventEmitter { + /** The event filter object. */ private readonly _filter: EventFilter; + /** + * Creates a new Subscription object. + * @param {EventFilter} filter The event filter object. + */ constructor(filter: EventFilter) { super(); this._filter = filter; } + /** + * Getter for the event filter. + */ get filter(): EventFilter { return this._filter; } From 4ed0c6ec3dab027e4f642717f3c0346a43df61f7 Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Thu, 21 Sep 2023 16:08:16 +0900 Subject: [PATCH 25/30] Add typedoc comments for EventCallbackManager class --- src/event-manager/event-callback-manager.ts | 55 ++++++++++++++++++++- src/event-manager/subscription.ts | 2 +- 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/src/event-manager/event-callback-manager.ts b/src/event-manager/event-callback-manager.ts index 6b63459..34dfb43 100644 --- a/src/event-manager/event-callback-manager.ts +++ b/src/event-manager/event-callback-manager.ts @@ -4,23 +4,45 @@ import { BlockchainEventTypes, BlockchainEventConfig, BlockchainEventCallback, F import { PushId } from '../ain-db/push-id'; import { FAILED_TO_REGISTER_ERROR_CODE } from '../constants'; +/** + * A class for managing event callbacks. + */ export default class EventCallbackManager { + /** The event filter map from filter ID to event filter. */ private readonly _filters: Map; + /** The subscription map from filter ID to subscription. */ private readonly _filterIdToSubscription: Map; + /** + * Creates a new EventCallbackManager object. + */ constructor() { this._filters = new Map(); this._filterIdToSubscription = new Map(); } + /** + * Builds a filter ID. + * @returns {string} The filter ID built. + */ buildFilterId() { return PushId.generate(); } + /** + * Builds a subscription ID. + * @returns {string} The subscription ID built. + */ buildSubscriptionId() { return PushId.generate(); } + /** + * Emits a blockchain event to trigger callback functions. + * @param {string} filterId The filter ID. + * @param {BlockchainEventTypes} eventType The blockchain event type. + * @param {any} payload The payload of the event. + */ emitEvent(filterId: string, eventType: BlockchainEventTypes, payload: any) { const subscription = this._filterIdToSubscription.get(filterId); if (!subscription) { @@ -33,6 +55,12 @@ export default class EventCallbackManager { subscription.emit('event', payload); } + /** + * Emits an error to trigger callback functions. + * @param {string} filterId The filter ID. + * @param {number} code The error code. + * @param {string} errorMessage The error message. + */ emitError(filterId: string, code: number, errorMessage: string) { const subscription = this._filterIdToSubscription.get(filterId); if (!subscription) { @@ -47,6 +75,12 @@ export default class EventCallbackManager { }); } + /** + * Creates a new EventFilter object and adds it to the event filter map. + * @param {string} eventTypeStr The event type string. + * @param {BlockchainEventConfig} config The blockchain event configuration. + * @returns {EventFilter} The event filter object created. + */ createFilter(eventTypeStr: string, config: BlockchainEventConfig): EventFilter { const eventType = eventTypeStr as BlockchainEventTypes; if (!Object.values(BlockchainEventTypes).includes(eventType) || @@ -62,7 +96,12 @@ export default class EventCallbackManager { return filter; } - getFilter(filterId): EventFilter { + /** + * Looks up an event filter with a filter ID. + * @param {string} filterId The filter ID. + * @returns {EventFilter} The event filter looked up. + */ + getFilter(filterId: string): EventFilter { const filter = this._filters.get(filterId); if (!filter) { throw Error(`Non-existent filter ID (${filterId})`); @@ -70,13 +109,21 @@ export default class EventCallbackManager { return filter; } + /** + * Creates a new Subscription object. + * @param {EventFilter} filter The event filter. + * @param {BlockchainEventCallback} eventCallback The blockchain event callback function. + * @param {(error: any) => void} errorCallback The error callback function. + * @param {FilterDeletedEventCallback} filterDeletedEventCallback The filter deletion event callback function. + * @returns {Subscription} The subscription object created. + */ createSubscription( filter: EventFilter, eventCallback?: BlockchainEventCallback, errorCallback?: (error: any) => void, filterDeletedEventCallback: FilterDeletedEventCallback = (payload) => console.log( `Event filter (id: ${payload.filter_id}) is deleted because of ${payload.reason}`) - ) { + ): Subscription { const subscription = new Subscription(filter); subscription.on( 'filterDeleted', (payload: FilterDeletedEvent) => { @@ -94,6 +141,10 @@ export default class EventCallbackManager { return subscription; } + /** + * Deletes an event filter. + * @param {string} filterId The event filter ID to delete. + */ deleteFilter(filterId: string) { if (!this._filterIdToSubscription.delete(filterId)) { console.log(`Can't remove the subscription because it can't be found. (${filterId})`); diff --git a/src/event-manager/subscription.ts b/src/event-manager/subscription.ts index fa5b9bf..5475a32 100644 --- a/src/event-manager/subscription.ts +++ b/src/event-manager/subscription.ts @@ -2,7 +2,7 @@ import { EventEmitter } from 'events'; import EventFilter from './event-filter'; /** - * A class for subscribing to blockchain events based on EventEmitter class. + * A class for subscribing callback functions to blockchain events. */ export default class Subscription extends EventEmitter { /** The event filter object. */ From 7b731af4441067798e01432b99b8479009a529a5 Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Thu, 21 Sep 2023 17:06:05 +0900 Subject: [PATCH 26/30] Rename: DisconnectCallback -> DisconnectionCallback --- src/event-manager/event-channel-client.ts | 8 ++++---- src/event-manager/index.ts | 6 +++--- src/types.ts | 8 ++++---- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/event-manager/event-channel-client.ts b/src/event-manager/event-channel-client.ts index a5998eb..66b68ac 100644 --- a/src/event-manager/event-channel-client.ts +++ b/src/event-manager/event-channel-client.ts @@ -5,7 +5,7 @@ import { EventChannelMessage, BlockchainEventTypes, EventChannelConnectionOptions, - DisconnectCallback, + DisconnectionCallback, } from '../types'; import EventFilter from './event-filter'; import EventCallbackManager from './event-callback-manager'; @@ -34,7 +34,7 @@ export default class EventChannelClient { return this._isConnected; } - connect(connectionOption: EventChannelConnectionOptions, disconnectCallback?: DisconnectCallback) { + connect(connectionOption: EventChannelConnectionOptions, disconnectionCallback?: DisconnectionCallback) { return new Promise(async (resolve, reject) => { if (this.isConnected) { reject(new Error(`Can't connect multiple channels`)); @@ -86,8 +86,8 @@ export default class EventChannelClient { }); this._wsClient.on('close', () => { this.disconnect(); - if (disconnectCallback) { - disconnectCallback(this._wsClient); + if (disconnectionCallback) { + disconnectionCallback(this._wsClient); } }); }) diff --git a/src/event-manager/index.ts b/src/event-manager/index.ts index 8c85100..fe6f0d7 100644 --- a/src/event-manager/index.ts +++ b/src/event-manager/index.ts @@ -5,7 +5,7 @@ import { EventChannelConnectionOptions, BlockchainEventConfig, BlockchainEventCallback, TxStateChangedEventConfig, TxStateChangedEvent, - ValueChangedEventConfig, ValueChangedEvent, DisconnectCallback, FilterDeletedEventCallback, + ValueChangedEventConfig, ValueChangedEvent, DisconnectionCallback, FilterDeletedEventCallback, } from '../types'; import EventChannelClient from './event-channel-client'; import EventCallbackManager from './event-callback-manager'; @@ -22,8 +22,8 @@ export default class EventManager { this._eventChannelClient = new EventChannelClient(ain, this._eventCallbackManager); } - async connect(connectionOption?: EventChannelConnectionOptions, disconnectCallback?: DisconnectCallback) { - await this._eventChannelClient.connect(connectionOption || {}, disconnectCallback); + async connect(connectionOption?: EventChannelConnectionOptions, disconnectionCallback?: DisconnectionCallback) { + await this._eventChannelClient.connect(connectionOption || {}, disconnectionCallback); } disconnect() { diff --git a/src/types.ts b/src/types.ts index b3b8f5c..493d41e 100755 --- a/src/types.ts +++ b/src/types.ts @@ -474,7 +474,7 @@ export interface FilterDeletedEvent { } /** - * An interface for blockchain event callback (blockchain event handler). + * An interface for blockchain event callback functions (blockchain event handler). */ export interface BlockchainEventCallback { (event: BlockFinalizedEvent): void; @@ -483,11 +483,11 @@ export interface BlockchainEventCallback { } /** - * A type for filter-deleted event callback (blockchain event handler). + * A type for filter-deleted event callback functions (blockchain event handler). */ export type FilterDeletedEventCallback = (event: FilterDeletedEvent) => void; /** - * A type for disconnected callback (blockchain event handler). + * A type for disconnection callback functions (blockchain event handler). */ -export type DisconnectCallback = (webSocket) => void; +export type DisconnectionCallback = (webSocket) => void; From dae08b44e046d9d96e3ca4efcc41d16e8088f2da Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Fri, 22 Sep 2023 16:34:44 +0900 Subject: [PATCH 27/30] Add typedoc comments for EventChannelClient class --- src/event-manager/event-channel-client.ts | 61 ++++++++++++++++++++++- 1 file changed, 59 insertions(+), 2 deletions(-) diff --git a/src/event-manager/event-channel-client.ts b/src/event-manager/event-channel-client.ts index 66b68ac..1877399 100644 --- a/src/event-manager/event-channel-client.ts +++ b/src/event-manager/event-channel-client.ts @@ -13,14 +13,28 @@ import EventCallbackManager from './event-callback-manager'; const DEFAULT_HEARTBEAT_INTERVAL_MS = 15000 + 1000; // NOTE: This time must be longer than blockchain event handler heartbeat interval. const DEFAULT_HANDSHAKE_TIMEOUT_MS = 30000; +/** + * A class for managing event channels and event handling callback functions. + */ export default class EventChannelClient { + /** The Ain object. */ private readonly _ain: Ain; + /** The event callback manager object. */ private readonly _eventCallbackManager: EventCallbackManager; + /** The web socket client. */ private _wsClient?: WebSocket; + /** The blockchain endpoint URL. */ private _endpointUrl?: string; + /** Whether it's connected or not. */ private _isConnected: boolean; + /** The heartbeat timeout object. */ private _heartbeatTimeout?: ReturnType | null; + /** + * Creates a new EventChannelClient object. + * @param {Ain} ain The Ain object. + * @param {EventCallbackManager} eventCallbackManager The event callback manager object. + */ constructor(ain: Ain, eventCallbackManager: EventCallbackManager) { this._ain = ain; this._eventCallbackManager = eventCallbackManager; @@ -34,6 +48,12 @@ export default class EventChannelClient { return this._isConnected; } + /** + * Opens an event channel. + * @param {EventChannelConnectionOptions} connectionOption The event channel connection options. + * @param {DisconnectionCallback} disconnectionCallback The disconnection callback function. + * @returns {Promise} A promise for the connection success. + */ connect(connectionOption: EventChannelConnectionOptions, disconnectionCallback?: DisconnectionCallback) { return new Promise(async (resolve, reject) => { if (this.isConnected) { @@ -93,6 +113,9 @@ export default class EventChannelClient { }) } + /** + * Closes the event channel. + */ disconnect() { this._isConnected = false; this._wsClient!.terminate(); @@ -102,6 +125,10 @@ export default class EventChannelClient { } } + /** + * Starts the heartbeat timer for the event channel. + * @param {number} timeoutMs The timeout value in miliseconds. + */ startHeartbeatTimer(timeoutMs: number) { this._heartbeatTimeout = setTimeout(() => { console.log(`Connection timeout! Terminate the connection. All event subscriptions are stopped.`); @@ -109,7 +136,11 @@ export default class EventChannelClient { }, timeoutMs); } - handleEmitEventMessage(messageData) { + /** + * Handles an emit-event message from the event channel. + * @param {any} messageData The payload data of the message. + */ + handleEmitEventMessage(messageData: any) { const filterId = messageData.filter_id; if (!filterId) { throw Error(`Can't find filter ID from message data (${JSON.stringify(messageData, null, 2)})`); @@ -126,7 +157,11 @@ export default class EventChannelClient { this._eventCallbackManager.emitEvent(filterId, eventType, payload); } - handleEmitErrorMessage(messageData) { + /** + * Handles an emit-error message from the event channel. + * @param {any} messageData The payload data of the message. + */ + handleEmitErrorMessage(messageData: any) { const code = messageData.code; if (!code) { console.log(`Can't find code from message data (${JSON.stringify(messageData, null, 2)})`); @@ -145,6 +180,10 @@ export default class EventChannelClient { this._eventCallbackManager.emitError(filterId, code, errorMessage); } + /** + * Handles a message from the event channel. + * @param {string} message The message. + */ handleMessage(message: string) { try { const parsedMessage = JSON.parse(message); @@ -171,6 +210,12 @@ export default class EventChannelClient { } } + /** + * Builds a message to be sent to the event channel. + * @param {EventChannelMessageTypes} messageType The message type. + * @param {any} data The payload data of the msssage. + * @returns + */ buildMessage(messageType: EventChannelMessageTypes, data: any): EventChannelMessage { return { type: messageType, @@ -178,6 +223,10 @@ export default class EventChannelClient { }; } + /** + * Sends a message to the event channel. + * @param {EventChannelMessage} message The message to be sent. + */ sendMessage(message: EventChannelMessage) { if (!this._isConnected) { throw Error(`Failed to send message. Event channel is not connected!`); @@ -185,12 +234,20 @@ export default class EventChannelClient { this._wsClient!.send(JSON.stringify(message)); } + /** + * Sends a register-event-filter messsage to the event channel. + * @param {EventFilter} filter The event filter to register. + */ registerFilter(filter: EventFilter) { const filterObj = filter.toObject(); const registerMessage = this.buildMessage(EventChannelMessageTypes.REGISTER_FILTER, filterObj); this.sendMessage(registerMessage); } + /** + * Sends a deregister-event-filter messsage to the event channel. + * @param {EventFilter} filter The event filter to deregister. + */ deregisterFilter(filter: EventFilter) { const filterObj = filter.toObject(); const deregisterMessage = this.buildMessage(EventChannelMessageTypes.DEREGISTER_FILTER, filterObj); From 3fe44575d6ac5c08547c15ff035a679cbc516698 Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Fri, 22 Sep 2023 18:41:53 +0900 Subject: [PATCH 28/30] Add typedoc comments for EventManager class --- src/event-manager/event-channel-client.ts | 6 ++--- src/event-manager/index.ts | 33 +++++++++++++++++++++-- src/types.ts | 2 +- 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/src/event-manager/event-channel-client.ts b/src/event-manager/event-channel-client.ts index 1877399..9c64f61 100644 --- a/src/event-manager/event-channel-client.ts +++ b/src/event-manager/event-channel-client.ts @@ -49,12 +49,12 @@ export default class EventChannelClient { } /** - * Opens an event channel. + * Opens a new event channel. * @param {EventChannelConnectionOptions} connectionOption The event channel connection options. * @param {DisconnectionCallback} disconnectionCallback The disconnection callback function. * @returns {Promise} A promise for the connection success. */ - connect(connectionOption: EventChannelConnectionOptions, disconnectionCallback?: DisconnectionCallback) { + connect(connectionOption: EventChannelConnectionOptions, disconnectionCallback?: DisconnectionCallback): Promise { return new Promise(async (resolve, reject) => { if (this.isConnected) { reject(new Error(`Can't connect multiple channels`)); @@ -114,7 +114,7 @@ export default class EventChannelClient { } /** - * Closes the event channel. + * Closes the current event channel. */ disconnect() { this._isConnected = false; diff --git a/src/event-manager/index.ts b/src/event-manager/index.ts index fe6f0d7..48def12 100644 --- a/src/event-manager/index.ts +++ b/src/event-manager/index.ts @@ -11,21 +11,36 @@ import EventChannelClient from './event-channel-client'; import EventCallbackManager from './event-callback-manager'; import EventFilter from './event-filter'; +/** + * A class for managing blockchain events. + */ export default class EventManager { - private _ain: Ain; + /** The event callback manager. */ private readonly _eventCallbackManager: EventCallbackManager; + /** The event channel client. */ private readonly _eventChannelClient: EventChannelClient; + /** + * Creates a new EventManager object. + * @param {Ain} ain The Ain object. + */ constructor(ain: Ain) { - this._ain = ain; this._eventCallbackManager = new EventCallbackManager(); this._eventChannelClient = new EventChannelClient(ain, this._eventCallbackManager); } + /** + * Opens a new event channel. + * @param {EventChannelConnectionOptions} connectionOption The event channel connection options. + * @param {DisconnectionCallback} disconnectionCallback The disconnection callback function. + */ async connect(connectionOption?: EventChannelConnectionOptions, disconnectionCallback?: DisconnectionCallback) { await this._eventChannelClient.connect(connectionOption || {}, disconnectionCallback); } + /** + * Closes the current event channel. + */ disconnect() { this._eventChannelClient.disconnect(); } @@ -49,6 +64,15 @@ export default class EventManager { errorCallback?: (error: any) => void, filterDeletedEventCallback?: FilterDeletedEventCallback ): string; + /** + * Subscribes to blockchain events. + * @param {string} eventTypeStr The event type. + * @param {BlockchainEventConfig} config The blockchain event configuraiton. + * @param {BlockchainEventCallback} eventCallback The blockchain event callback function. + * @param {(error: any) => void} errorCallback The error event callback function. + * @param {FilterDeletedEventCallback} errorCallback The filter-deleted event callback function. + * @returns {string} The created filter ID. + */ subscribe( eventTypeStr: string, config: BlockchainEventConfig, @@ -65,6 +89,11 @@ export default class EventManager { return filter.id; } + /** + * Cancel a subscription. + * @param {string} filterId The filter ID of the subscription to cancel. + * @param {ErrorFirstCallback} callback The error handling callback function. + */ unsubscribe(filterId: string, callback: ErrorFirstCallback) { try { if (!this._eventChannelClient.isConnected) { diff --git a/src/types.ts b/src/types.ts index 493d41e..f672974 100755 --- a/src/types.ts +++ b/src/types.ts @@ -381,7 +381,7 @@ export interface TxStateChangedEventConfig { } /** - * A type for event configuration (blockchain event handler). + * A type for blockchain event configuration (blockchain event handler). */ export type BlockchainEventConfig = BlockFinalizedEventConfig | ValueChangedEventConfig | TxStateChangedEventConfig; From fe120e7821eb9edd75de00d30c423288d3ef4277 Mon Sep 17 00:00:00 2001 From: Dongil Seo Date: Mon, 25 Sep 2023 11:18:26 +0900 Subject: [PATCH 29/30] Define BlockchainErrorCallback type for blockchain error callback functions --- src/event-manager/event-callback-manager.ts | 6 +++--- src/event-manager/index.ts | 14 +++++++------- src/types.ts | 5 +++++ 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/src/event-manager/event-callback-manager.ts b/src/event-manager/event-callback-manager.ts index 34dfb43..77cf67f 100644 --- a/src/event-manager/event-callback-manager.ts +++ b/src/event-manager/event-callback-manager.ts @@ -1,6 +1,6 @@ import EventFilter from './event-filter'; import Subscription from './subscription'; -import { BlockchainEventTypes, BlockchainEventConfig, BlockchainEventCallback, FilterDeletedEventCallback, FilterDeletedEvent } from '../types'; +import { BlockchainEventTypes, BlockchainEventConfig, BlockchainEventCallback, BlockchainErrorCallback, FilterDeletedEventCallback, FilterDeletedEvent } from '../types'; import { PushId } from '../ain-db/push-id'; import { FAILED_TO_REGISTER_ERROR_CODE } from '../constants'; @@ -113,14 +113,14 @@ export default class EventCallbackManager { * Creates a new Subscription object. * @param {EventFilter} filter The event filter. * @param {BlockchainEventCallback} eventCallback The blockchain event callback function. - * @param {(error: any) => void} errorCallback The error callback function. + * @param {BlockchainErrorCallback} errorCallback The blockchain error callback function. * @param {FilterDeletedEventCallback} filterDeletedEventCallback The filter deletion event callback function. * @returns {Subscription} The subscription object created. */ createSubscription( filter: EventFilter, eventCallback?: BlockchainEventCallback, - errorCallback?: (error: any) => void, + errorCallback?: BlockchainErrorCallback, filterDeletedEventCallback: FilterDeletedEventCallback = (payload) => console.log( `Event filter (id: ${payload.filter_id}) is deleted because of ${payload.reason}`) ): Subscription { diff --git a/src/event-manager/index.ts b/src/event-manager/index.ts index 48def12..0e05fd2 100644 --- a/src/event-manager/index.ts +++ b/src/event-manager/index.ts @@ -5,7 +5,7 @@ import { EventChannelConnectionOptions, BlockchainEventConfig, BlockchainEventCallback, TxStateChangedEventConfig, TxStateChangedEvent, - ValueChangedEventConfig, ValueChangedEvent, DisconnectionCallback, FilterDeletedEventCallback, + ValueChangedEventConfig, ValueChangedEvent, DisconnectionCallback, FilterDeletedEventCallback, BlockchainErrorCallback, } from '../types'; import EventChannelClient from './event-channel-client'; import EventCallbackManager from './event-callback-manager'; @@ -49,19 +49,19 @@ export default class EventManager { eventType: 'BLOCK_FINALIZED', config: BlockFinalizedEventConfig, eventCallback?: (event: BlockFinalizedEvent) => void, - errorCallback?: (error: any) => void + errorCallback?: BlockchainErrorCallback ): string; subscribe( eventType: 'VALUE_CHANGED', config: ValueChangedEventConfig, eventCallback?: (event: ValueChangedEvent) => void, - errorCallback?: (error: any) => void + errorCallback?: BlockchainErrorCallback ): string; subscribe( eventType: 'TX_STATE_CHANGED', config: TxStateChangedEventConfig, eventCallback?: (event: TxStateChangedEvent) => void, - errorCallback?: (error: any) => void, + errorCallback?: BlockchainErrorCallback, filterDeletedEventCallback?: FilterDeletedEventCallback ): string; /** @@ -69,15 +69,15 @@ export default class EventManager { * @param {string} eventTypeStr The event type. * @param {BlockchainEventConfig} config The blockchain event configuraiton. * @param {BlockchainEventCallback} eventCallback The blockchain event callback function. - * @param {(error: any) => void} errorCallback The error event callback function. - * @param {FilterDeletedEventCallback} errorCallback The filter-deleted event callback function. + * @param {BlockchainErrorCallback} errorCallback The blockchain error callback function. + * @param {FilterDeletedEventCallback} filterDeletedEventCallback The filter-deleted event callback function. * @returns {string} The created filter ID. */ subscribe( eventTypeStr: string, config: BlockchainEventConfig, eventCallback?: BlockchainEventCallback, - errorCallback?: (error: any) => void, + errorCallback?: BlockchainErrorCallback, filterDeletedEventCallback?: FilterDeletedEventCallback ): string { if (!this._eventChannelClient.isConnected) { diff --git a/src/types.ts b/src/types.ts index f672974..d8c8452 100755 --- a/src/types.ts +++ b/src/types.ts @@ -482,6 +482,11 @@ export interface BlockchainEventCallback { (event: TxStateChangedEvent): void; } +/** + * A type for blockchain error callback functions (blockchain event handler). + */ +export type BlockchainErrorCallback = (error: any) => void; + /** * A type for filter-deleted event callback functions (blockchain event handler). */ From 3e219ba4da6aaf2d19495aedf24ea56796d5e4df Mon Sep 17 00:00:00 2001 From: platfowner Date: Wed, 27 Sep 2023 02:30:10 +0000 Subject: [PATCH 30/30] Upgrade version to 1.6.3 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index e9e83e8..fbc305e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ainblockchain/ain-js", - "version": "1.6.2", + "version": "1.6.3", "description": "", "main": "lib/ain.js", "scripts": {