From 4fc342e39cac3633deb153462ca30d3824eb2b27 Mon Sep 17 00:00:00 2001 From: Georgi Tsonev Date: Thu, 18 Jan 2024 14:42:47 +0200 Subject: [PATCH 1/2] chore: update docs --- packages/accounts/src/account.ts | 24 ++++++-- packages/accounts/src/account_2fa.ts | 60 ++++++++++++++++++- packages/accounts/src/account_multisig.ts | 38 +++++++++++- .../src/local-view-execution/index.ts | 9 +++ packages/biometric-ed25519/src/index.ts | 4 +- packages/crypto/src/key_pair.ts | 5 ++ packages/crypto/src/key_pair_ed25519.ts | 21 ++++++- packages/crypto/src/public_key.ts | 20 +++++++ packages/iframe-rpc/src/iframe-rpc.ts | 28 +++++++++ .../src/browser_local_storage_key_store.ts | 2 +- packages/near-api-js/src/connect.ts | 20 +++++++ packages/providers/src/fetch_json.ts | 6 ++ packages/signers/src/in_memory_signer.ts | 2 +- packages/signers/src/signer.ts | 2 + packages/transactions/src/action_creators.ts | 59 +++++++++++++++++- .../transactions/src/create_transaction.ts | 10 ++++ packages/transactions/src/delegate.ts | 12 ++-- packages/transactions/src/schema.ts | 5 ++ packages/transactions/src/sign.ts | 4 +- packages/utils/src/errors/errors.ts | 4 +- packages/utils/src/format.ts | 2 +- packages/utils/src/validators.ts | 14 ++--- packages/wallet-account/src/wallet_account.ts | 8 +++ 23 files changed, 329 insertions(+), 30 deletions(-) diff --git a/packages/accounts/src/account.ts b/packages/accounts/src/account.ts index 0ce11cbeda..d851dacfac 100644 --- a/packages/accounts/src/account.ts +++ b/packages/accounts/src/account.ts @@ -209,8 +209,14 @@ export class Account { } /** - * Sign a transaction to preform a list of actions and broadcast it using the RPC API. + * Sign a transaction to perform a list of actions and broadcast it using the RPC API. * @see {@link "@near-js/providers".json-rpc-provider.JsonRpcProvider | JsonRpcProvider } + * + * @param options The options for signing and sending the transaction. + * @param options.receiverId The NEAR account ID of the transaction receiver. + * @param options.actions The list of actions to be performed in the transaction. + * @param options.returnError Whether to return an error if the transaction fails. + * @returns {Promise} A promise that resolves to the final execution outcome of the transaction. */ async signAndSendTransaction({ receiverId, actions, returnError }: SignAndSendTransactionOptions): Promise { let txHash, signedTx; @@ -382,9 +388,19 @@ export class Account { return Buffer.concat([Buffer.from(contractId), Buffer.from([0]), Buffer.from(method), Buffer.from([0]), Buffer.from(args)]); } - /** - * Execute function call - * @returns {Promise} + /** + * Execute a function call. + * @param options The options for the function call. + * @param options.contractId The NEAR account ID of the smart contract. + * @param options.methodName The name of the method to be called on the smart contract. + * @param options.args The arguments to be passed to the method. + * @param options.gas The maximum amount of gas to be used for the function call. + * @param options.attachedDeposit The amount of NEAR tokens to be attached to the function call. + * @param options.walletMeta Metadata for wallet integration. + * @param options.walletCallbackUrl The callback URL for wallet integration. + * @param options.stringify A function to convert input arguments into bytes array + * @param options.jsContract Whether the contract is from JS SDK, automatically encodes args from JS SDK to binary. + * @returns {Promise} A promise that resolves to the final execution outcome of the function call. */ async functionCall({ contractId, methodName, args = {}, gas = DEFAULT_FUNCTION_CALL_GAS, attachedDeposit, walletMeta, walletCallbackUrl, stringify, jsContract }: ChangeFunctionCallOptions): Promise { this.validateArgs(args); diff --git a/packages/accounts/src/account_2fa.ts b/packages/accounts/src/account_2fa.ts index 6bfec76ef8..c9ab09aa5c 100644 --- a/packages/accounts/src/account_2fa.ts +++ b/packages/accounts/src/account_2fa.ts @@ -48,6 +48,11 @@ export class Account2FA extends AccountMultisig { /** * Sign a transaction to preform a list of actions and broadcast it using the RPC API. * @see {@link "@near-js/providers".json-rpc-provider.JsonRpcProvider.sendTransaction | JsonRpcProvider.sendTransaction} + * + * @param options Options for the transaction. + * @param options.receiverId The NEAR account ID of the transaction receiver. + * @param options.actions The list of actions to be included in the transaction. + * @returns {Promise} A promise that resolves to the final execution outcome of the transaction. */ async signAndSendTransaction({ receiverId, actions }: SignAndSendTransactionOptions): Promise { await super.signAndSendTransaction({ receiverId, actions }); @@ -62,6 +67,11 @@ export class Account2FA extends AccountMultisig { // default helpers for CH deployments of multisig + /** + * Deploy a multisig contract with 2FA and handle the deployment process. + * @param contractBytes - The bytecode of the multisig contract. + * @returns {Promise} A promise that resolves to the final execution outcome of the deployment. + */ async deployMultisig(contractBytes: Uint8Array) { const { accountId } = this; @@ -100,6 +110,13 @@ export class Account2FA extends AccountMultisig { } } + /** + * Disable 2FA with the option to clean up contract state. + * @param options Options for disabling 2FA. + * @param options.contractBytes The bytecode of the contract to deploy. + * @param options.cleanupContractBytes The bytecode of the cleanup contract (optional). + * @returns {Promise} A promise that resolves to the final execution outcome of the operation. + */ async disableWithFAK({ contractBytes, cleanupContractBytes }: { contractBytes: Uint8Array; cleanupContractBytes?: Uint8Array }) { let cleanupActions = []; if(cleanupContractBytes) { @@ -123,6 +140,11 @@ export class Account2FA extends AccountMultisig { return this.signAndSendTransactionWithAccount(this.accountId, actions); } + /** + * Retrieves cleanup actions for disabling 2FA. + * @param cleanupContractBytes - The bytecode of the cleanup contract. + * @returns {Promise} - A promise that resolves to an array of cleanup actions. + */ async get2faDisableCleanupActions(cleanupContractBytes: Uint8Array) { const currentAccountState: { key: Buffer; value: Buffer }[] = await this.viewState('').catch(error => { const cause = error.cause && error.cause.name; @@ -141,6 +163,10 @@ export class Account2FA extends AccountMultisig { ] : []; } + /** + * Retrieves key conversion actions for disabling 2FA. + * @returns {Promise} - A promise that resolves to an array of key conversion actions. + */ async get2faDisableKeyConversionActions() { const { accountId } = this; const accessKeys = await this.getAccessKeys(); @@ -163,7 +189,8 @@ export class Account2FA extends AccountMultisig { /** * This method converts LAKs back to FAKs, clears state and deploys an 'empty' contract (contractBytes param) * @param [contractBytes]{@link https://github.com/near/near-wallet/blob/master/packages/frontend/src/wasm/main.wasm?raw=true} - * @param [cleanupContractBytes]{@link https://github.com/near/core-contracts/blob/master/state-cleanup/res/state_cleanup.wasm?raw=true} + * @param [cleanupContractBytes]{@link https://github.com/near/core-contracts/blob/master/state-manipulation/res/state_cleanup.wasm?raw=true} + * @returns {Promise} A promise that resolves to the final execution outcome of the operation. */ async disable(contractBytes: Uint8Array, cleanupContractBytes: Uint8Array) { const { stateStatus } = await this.checkMultisigCodeAndStateStatus(); @@ -193,6 +220,10 @@ export class Account2FA extends AccountMultisig { }); } + /** + * Default implementation for sending the 2FA code. + * @returns {Promise} - A promise that resolves to the request ID. + */ async sendCodeDefault() { const { accountId } = this; const { requestId } = this.getRequest(); @@ -209,6 +240,10 @@ export class Account2FA extends AccountMultisig { throw new Error('There is no getCode callback provided. Please provide your own in AccountMultisig constructor options. It has a parameter method where method.kind is "email" or "phone".'); } + /** + * Prompts the user to enter and verify the 2FA code. + * @returns {Promise} - A promise that resolves to the verification result. + */ async promptAndVerify() { const method = await this.get2faMethod(); const securityCode = await this.getCode(method); @@ -227,6 +262,11 @@ export class Account2FA extends AccountMultisig { } } + /** + * Verify the 2FA code using the default method. + * @param securityCode - The security code to verify. + * @returns {Promise} A promise that resolves to the verification result. + */ async verifyCodeDefault(securityCode: string) { const { accountId } = this; const request = this.getRequest(); @@ -241,6 +281,10 @@ export class Account2FA extends AccountMultisig { }); } + /** + * Retrieves recovery methods for the account. + * @returns {Promise<{ accountId: string, data: any }>} - A promise that resolves to recovery methods data. + */ async getRecoveryMethods() { const { accountId } = this; return { @@ -249,6 +293,10 @@ export class Account2FA extends AccountMultisig { }; } + /** + * Gets the 2FA method (kind and detail). + * @returns {Promise<{ kind: string, detail: string } | null>} - A promise that resolves to the 2FA method. + */ async get2faMethod() { let { data } = await this.getRecoveryMethods(); if (data && data.length) { @@ -259,6 +307,10 @@ export class Account2FA extends AccountMultisig { return { kind, detail }; } + /** + * Generates a signature for the current block number. + * @returns {Promise<{ blockNumber: string, blockNumberSignature: string }>} - A promise that resolves to the signature information. + */ async signatureFor() { const { accountId } = this; const block = await this.connection.provider.block({ finality: 'final' }); @@ -268,6 +320,12 @@ export class Account2FA extends AccountMultisig { return { blockNumber, blockNumberSignature }; } + /** + * Sends a signed JSON request to a specified path. + * @param path - The path for the request. + * @param body - The request body. + * @returns {Promise} - A promise that resolves to the response from the helper. + */ async postSignedJson(path, body) { return await fetchJson(this.helperUrl + path, JSON.stringify({ ...body, diff --git a/packages/accounts/src/account_multisig.ts b/packages/accounts/src/account_multisig.ts index c159b4b70c..a7d92a5486 100644 --- a/packages/accounts/src/account_multisig.ts +++ b/packages/accounts/src/account_multisig.ts @@ -30,16 +30,37 @@ export class AccountMultisig extends Account { public storage: any; public onAddRequestResult: (any) => any; + /** + * Constructs an instance of the `AccountMultisig` class. + * @param connection The NEAR connection object. + * @param accountId The NEAR account ID. + * @param options Additional options for the multisig account. + * @param options.storage Storage to store data related to multisig operations. + * @param options.onAddRequestResult Callback function to handle the result of adding a request. + */ constructor(connection: Connection, accountId: string, options: any) { super(connection, accountId); this.storage = options.storage; this.onAddRequestResult = options.onAddRequestResult; } + /** + * Sign and send a transaction with the multisig account as the sender. + * @param receiverId - The NEAR account ID of the transaction receiver. + * @param actions - The list of actions to be included in the transaction. + * @returns {Promise} A promise that resolves to the final execution outcome of the transaction. + */ async signAndSendTransactionWithAccount(receiverId: string, actions: Action[]): Promise { return super.signAndSendTransaction({ receiverId, actions }); } + /** + * Sign and send a multisig transaction to add a request and confirm it. + * @param options Options for the multisig transaction. + * @param options.receiverId The NEAR account ID of the transaction receiver. + * @param options.actions The list of actions to be included in the transaction. + * @returns {Promise} A promise that resolves to the final execution outcome of the transaction. + */ async signAndSendTransaction({ receiverId, actions }: SignAndSendTransactionOptions): Promise { const { accountId } = this; @@ -91,10 +112,12 @@ export class AccountMultisig extends Account { return result; } - /* + /** * This method submits a canary transaction that is expected to always fail in order to determine whether the contract currently has valid multisig state * and whether it is initialized. The canary transaction attempts to delete a request at index u32_max and will go through if a request exists at that index. * a u32_max + 1 and -1 value cannot be used for the canary due to expected u32 error thrown before deserialization attempt. + * @param contractBytes The bytecode of the multisig contract. + * @returns {Promise<{ codeStatus: MultisigCodeStatus; stateStatus: MultisigStateStatus }>} A promise that resolves to the status of the code and state. */ async checkMultisigCodeAndStateStatus(contractBytes?: Uint8Array): Promise<{ codeStatus: MultisigCodeStatus; stateStatus: MultisigStateStatus }> { const u32_max = 4_294_967_295; @@ -128,6 +151,11 @@ export class AccountMultisig extends Account { } } + /** + * Delete a multisig request by its ID. + * @param request_id The ID of the multisig request to be deleted. + * @returns {Promise} A promise that resolves to the final execution outcome of the deletion. + */ deleteRequest(request_id) { return super.signAndSendTransaction({ receiverId: this.accountId, @@ -135,6 +163,10 @@ export class AccountMultisig extends Account { }); } + /** + * Delete all multisig requests associated with the account. + * @returns {Promise} A promise that resolves when all requests are deleted. + */ async deleteAllRequests() { const request_ids = await this.getRequestIds(); if(request_ids.length) { @@ -142,6 +174,10 @@ export class AccountMultisig extends Account { } } + /** + * Delete unconfirmed multisig requests associated with the account. + * @returns {Promise} A promise that resolves when unconfirmed requests are deleted. + */ async deleteUnconfirmedRequests () { // TODO: Delete in batch, don't delete unexpired // TODO: Delete in batch, don't delete unexpired (can reduce gas usage dramatically) diff --git a/packages/accounts/src/local-view-execution/index.ts b/packages/accounts/src/local-view-execution/index.ts index d231c9a408..66af734a00 100644 --- a/packages/accounts/src/local-view-execution/index.ts +++ b/packages/accounts/src/local-view-execution/index.ts @@ -64,6 +64,15 @@ export class LocalViewExecution { return fetched; } + /** + * Calls a view function on a contract, fetching the contract code and state if needed. + * @param options Options for calling the view function. + * @param options.contractId The contract account ID. + * @param options.methodName The name of the view function to call. + * @param options.args The arguments to pass to the view function. + * @param options.blockQuery The block query options. + * @returns {Promise} - A promise that resolves to the result of the view function. + */ public async viewFunction({ contractId, methodName, args = {}, blockQuery = { finality: 'optimistic' }, ...ignored }: ViewFunctionCallOptions) { const methodArgs = JSON.stringify(args); diff --git a/packages/biometric-ed25519/src/index.ts b/packages/biometric-ed25519/src/index.ts index 5dbd96acac..3ffc8cfead 100644 --- a/packages/biometric-ed25519/src/index.ts +++ b/packages/biometric-ed25519/src/index.ts @@ -106,8 +106,8 @@ export const getKeys = async (username: string): Promise<[KeyPair, KeyPair]> => Buffer.from(new Uint8Array(base64.toArrayBuffer(getAssertionResponse.response.clientDataJSON, true))) ); const clientDataJSONHash = await clientDataSha256.digest(); - const AuthenticatiorDataJSONHash = Buffer.from(new Uint8Array(base64.toArrayBuffer(getAssertionResponse.response.authenticatorData, true))); - const authenticatorAndClientDataJSONHash = Buffer.concat([AuthenticatiorDataJSONHash, clientDataJSONHash]); + const AuthenticatorDataJSONHash = Buffer.from(new Uint8Array(base64.toArrayBuffer(getAssertionResponse.response.authenticatorData, true))); + const authenticatorAndClientDataJSONHash = Buffer.concat([AuthenticatorDataJSONHash, clientDataJSONHash]); const correctPKs = await recoverPublicKey(rAndS.children[0].value, rAndS.children[1].value, authenticatorAndClientDataJSONHash, 0); diff --git a/packages/crypto/src/key_pair.ts b/packages/crypto/src/key_pair.ts index d02790a156..fb5d5ca59f 100644 --- a/packages/crypto/src/key_pair.ts +++ b/packages/crypto/src/key_pair.ts @@ -13,6 +13,11 @@ export abstract class KeyPair extends KeyPairBase { } } + /** + * Creates a key pair from an encoded key string. + * @param encodedKey The encoded key string. + * @returns {KeyPair} The key pair created from the encoded key string. + */ static fromString(encodedKey: string): KeyPair { const parts = encodedKey.split(':'); if (parts.length === 1) { diff --git a/packages/crypto/src/key_pair_ed25519.ts b/packages/crypto/src/key_pair_ed25519.ts index 3047cfc4fd..6462c87692 100644 --- a/packages/crypto/src/key_pair_ed25519.ts +++ b/packages/crypto/src/key_pair_ed25519.ts @@ -18,7 +18,7 @@ export class KeyPairEd25519 extends KeyPairBase { /** * Construct an instance of key pair given a secret key. * It's generally assumed that these are encoded in base58. - * @param {string} extendedSecretKey + * @param extendedSecretKey */ constructor(extendedSecretKey: string) { super(); @@ -47,19 +47,38 @@ export class KeyPairEd25519 extends KeyPairBase { return new KeyPairEd25519(baseEncode(extendedSecretKey)); } + /** + * Signs a message using the key pair's secret key. + * @param message The message to be signed. + * @returns {Signature} The signature object containing the signature and the public key. + */ sign(message: Uint8Array): Signature { const signature = ed25519.sign(message, baseDecode(this.secretKey)); return { signature, publicKey: this.publicKey }; } + /** + * Verifies the signature of a message using the key pair's public key. + * @param message The message to be verified. + * @param signature The signature to be verified. + * @returns {boolean} `true` if the signature is valid, otherwise `false`. + */ verify(message: Uint8Array, signature: Uint8Array): boolean { return this.publicKey.verify(message, signature); } + /** + * Returns a string representation of the key pair in the format 'ed25519:[extendedSecretKey]'. + * @returns {string} The string representation of the key pair. + */ toString(): string { return `ed25519:${this.extendedSecretKey}`; } + /** + * Retrieves the public key associated with the key pair. + * @returns {PublicKey} The public key. + */ getPublicKey(): PublicKey { return this.publicKey; } diff --git a/packages/crypto/src/public_key.ts b/packages/crypto/src/public_key.ts index 0959cd4d6e..8b06dd8663 100644 --- a/packages/crypto/src/public_key.ts +++ b/packages/crypto/src/public_key.ts @@ -25,6 +25,11 @@ export class PublicKey extends Assignable { keyType: KeyType; data: Uint8Array; + /** + * Creates a PublicKey instance from a string or an existing PublicKey instance. + * @param value The string or PublicKey instance to create a PublicKey from. + * @returns {PublicKey} The PublicKey instance. + */ static from(value: string | PublicKey): PublicKey { if (typeof value === 'string') { return PublicKey.fromString(value); @@ -32,6 +37,11 @@ export class PublicKey extends Assignable { return value; } + /** + * Creates a PublicKey instance from an encoded key string. + * @param encodedKey The encoded key string. + * @returns {PublicKey} The PublicKey instance created from the encoded key string. + */ static fromString(encodedKey: string): PublicKey { const parts = encodedKey.split(':'); let publicKey: string; @@ -51,10 +61,20 @@ export class PublicKey extends Assignable { return new PublicKey({ keyType, data: decodedPublicKey }); } + /** + * Returns a string representation of the public key. + * @returns {string} The string representation of the public key. + */ toString(): string { return `${key_type_to_str(this.keyType)}:${baseEncode(this.data)}`; } + /** + * Verifies a message signature using the public key. + * @param message The message to be verified. + * @param signature The signature to be verified. + * @returns {boolean} `true` if the signature is valid, otherwise `false`. + */ verify(message: Uint8Array, signature: Uint8Array): boolean { switch (this.keyType) { case KeyType.ED25519: return ed25519.verify(signature, message, this.data); diff --git a/packages/iframe-rpc/src/iframe-rpc.ts b/packages/iframe-rpc/src/iframe-rpc.ts index 5d466b93cd..e97bfcfcd3 100644 --- a/packages/iframe-rpc/src/iframe-rpc.ts +++ b/packages/iframe-rpc/src/iframe-rpc.ts @@ -35,6 +35,10 @@ export class IFrameRPC extends EventEmitter { private remoteProtocolVersion: string | undefined; private readonly removeMessageListener: () => void; + /** + * Creates an instance of IFrameRPC. + * @param options The configuration options for IFrameRPC. + */ constructor(private readonly options: IRPCOptions) { super(); this.removeMessageListener = (options.receiver || windowReceiver).readMessages(this.messageEventListener); @@ -57,11 +61,22 @@ export class IFrameRPC extends EventEmitter { }); } + /** + * Static method to get a ready instance of IFrameRPC based on the provided options. + * @param options The configuration options for IFrameRPC. + * @returns A Promise that resolves to the ready IFrameRPC instance. + */ static getReadyInstance(options: IRPCOptions): Promise { const rpc = new IFrameRPC(options); return rpc.isReady.then(() => rpc); } + /** + * Binds a method handler for the specified RPC method. + * @param method The RPC method name. + * @param handler The method handler function. + * @returns The current IFrameRPC instance. + */ public bindMethodHandler(method: string, handler: (params: T) => Promise | any): this { this.on(method, (data: IRPCMethod) => { new Promise(resolve => resolve(handler(data.params))) @@ -89,6 +104,12 @@ export class IFrameRPC extends EventEmitter { return this; } + /** + * Calls an RPC method with the specified method name and parameters. + * @param method The RPC method name. + * @param params The parameters for the RPC method. + * @returns A Promise that resolves with the result of the RPC method. + */ public callMethod(method: string, params: object): Promise { const id = method === 'ready' ? readyId : this.lastCallId; const message: IRPCMethod = { @@ -113,11 +134,18 @@ export class IFrameRPC extends EventEmitter { }); } + /** + * Destroys the IFrameRPC instance, removing event listeners. + */ public destroy() { this.emit('destroy'); this.removeMessageListener(); } + /** + * Retrieves the remote protocol version. + * @returns The remote protocol version. + */ public remoteVersion(): string | undefined { return this.remoteProtocolVersion; } diff --git a/packages/keystores-browser/src/browser_local_storage_key_store.ts b/packages/keystores-browser/src/browser_local_storage_key_store.ts index 9472b183b3..e72e6cf6ed 100644 --- a/packages/keystores-browser/src/browser_local_storage_key_store.ts +++ b/packages/keystores-browser/src/browser_local_storage_key_store.ts @@ -121,7 +121,7 @@ export class BrowserLocalStorageKeyStore extends KeyStore { * @hidden * Helper function to retrieve a local storage key * @param networkId The targeted network. (ex. default, betanet, etc…) - * @param accountId The NEAR account tied to the storage keythat's sought + * @param accountId The NEAR account tied to the storage key that's sought * @returns {string} An example might be: `near-api-js:keystore:near-friend:default` */ private storageKeyForSecretKey(networkId: string, accountId: string): string { diff --git a/packages/near-api-js/src/connect.ts b/packages/near-api-js/src/connect.ts index 64777da84e..dada230405 100644 --- a/packages/near-api-js/src/connect.ts +++ b/packages/near-api-js/src/connect.ts @@ -45,6 +45,26 @@ export interface ConnectConfig extends NearConfig { /** * Initialize connection to Near network. + * @param config The configuration object for connecting to NEAR Protocol. + * @returns A Promise that resolves to a `Near` object representing the connection. + * + * @example + * ```js + * const connectionConfig = { + * networkId: 'testnet', + * nodeUrl: 'https://rpc.testnet.near.org', + * walletUrl: 'https://wallet.testnet.near.org', + * helperUrl: 'https://helper.testnet.near.org', + * keyStore: new InMemoryKeyStore(), + * deps: { keyStore: new BrowserLocalStorageKeyStore() }, + * logger: true, + * keyPath: '/path/to/account-key.json', + * masterAccount: 'master-account.near', + * }; + * + * const nearConnection = await connect(connectionConfig); + * console.log(nearConnection); // Near object representing the connection + * ``` */ export async function connect(config: ConnectConfig): Promise { if (config.logger === false) { diff --git a/packages/providers/src/fetch_json.ts b/packages/providers/src/fetch_json.ts index 1e8836f1eb..376767eeab 100644 --- a/packages/providers/src/fetch_json.ts +++ b/packages/providers/src/fetch_json.ts @@ -17,6 +17,12 @@ export interface ConnectionInfo { headers?: { [key: string]: string | number }; } +/** + * Performs an HTTP request to a specified URL or connection and returns the parsed JSON response. + * @param connectionInfoOrUrl The connection information or URL for the HTTP request. + * @param json The JSON payload to be included in the request body for POST requests. + * @returns A Promise that resolves to the parsed JSON response from the HTTP request. + */ export async function fetchJson(connectionInfoOrUrl: string | ConnectionInfo, json?: string): Promise { let connectionInfo: ConnectionInfo = { url: null }; if (typeof (connectionInfoOrUrl) === 'string') { diff --git a/packages/signers/src/in_memory_signer.ts b/packages/signers/src/in_memory_signer.ts index 5c0797b5bf..273b79d4f7 100644 --- a/packages/signers/src/in_memory_signer.ts +++ b/packages/signers/src/in_memory_signer.ts @@ -1,5 +1,5 @@ import { KeyPair, PublicKey, Signature } from '@near-js/crypto'; -import { InMemoryKeyStore, KeyStore } from '@near-js/keystores' +import { InMemoryKeyStore, KeyStore } from '@near-js/keystores'; import { sha256 } from '@noble/hashes/sha256'; import { Signer } from './signer'; diff --git a/packages/signers/src/signer.ts b/packages/signers/src/signer.ts index d5d5ae670e..97ec749ffa 100644 --- a/packages/signers/src/signer.ts +++ b/packages/signers/src/signer.ts @@ -7,6 +7,8 @@ export abstract class Signer { /** * Creates new key and returns public key. + * @param accountId accountId to retrieve from. + * @param networkId The targeted network. (ex. default, betanet, etc…) */ abstract createKey(accountId: string, networkId?: string): Promise; diff --git a/packages/transactions/src/action_creators.ts b/packages/transactions/src/action_creators.ts index 6f5ee1f36a..7853bde0e5 100644 --- a/packages/transactions/src/action_creators.ts +++ b/packages/transactions/src/action_creators.ts @@ -20,6 +20,10 @@ import { import { DelegateAction } from './delegate'; import { Signature } from './signature'; +/** + * Creates a full access key with all permissions. + * @returns A new access key with full access permission. + */ function fullAccessKey(): AccessKey { return new AccessKey({ nonce: 0, @@ -28,7 +32,13 @@ function fullAccessKey(): AccessKey { }) }); } - +/** + * Creates an access key with function call permission for a specific receiver and method names. + * @param receiverId The NEAR account ID of the function call receiver. + * @param methodNames An array of method names allowed for function calls. + * @param allowance An optional allowance (maximum amount) for the function call. Default: Unlimited. + * @returns A new access key with function call permission. + */ function functionCallAccessKey(receiverId: string, methodNames: string[], allowance?: BN): AccessKey { return new AccessKey({ nonce: 0, @@ -38,14 +48,28 @@ function functionCallAccessKey(receiverId: string, methodNames: string[], allowa }); } +/** + * Creates a new action for creating a new NEAR account. + * @returns A new action for creating a new account. + */ function createAccount(): Action { return new Action({ createAccount: new CreateAccount({}) }); } +/** + * Creates a new action for deploying a contract with the provided code. + * @param code The Uint8Array representing the code of the contract. + * @returns A new action for deploying a contract. + */ function deployContract(code: Uint8Array): Action { return new Action({ deployContract: new DeployContract({ code }) }); } +/** + * Converts an input argument to a Buffer, handling cases for both JSON and Uint8Array. + * @param args The input argument, either JSON object or Uint8Array. + * @returns A Buffer representation of the input argument. + */ export function stringifyJsonOrBytes(args: any): Buffer { const isUint8Array = args.byteLength !== undefined && args.byteLength === args.length; return isUint8Array ? args : Buffer.from(JSON.stringify(args)); @@ -77,26 +101,59 @@ function functionCall(methodName: string, args: Uint8Array | object, gas: BN = n }); } +/** + * Creates a new action for transferring funds, optionally specifying a deposit amount. + * @param deposit The amount to be deposited along with the transfer. Default: 0. + * @returns A new action for transferring funds. + */ function transfer(deposit: BN = new BN(0)): Action { return new Action({ transfer: new Transfer({ deposit }) }); } +/** + * Creates a new action for staking tokens, specifying the stake amount and public key. + * @param stake The amount to be staked. Default: 0. + * @param publicKey The public key associated with the staking action. + * @returns A new action for staking tokens. + */ function stake(stake: BN = new BN(0), publicKey: PublicKey): Action { return new Action({ stake: new Stake({ stake, publicKey }) }); } +/** + * Creates a new action for adding a public key with a specified access key. + * @param publicKey The public key to be added. + * @param accessKey The access key associated with the added public key. + * @returns A new action for adding a public key. + */ function addKey(publicKey: PublicKey, accessKey: AccessKey): Action { return new Action({ addKey: new AddKey({ publicKey, accessKey }) }); } +/** + * Creates a new action for deleting a public key. + * @param publicKey The public key to be deleted. + * @returns A new action for deleting a public key. + */ function deleteKey(publicKey: PublicKey): Action { return new Action({ deleteKey: new DeleteKey({ publicKey }) }); } +/** + * Creates a new action for deleting an account with the specified beneficiary ID. + * @param beneficiaryId The NEAR account ID of the beneficiary. + * @returns A new action for deleting an account. + */ function deleteAccount(beneficiaryId: string): Action { return new Action({ deleteAccount: new DeleteAccount({ beneficiaryId }) }); } +/** + * Creates a new action for a signed delegation, specifying the delegate action and signature. + * @param delegateAction The delegate action to be performed. + * @param signature The signature associated with the delegate action. + * @returns A new action for a signed delegation. + */ function signedDelegate({ delegateAction, signature }: { delegateAction: DelegateAction, signature: Signature }): Action { return new Action({ signedDelegate: new SignedDelegate({ delegateAction, signature }) }); } diff --git a/packages/transactions/src/create_transaction.ts b/packages/transactions/src/create_transaction.ts index 5d5d1198af..5da87aa248 100644 --- a/packages/transactions/src/create_transaction.ts +++ b/packages/transactions/src/create_transaction.ts @@ -4,6 +4,16 @@ import BN from 'bn.js'; import { Action } from './actions'; import { Transaction } from './schema'; +/** + * Creates a new transaction object with the provided parameters. + * @param signerId The NEAR account ID of the transaction signer. + * @param publicKey The public key associated with the signer. + * @param receiverId The NEAR account ID of the transaction receiver. + * @param nonce The nonce value for the transaction, represented as a BN, string, or number. + * @param actions An array of transaction actions to be performed. + * @param blockHash The hash of the block where the transaction will be included. + * @returns A new transaction object initialized with the provided parameters. + */ export function createTransaction(signerId: string, publicKey: PublicKey, receiverId: string, nonce: BN | string | number, actions: Action[], blockHash: Uint8Array): Transaction { return new Transaction({ signerId, publicKey, nonce: new BN(nonce), receiverId, actions, blockHash }); } diff --git a/packages/transactions/src/delegate.ts b/packages/transactions/src/delegate.ts index de6768f841..c25db66427 100644 --- a/packages/transactions/src/delegate.ts +++ b/packages/transactions/src/delegate.ts @@ -27,12 +27,12 @@ export class DelegateAction extends Assignable { /** * Compose a delegate action for inclusion with a meta transaction signed on the sender's behalf - * @params.actions The set of actions to be included in the meta transaction - * @params.maxBlockHeight The maximum block height for which this action can be executed as part of a transaction - * @params.nonce Current nonce on the access key used to sign the delegate action - * @params.publicKey Public key for the access key used to sign the delegate action - * @params.receiverId Account ID for the intended receiver of the meta transaction - * @params.senderId Account ID for the intended signer of the delegate action + * @param actions The set of actions to be included in the meta transaction + * @param maxBlockHeight The maximum block height for which this action can be executed as part of a transaction + * @param nonce Current nonce on the access key used to sign the delegate action + * @param publicKey Public key for the access key used to sign the delegate action + * @param receiverId Account ID for the intended receiver of the meta transaction + * @param senderId Account ID for the intended signer of the delegate action */ export function buildDelegateAction({ actions, diff --git a/packages/transactions/src/schema.ts b/packages/transactions/src/schema.ts index 39690ae92b..378934e0bd 100644 --- a/packages/transactions/src/schema.ts +++ b/packages/transactions/src/schema.ts @@ -32,6 +32,11 @@ export function encodeSignedDelegate(signedDelegate: SignedDelegate) { return serialize(SCHEMA.SignedDelegate, signedDelegate); } +/** * +* Borsh-encode a transaction or signed transaction into a serialized form. +* @param transaction The transaction or signed transaction object to be encoded. +* @returns A serialized representation of the input transaction. +*/ export function encodeTransaction(transaction: Transaction | SignedTransaction) { const schema: Schema = transaction instanceof SignedTransaction ? SCHEMA.SignedTransaction : SCHEMA.Transaction; return serialize(schema, transaction); diff --git a/packages/transactions/src/sign.ts b/packages/transactions/src/sign.ts index 0c2cc4422b..23719f2314 100644 --- a/packages/transactions/src/sign.ts +++ b/packages/transactions/src/sign.ts @@ -56,8 +56,8 @@ export async function signTransaction(...args): Promise<[Uint8Array, SignedTrans /** * Sign a delegate action - * @params.delegateAction Delegate action to be signed by the meta transaction sender - * @params.signer Signer instance for the meta transaction sender + * @param delegateAction Delegate action to be signed by the meta transaction sender + * @param signer Signer instance for the meta transaction sender */ export async function signDelegateAction({ delegateAction, signer }: SignDelegateOptions): Promise { const message = encodeDelegateAction(delegateAction); diff --git a/packages/utils/src/errors/errors.ts b/packages/utils/src/errors/errors.ts index c13d04657b..474e4cfac3 100644 --- a/packages/utils/src/errors/errors.ts +++ b/packages/utils/src/errors/errors.ts @@ -2,6 +2,6 @@ import { Logger } from '../logger'; /** @deprecated */ export function logWarning(...args: any[]): void { - const [message, ...optinalParams] = args; - Logger.warn(message, ...optinalParams); + const [message, ...optionalParams] = args; + Logger.warn(message, ...optionalParams); } diff --git a/packages/utils/src/format.ts b/packages/utils/src/format.ts index 1013c332fb..1f718d6819 100644 --- a/packages/utils/src/format.ts +++ b/packages/utils/src/format.ts @@ -11,7 +11,7 @@ export const NEAR_NOMINATION_EXP = 24; */ export const NEAR_NOMINATION = new BN('10', 10).pow(new BN(NEAR_NOMINATION_EXP, 10)); -// Pre-calculate offests used for rounding to different number of digits +// Pre-calculate offsets used for rounding to different number of digits const ROUNDING_OFFSETS: BN[] = []; const BN10 = new BN(10); for (let i = 0, offset = new BN(5); i < NEAR_NOMINATION_EXP; i++, offset = offset.mul(BN10)) { diff --git a/packages/utils/src/validators.ts b/packages/utils/src/validators.ts index 30cdf63a1e..7dac43ffce 100644 --- a/packages/utils/src/validators.ts +++ b/packages/utils/src/validators.ts @@ -4,10 +4,10 @@ import depd from 'depd'; /** Finds seat price given validators stakes and number of seats. * Calculation follow the spec: https://nomicon.io/Economics/README.html#validator-selection - * @params validators: current or next epoch validators. - * @params maxNumberOfSeats: maximum number of seats in the network. - * @params minimumStakeRatio: minimum stake ratio - * @params protocolVersion: version of the protocol from genesis config + * @param validators: current or next epoch validators. + * @param maxNumberOfSeats: maximum number of seats in the network. + * @param minimumStakeRatio: minimum stake ratio + * @param protocolVersion: version of the protocol from genesis config */ export function findSeatPrice(validators: (CurrentEpochValidatorInfo | NextEpochValidatorInfo)[], maxNumberOfSeats: number, minimumStakeRatio: number[], protocolVersion?: number): BN { if (protocolVersion && protocolVersion < 49) { @@ -16,7 +16,7 @@ export function findSeatPrice(validators: (CurrentEpochValidatorInfo | NextEpoch if (!minimumStakeRatio) { const deprecate = depd('findSeatPrice(validators, maxNumberOfSeats)'); deprecate('`use `findSeatPrice(validators, maxNumberOfSeats, minimumStakeRatio)` instead'); - minimumStakeRatio = [1, 6250]; // harcoded minimumStakeRation from 12/7/21 + minimumStakeRatio = [1, 6250]; // hardcoded minimumStakeRation from 12/7/21 } return findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio); } @@ -76,8 +76,8 @@ export interface EpochValidatorsDiff { /** Diff validators between current and next epoch. * Returns additions, subtractions and changes to validator set. - * @params currentValidators: list of current validators. - * @params nextValidators: list of next validators. + * @param currentValidators: list of current validators. + * @param nextValidators: list of next validators. */ export function diffEpochValidators(currentValidators: CurrentEpochValidatorInfo[], nextValidators: NextEpochValidatorInfo[]): EpochValidatorsDiff { const validatorsMap = new Map(); diff --git a/packages/wallet-account/src/wallet_account.ts b/packages/wallet-account/src/wallet_account.ts index dfd7126dd9..d278f61308 100644 --- a/packages/wallet-account/src/wallet_account.ts +++ b/packages/wallet-account/src/wallet_account.ts @@ -207,6 +207,10 @@ export class WalletConnection { /** * Requests the user to quickly sign for a transaction or batch of transactions by redirecting to the NEAR wallet. + * @param options + * @param options.transactions An array of transactions to be signed. + * @param options.meta Additional metadata to be included in the signing request. + * @param options.callbackUrl URL to redirect upon completion. Default: current URL. */ async requestSignTransactions({ transactions, meta, callbackUrl }: RequestSignTransactionsOptions): Promise { const currentUrl = new URL(window.location.href); @@ -300,6 +304,10 @@ export class ConnectedWalletAccount extends Account { /** * Sign a transaction by redirecting to the NEAR Wallet * @see {@link WalletConnection#requestSignTransactions} + * @param receiverId The NEAR account ID of the transaction receiver. + * @param actions An array of transaction actions to be performed. + * @param walletMeta Additional metadata to be included in the wallet signing request. + * @param walletCallbackUrl URL to redirect upon completion of the wallet signing process. Default: current URL. */ async signAndSendTransaction({ receiverId, actions, walletMeta, walletCallbackUrl = window.location.href }: SignAndSendTransactionOptions): Promise { const localKey = await this.connection.signer.getPublicKey(this.accountId, this.connection.networkId); From ee0eb780224b2328a024784222b18844c3924256 Mon Sep 17 00:00:00 2001 From: Georgi Tsonev Date: Fri, 19 Jan 2024 12:30:59 +0200 Subject: [PATCH 2/2] chore: add missing functions docs --- packages/accounts/src/account.ts | 22 ++++++++++--------- packages/accounts/src/account_2fa.ts | 4 ++-- packages/biometric-ed25519/src/index.ts | 4 ++-- packages/keystores/src/merge_key_store.ts | 1 + packages/transactions/src/action_creators.ts | 4 ++-- packages/transactions/src/schema.ts | 2 +- packages/transactions/src/sign.ts | 5 +++-- packages/wallet-account/src/wallet_account.ts | 11 +++++----- 8 files changed, 29 insertions(+), 24 deletions(-) diff --git a/packages/accounts/src/account.ts b/packages/accounts/src/account.ts index d851dacfac..989ae1daf3 100644 --- a/packages/accounts/src/account.ts +++ b/packages/accounts/src/account.ts @@ -477,9 +477,10 @@ export class Account { /** * Compose and sign a SignedDelegate action to be executed in a transaction on behalf of this Account instance * - * @param actions Actions to be included in the meta transaction - * @param blockHeightTtl Number of blocks past the current block height for which the SignedDelegate action may be included in a meta transaction - * @param receiverId Receiver account of the meta transaction + * @param options Options for the transaction. + * @param options.actions Actions to be included in the meta transaction + * @param options.blockHeightTtl Number of blocks past the current block height for which the SignedDelegate action may be included in a meta transaction + * @param options.receiverId Receiver account of the meta transaction */ async signedDelegate({ actions, @@ -533,13 +534,14 @@ export class Account { * Invoke a contract view function using the RPC API. * @see [https://docs.near.org/api/rpc/contracts#call-a-contract-function](https://docs.near.org/api/rpc/contracts#call-a-contract-function) * - * @param viewFunctionCallOptions.contractId NEAR account where the contract is deployed - * @param viewFunctionCallOptions.methodName The view-only method (no state mutations) name on the contract as it is written in the contract code - * @param viewFunctionCallOptions.args Any arguments to the view contract method, wrapped in JSON - * @param viewFunctionCallOptions.parse Parse the result of the call. Receives a Buffer (bytes array) and converts it to any object. By default result will be treated as json. - * @param viewFunctionCallOptions.stringify Convert input arguments into a bytes array. By default the input is treated as a JSON. - * @param viewFunctionCallOptions.jsContract Is contract from JS SDK, automatically encodes args from JS SDK to binary. - * @param viewFunctionCallOptions.blockQuery specifies which block to query state at. By default returns last "optimistic" block (i.e. not necessarily finalized). + * @param options Function call options. + * @param options.contractId NEAR account where the contract is deployed + * @param options.methodName The view-only method (no state mutations) name on the contract as it is written in the contract code + * @param options.args Any arguments to the view contract method, wrapped in JSON + * @param options.parse Parse the result of the call. Receives a Buffer (bytes array) and converts it to any object. By default result will be treated as json. + * @param options.stringify Convert input arguments into a bytes array. By default the input is treated as a JSON. + * @param options.jsContract Is contract from JS SDK, automatically encodes args from JS SDK to binary. + * @param options.blockQuery specifies which block to query state at. By default returns last "optimistic" block (i.e. not necessarily finalized). * @returns {Promise} */ diff --git a/packages/accounts/src/account_2fa.ts b/packages/accounts/src/account_2fa.ts index c9ab09aa5c..c22e664a0d 100644 --- a/packages/accounts/src/account_2fa.ts +++ b/packages/accounts/src/account_2fa.ts @@ -295,7 +295,7 @@ export class Account2FA extends AccountMultisig { /** * Gets the 2FA method (kind and detail). - * @returns {Promise<{ kind: string, detail: string } | null>} - A promise that resolves to the 2FA method. + * @returns {Promise<{ kind: string, detail: string }>} A promise that resolves to the 2FA method. */ async get2faMethod() { let { data } = await this.getRecoveryMethods(); @@ -308,7 +308,7 @@ export class Account2FA extends AccountMultisig { } /** - * Generates a signature for the current block number. + * Generates a signature for the latest finalized block. * @returns {Promise<{ blockNumber: string, blockNumberSignature: string }>} - A promise that resolves to the signature information. */ async signatureFor() { diff --git a/packages/biometric-ed25519/src/index.ts b/packages/biometric-ed25519/src/index.ts index 3ffc8cfead..57b31af01e 100644 --- a/packages/biometric-ed25519/src/index.ts +++ b/packages/biometric-ed25519/src/index.ts @@ -106,8 +106,8 @@ export const getKeys = async (username: string): Promise<[KeyPair, KeyPair]> => Buffer.from(new Uint8Array(base64.toArrayBuffer(getAssertionResponse.response.clientDataJSON, true))) ); const clientDataJSONHash = await clientDataSha256.digest(); - const AuthenticatorDataJSONHash = Buffer.from(new Uint8Array(base64.toArrayBuffer(getAssertionResponse.response.authenticatorData, true))); - const authenticatorAndClientDataJSONHash = Buffer.concat([AuthenticatorDataJSONHash, clientDataJSONHash]); + const authenticatorDataJSONHash = Buffer.from(new Uint8Array(base64.toArrayBuffer(getAssertionResponse.response.authenticatorData, true))); + const authenticatorAndClientDataJSONHash = Buffer.concat([authenticatorDataJSONHash, clientDataJSONHash]); const correctPKs = await recoverPublicKey(rAndS.children[0].value, rAndS.children[1].value, authenticatorAndClientDataJSONHash, 0); diff --git a/packages/keystores/src/merge_key_store.ts b/packages/keystores/src/merge_key_store.ts index 2fc6227dc6..4caf4b20f2 100644 --- a/packages/keystores/src/merge_key_store.ts +++ b/packages/keystores/src/merge_key_store.ts @@ -45,6 +45,7 @@ export class MergeKeyStore extends KeyStore { /** * @param keyStores read calls are attempted from start to end of array + * @param options KeyStore options * @param options.writeKeyStoreIndex the keystore index that will receive all write calls */ constructor(keyStores: KeyStore[], options: MergeKeyStoreOptions = { writeKeyStoreIndex: 0 }) { diff --git a/packages/transactions/src/action_creators.ts b/packages/transactions/src/action_creators.ts index 7853bde0e5..021106b97b 100644 --- a/packages/transactions/src/action_creators.ts +++ b/packages/transactions/src/action_creators.ts @@ -21,8 +21,8 @@ import { DelegateAction } from './delegate'; import { Signature } from './signature'; /** - * Creates a full access key with all permissions. - * @returns A new access key with full access permission. + * Creates a full access key with full access permissions. + * @returns A new full access key. */ function fullAccessKey(): AccessKey { return new AccessKey({ diff --git a/packages/transactions/src/schema.ts b/packages/transactions/src/schema.ts index 378934e0bd..4f909a685f 100644 --- a/packages/transactions/src/schema.ts +++ b/packages/transactions/src/schema.ts @@ -32,7 +32,7 @@ export function encodeSignedDelegate(signedDelegate: SignedDelegate) { return serialize(SCHEMA.SignedDelegate, signedDelegate); } -/** * +/** * Borsh-encode a transaction or signed transaction into a serialized form. * @param transaction The transaction or signed transaction object to be encoded. * @returns A serialized representation of the input transaction. diff --git a/packages/transactions/src/sign.ts b/packages/transactions/src/sign.ts index 23719f2314..f84fc5a844 100644 --- a/packages/transactions/src/sign.ts +++ b/packages/transactions/src/sign.ts @@ -56,8 +56,9 @@ export async function signTransaction(...args): Promise<[Uint8Array, SignedTrans /** * Sign a delegate action - * @param delegateAction Delegate action to be signed by the meta transaction sender - * @param signer Signer instance for the meta transaction sender + * @options SignDelegate options + * @param options.delegateAction Delegate action to be signed by the meta transaction sender + * @param options.signer Signer instance for the meta transaction sender */ export async function signDelegateAction({ delegateAction, signer }: SignDelegateOptions): Promise { const message = encodeDelegateAction(delegateAction); diff --git a/packages/wallet-account/src/wallet_account.ts b/packages/wallet-account/src/wallet_account.ts index d278f61308..57f54a2e23 100644 --- a/packages/wallet-account/src/wallet_account.ts +++ b/packages/wallet-account/src/wallet_account.ts @@ -207,7 +207,7 @@ export class WalletConnection { /** * Requests the user to quickly sign for a transaction or batch of transactions by redirecting to the NEAR wallet. - * @param options + * @param options An optional options object * @param options.transactions An array of transactions to be signed. * @param options.meta Additional metadata to be included in the signing request. * @param options.callbackUrl URL to redirect upon completion. Default: current URL. @@ -304,10 +304,11 @@ export class ConnectedWalletAccount extends Account { /** * Sign a transaction by redirecting to the NEAR Wallet * @see {@link WalletConnection#requestSignTransactions} - * @param receiverId The NEAR account ID of the transaction receiver. - * @param actions An array of transaction actions to be performed. - * @param walletMeta Additional metadata to be included in the wallet signing request. - * @param walletCallbackUrl URL to redirect upon completion of the wallet signing process. Default: current URL. + * @param options An optional options object + * @param options.receiverId The NEAR account ID of the transaction receiver. + * @param options.actions An array of transaction actions to be performed. + * @param options.walletMeta Additional metadata to be included in the wallet signing request. + * @param options.walletCallbackUrl URL to redirect upon completion of the wallet signing process. Default: current URL. */ async signAndSendTransaction({ receiverId, actions, walletMeta, walletCallbackUrl = window.location.href }: SignAndSendTransactionOptions): Promise { const localKey = await this.connection.signer.getPublicKey(this.accountId, this.connection.networkId);