From b98011d4c290df1470c6f923a3a4e2d6469b3633 Mon Sep 17 00:00:00 2001 From: Ivan Krcatovic Date: Sat, 23 Mar 2024 21:58:40 +0000 Subject: [PATCH 1/8] docs: adding missing jsdocs on methods --- src/channel/rpc_0_6.ts | 192 ++++++++++++++++++++++++++ src/contract/interface.ts | 6 + src/provider/extensions/starknetId.ts | 59 ++++++++ src/signer/default.ts | 6 + src/signer/ethSigner.ts | 27 ++++ src/utils/address.ts | 9 +- src/utils/assert.ts | 6 + src/utils/calldata/cairo.ts | 109 +++++++++++++++ src/utils/calldata/formatter.ts | 8 ++ src/utils/calldata/propertyOrder.ts | 41 ++++++ src/utils/calldata/requestParser.ts | 6 + src/utils/calldata/responseParser.ts | 1 + src/utils/calldata/tuple.ts | 34 +++++ src/utils/calldata/validate.ts | 73 ++++++++++ src/utils/contract.ts | 15 ++ src/utils/events/index.ts | 7 + src/utils/hash/classHash.ts | 8 +- src/utils/provider.ts | 22 ++- src/utils/responseParser/rpc.ts | 48 +++++++ src/utils/stark.ts | 22 +++ src/utils/starknetId.ts | 84 ++++++++++- src/utils/transaction.ts | 8 ++ src/utils/typedData.ts | 13 ++ src/utils/url.ts | 8 ++ src/wallet/account.ts | 34 ++++- src/wallet/connect.ts | 26 +++- 26 files changed, 865 insertions(+), 7 deletions(-) diff --git a/src/channel/rpc_0_6.ts b/src/channel/rpc_0_6.ts index f89ce7eff..2281085b4 100644 --- a/src/channel/rpc_0_6.ts +++ b/src/channel/rpc_0_6.ts @@ -71,10 +71,26 @@ export class RpcChannel { this.requestId = 0; } + /** + * Sets the chain ID for the Starknet. + * + * @param {StarknetChainId} chainId - The chain ID to be set. + * + * @return + */ public setChainId(chainId: StarknetChainId) { this.chainId = chainId; } + /** + * Fetches data from a remote server using the provided method, parameters, and ID. + * + * @param {string} method - The method to be called on the remote server. + * @param {?object} params - Optional parameters to be passed to the remote server. + * @param {string|number} id - The ID to identify the request. Default value is 0. + * + * @return - A Promise that resolves to the Response object representing the fetched data. + */ public fetch(method: string, params?: object, id: string | number = 0) { const rpcRequestBody: JRPC.RequestBody = { id, @@ -89,6 +105,17 @@ export class RpcChannel { }); } + /** + * Handles errors in the software library. + * + * @param {string} method - The name of the method that encountered the error. + * @param {any} params - The parameters passed to the method. + * @param {JRPC.Error} [rpcError] - The error object returned by the remote procedure call. Defaults to undefined. + * @param {any} [otherError] - Any other error object encountered. Defaults to undefined. + * @throws {LibraryError} - If rpcError is provided, it throws a LibraryError with the error code, message, and data. + * @throws {LibraryError} - If otherError instance is provided, it throws the same LibraryError. + * @throws {Error} - If otherError is provided, it throws a generic Error with the error message. + */ protected errorHandler(method: string, params: any, rpcError?: JRPC.Error, otherError?: any) { if (rpcError) { const { code, message, data } = rpcError; @@ -105,6 +132,14 @@ export class RpcChannel { } } + /** + * Fetches data from the specified API endpoint. + * + * @param method - The method name of the API endpoint. + * @param params - Optional parameters for the API endpoint. + * @returns A Promise that resolves to the result of the API endpoint. + * @throws If an error occurs during the fetch operation. + */ protected async fetchEndpoint( method: T, params?: RPC.Methods[T]['params'] @@ -120,16 +155,35 @@ export class RpcChannel { } } + /** + * Retrieves the chain ID from the Starknet endpoint. + * If the chain ID has already been fetched, it returns the cached value. + * + * @returns - A promise that resolves to the chain ID. + */ public async getChainId() { this.chainId ??= (await this.fetchEndpoint('starknet_chainId')) as StarknetChainId; return this.chainId; } + /** + * Returns the version of the Starknet JSON-RPC specification being used + * + * @returns - A Promise that resolves with the spec version of the Starknet chain. + */ public async getSpecVersion() { this.specVersion ??= (await this.fetchEndpoint('starknet_specVersion')) as StarknetChainId; return this.specVersion; } + /** + * Retrieves the nonce for a given contract address and block identifier. + * + * @param {BigNumberish} contractAddress - The contract address to retrieve the nonce for. + * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The block identifier to retrieve the nonce from (optional, defaults to this.blockIdentifier). + * + * @return - A promise that resolves to the nonce value. + */ public getNonceForAddress( contractAddress: BigNumberish, blockIdentifier: BlockIdentifier = this.blockIdentifier @@ -158,31 +212,68 @@ export class RpcChannel { return this.fetchEndpoint('starknet_blockNumber'); } + /** + * Retrieves a block with transaction hashes. + * + * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The identifier of the block to retrieve. + * @return {Promise} - A promise that resolves with the block containing transaction hashes. + */ public getBlockWithTxHashes(blockIdentifier: BlockIdentifier = this.blockIdentifier) { const block_id = new Block(blockIdentifier).identifier; return this.fetchEndpoint('starknet_getBlockWithTxHashes', { block_id }); } + /** + * Retrieves a block with its transactions. + * + * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The identifier of the block to retrieve. Defaults to the current block identifier. + * @return {Promise} A promise that resolves to the block with its transactions. + */ public getBlockWithTxs(blockIdentifier: BlockIdentifier = this.blockIdentifier) { const block_id = new Block(blockIdentifier).identifier; return this.fetchEndpoint('starknet_getBlockWithTxs', { block_id }); } + /** + * Retrieve the state update for a given block. + * + * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The identifier of the block to retrieve the state update for. + * @return {Promise} - A promise that resolves with the state update of the specified block. + */ public getBlockStateUpdate(blockIdentifier: BlockIdentifier = this.blockIdentifier) { const block_id = new Block(blockIdentifier).identifier; return this.fetchEndpoint('starknet_getStateUpdate', { block_id }); } + /** + * Fetches the transaction traces for a given block identifier. + * + * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The block identifier. + * @returns {Promise} - A promise that resolves with an array of transaction traces. + */ public getBlockTransactionsTraces(blockIdentifier: BlockIdentifier = this.blockIdentifier) { const block_id = new Block(blockIdentifier).identifier; return this.fetchEndpoint('starknet_traceBlockTransactions', { block_id }); } + /** + * Retrieves the number of transactions in a given block. + * + * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The identifier of the block. Defaults to the current block identifier. + * + * @return {Promise} - A Promise that resolves to the number of transactions in the block. + */ public getBlockTransactionCount(blockIdentifier: BlockIdentifier = this.blockIdentifier) { const block_id = new Block(blockIdentifier).identifier; return this.fetchEndpoint('starknet_getBlockTransactionCount', { block_id }); } + /** + * Fetches transaction details by its hash. + * + * @param {BigNumberish} txHash - The hash of the transaction. + * @returns {Promise} - A promise that resolves with the transaction details. + */ public getTransactionByHash(txHash: BigNumberish) { const transaction_hash = toHex(txHash); return this.fetchEndpoint('starknet_getTransactionByHash', { @@ -190,16 +281,35 @@ export class RpcChannel { }); } + /** + * Retrieves a transaction from the StarkNet blockchain by its block identifier and index. + * + * @param {BlockIdentifier} blockIdentifier - The identifier of the block containing the transaction. + * @param {number} index - The index of the transaction within the block. + * @return {Promise} - A Promise that resolves to the requested transaction object. + */ public getTransactionByBlockIdAndIndex(blockIdentifier: BlockIdentifier, index: number) { const block_id = new Block(blockIdentifier).identifier; return this.fetchEndpoint('starknet_getTransactionByBlockIdAndIndex', { block_id, index }); } + /** + * Retrieves the transaction receipt for a given transaction hash. + * + * @param {BigNumberish} txHash - The transaction hash to retrieve the receipt for. + * @return {Promise} A promise that resolves with the transaction receipt object. + */ public getTransactionReceipt(txHash: BigNumberish) { const transaction_hash = toHex(txHash); return this.fetchEndpoint('starknet_getTransactionReceipt', { transaction_hash }); } + /** + * Retrieves the transaction trace for a given transaction hash. + * + * @param {BigNumberish} txHash - The transaction hash to fetch the trace for. + * @returns {Promise} - The transaction trace object. + */ public getTransactionTrace(txHash: BigNumberish) { const transaction_hash = toHex(txHash); return this.fetchEndpoint('starknet_traceTransaction', { transaction_hash }); @@ -207,6 +317,9 @@ export class RpcChannel { /** * Get the status of a transaction + * + * @param {BigNumberish} transactionHash - The hash of the transaction. + * @return {Promise} - A promise that resolves to the transaction status object. */ public getTransactionStatus(transactionHash: BigNumberish) { const transaction_hash = toHex(transactionHash); @@ -240,6 +353,15 @@ export class RpcChannel { }); } + /** + * Asynchronously waits for a transaction to be confirmed on the blockchain. + * + * @param {BigNumberish} txHash - The transaction hash to wait for. + * @param {waitForTransactionOptions} [options] - Optional parameters for the method. + * @return {Promise} - A promise that resolves with the transaction receipt. + * @throws {Error} - If the transaction is rejected or encounters an error. + * @throws {Error} - If the maximum number of retries is reached. + */ public async waitForTransaction(txHash: BigNumberish, options?: waitForTransactionOptions) { const transactionHash = toHex(txHash); let { retries } = this; @@ -322,6 +444,15 @@ export class RpcChannel { return txReceipt as RPC.SPEC.TXN_RECEIPT; } + /** + * Retrieves the storage value at the specified key for a given contract address and block identifier. + * + * @param {BigNumberish} contractAddress - The address of the contract. + * @param {BigNumberish} key - The key to retrieve the storage value from. + * @param {BlockIdentifier} [blockIdentifier] - The identifier of the block. Defaults to the current block identifier. + * + * @return {Promise} - A promise resolving to the storage value at the specified key. + */ public getStorageAt( contractAddress: BigNumberish, key: BigNumberish, @@ -337,6 +468,13 @@ export class RpcChannel { }); } + /** + * Gets the class hash of a contract at a given block. + * + * @param {BigNumberish} contractAddress - The contract address. + * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The block identifier. + * @returns {Promise} - A Promise that resolves with the class hash of the contract at the given block. + */ public getClassHashAt( contractAddress: BigNumberish, blockIdentifier: BlockIdentifier = this.blockIdentifier @@ -349,6 +487,13 @@ export class RpcChannel { }); } + /** + * Retrieves the class information for the given class hash. + * + * @param {BigNumberish} classHash - The hash of the class. + * @param {BlockIdentifier} [blockIdentifier] - The block identifier. Default value is set to 'this.blockIdentifier'. + * @returns {Promise} - A promise that resolves to the class information object. + */ public getClass( classHash: BigNumberish, blockIdentifier: BlockIdentifier = this.blockIdentifier @@ -361,6 +506,13 @@ export class RpcChannel { }); } + /** + * Retrieves the class at the specified contract address and block identifier. + * + * @param {BigNumberish} contractAddress - The address of the contract. + * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The block identifier. + * @return {Promise} - A promise that resolves with the class information. + */ public getClassAt( contractAddress: BigNumberish, blockIdentifier: BlockIdentifier = this.blockIdentifier @@ -373,6 +525,16 @@ export class RpcChannel { }); } + /** + * Retrieves the estimated fee for a given set of account invocations. + * + * @param {AccountInvocations} invocations - The list of account invocations. + * @param {getEstimateFeeBulkOptions} options - The options for getting estimated fee. + * - blockIdentifier: The identifier of the block to use. Default is the current block identifier. + * - skipValidate: A flag indicating whether to skip validation. Default is true. + * + * @return {Promise} - The estimated fee. + */ public async getEstimateFee( invocations: AccountInvocations, { blockIdentifier = this.blockIdentifier, skipValidate = true }: getEstimateFeeBulkOptions @@ -392,6 +554,13 @@ export class RpcChannel { }); } + /** + * Invokes a function on a contract. + * + * @param {Invocation} functionInvocation - The function invocation details. + * @param {InvocationsDetailsWithNonce} details - The transaction details. + * @returns {Promise} - A promise that resolves to the transaction hash or the transaction object. + */ public async invoke(functionInvocation: Invocation, details: InvocationsDetailsWithNonce) { let promise; if (!isV3Tx(details)) { @@ -430,6 +599,14 @@ export class RpcChannel { return this.waitMode ? this.waitForTransaction((await promise).transaction_hash) : promise; } + /** + * Declares a contract transaction on the StarkNet blockchain. + * + * @param {DeclareContractTransaction} transaction - The transaction details. + * @param {InvocationsDetailsWithNonce} details - The details of the transaction invocations. + * @throws {Error} If the parameters of the transaction are incorrect. + * @returns {Promise} A promise that resolves to the transaction hash. + */ public async declare( { contract, signature, senderAddress, compiledClassHash }: DeclareContractTransaction, details: InvocationsDetailsWithNonce @@ -502,6 +679,14 @@ export class RpcChannel { return this.waitMode ? this.waitForTransaction((await promise).transaction_hash) : promise; } + /** + * Deploy an account contract transaction. + * + * @param {DeployAccountContractTransaction} deployAccountTransaction - The transaction details. + * @param {InvocationsDetailsWithNonce} details - The additional transaction details. + * + * @return {Promise} - Promise resolved with the transaction result or transaction hash if `waitMode` is enabled. + */ public async deployAccount( { classHash, constructorCalldata, addressSalt, signature }: DeployAccountContractTransaction, details: InvocationsDetailsWithNonce @@ -544,6 +729,13 @@ export class RpcChannel { return this.waitMode ? this.waitForTransaction((await promise).transaction_hash) : promise; } + /** + * Calls a contract on the StarkNet protocol. + * + * @param {Call} call - The call object representing the contract call. + * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The identifier of the block to execute the contract call. + * @returns {Promise} - A promise that resolves with the result of the contract call. + */ public callContract(call: Call, blockIdentifier: BlockIdentifier = this.blockIdentifier) { const block_id = new Block(blockIdentifier).identifier; return this.fetchEndpoint('starknet_call', { diff --git a/src/contract/interface.ts b/src/contract/interface.ts index 9a2f53e0b..b04ae9fe5 100644 --- a/src/contract/interface.ts +++ b/src/contract/interface.ts @@ -162,5 +162,11 @@ export abstract class ContractInterface { */ public abstract getVersion(): Promise; + /** + * Returns a typed instance of ContractV2 based on the supplied ABI. + * + * @param {TAbi} tAbi - The ABI (Abstract Binary Interface) of the ContractV2. + * @return {TypedContractV2} - A typed instance of ContractV2. + */ public abstract typedv2(tAbi: TAbi): TypedContractV2; } diff --git a/src/provider/extensions/starknetId.ts b/src/provider/extensions/starknetId.ts index 1c9848ee5..7288086ed 100644 --- a/src/provider/extensions/starknetId.ts +++ b/src/provider/extensions/starknetId.ts @@ -18,6 +18,13 @@ import { import type { ProviderInterface } from '..'; export class StarknetId { + /** + * Retrieves the Stark name associated with a specific address. + * + * @param {BigNumberish} address - The address to query the Stark name for. + * @param {string} [StarknetIdContract] - The Starknet ID contract address. Optional. + * @returns {Promise} - A Promise that resolves to the Stark name associated with the address. + */ async getStarkName(address: BigNumberish, StarknetIdContract?: string) { return StarknetId.getStarkName( // After Mixin, this is ProviderInterface @@ -27,6 +34,14 @@ export class StarknetId { ); } + /** + * Retrieves the address associated with a given Stark name. + * + * @param {string} name - The Stark name. + * @param {string} [StarknetIdContract] - The contract address of the StarknetId smart contract. + * + * @returns {Promise} - The address associated with the Stark name. + */ public async getAddressFromStarkName(name: string, StarknetIdContract?: string): Promise { return StarknetId.getAddressFromStarkName( // After Mixin, this is ProviderInterface @@ -36,6 +51,18 @@ export class StarknetId { ); } + /** + * Retrieves the Stark profile for a given address. + * + * @param {BigNumberish} address - The address for which to retrieve the Stark profile. + * @param {string} [StarknetIdContract] - The address of the StarknetId contract. + * @param {string} [StarknetIdIdentityContract] - The address of the StarknetIdIdentity contract. + * @param {string} [StarknetIdVerifierContract] - The address of the StarknetIdVerifier contract. + * @param {string} [StarknetIdPfpContract] - The address of the StarknetIdPfp contract. + * @param {string} [StarknetIdPopContract] - The address of the StarknetIdPop contract. + * @param {string} [StarknetIdMulticallContract] - The address of the StarknetIdMulticall contract. + * @returns {Promise} A Promise that resolves to the Stark profile. + */ async getStarkProfile( address: BigNumberish, StarknetIdContract?: string, @@ -58,6 +85,15 @@ export class StarknetId { ); } + /** + * Retrieves the Starkname associated with a given Ethereum address. + * + * @param {ProviderInterface} provider - The provider interface. + * @param {BigNumberish} address - The Ethereum address. + * @param {string} [StarknetIdContract] - The address of the Starknet Id contract. If not provided, it will be derived based on the chainId. + * @returns {Promise} - The Starkname associated with the given Ethereum address. + * @throws {Error} - If the Starkname is not found or if an error occurred while retrieving the Starkname. + */ static async getStarkName( provider: ProviderInterface, address: BigNumberish, @@ -91,6 +127,15 @@ export class StarknetId { } } + /** + * Retrieves the address associated with a Stark name. + * + * @param {ProviderInterface} provider - The provider to use for interacting with the blockchain. + * @param {string} name - The Stark name to retrieve the address for. + * @param {string} [StarknetIdContract] - The address of the StarknetId contract. If not provided, it will be retrieved based on the chain Id. + * @returns {Promise} - The address associated with the Stark name. + * @throws {Error} - If the address cannot be retrieved. + */ static async getAddressFromStarkName( provider: ProviderInterface, name: string, @@ -117,6 +162,20 @@ export class StarknetId { } } + /** + * Retrieves the Stark Profile of a user using their Ethereum address. + * + * @param {ProviderInterface} provider - The provider interface used to communicate with the blockchain. + * @param {BigNumberish} address - The Ethereum address of the user. + * @param {string} [StarknetIdContract] - The contract address of the Starknet ID contract. + * @param {string} [StarknetIdIdentityContract] - The contract address of the Starknet ID Identity contract. + * @param {string} [StarknetIdVerifierContract] - The contract address of the Starknet ID Verifier contract. + * @param {string} [StarknetIdPfpContract] - The contract address of the Starknet ID Pfp contract. + * @param {string} [StarknetIdPopContract] - The contract address of the Starknet ID Proof-of-Personhood contract. + * @param {string} [StarknetIdMulticallContract] - The contract address of the Starknet ID Multicall contract. + * @returns {Promise} - The Stark Profile of the user, including their name, social media accounts, proof-of-personhood status, and profile picture. + * @throws {Error} - If there was an error while retrieving the Stark Profile. + */ static async getStarkProfile( provider: ProviderInterface, address: BigNumberish, diff --git a/src/signer/default.ts b/src/signer/default.ts index 1915c8274..94171c025 100644 --- a/src/signer/default.ts +++ b/src/signer/default.ts @@ -135,6 +135,12 @@ export class Signer implements SignerInterface { return this.signRaw(msgHash as string); } + /** + * Signs a raw message hash using the `starkCurve` and the provided private key. + * + * @param {string} msgHash - The raw message hash to sign. + * @returns {Promise} - A Promise that resolves to the generated signature. + */ protected async signRaw(msgHash: string): Promise { return starkCurve.sign(msgHash, this.pk); } diff --git a/src/signer/ethSigner.ts b/src/signer/ethSigner.ts index d54dcd23e..afe429b3a 100644 --- a/src/signer/ethSigner.ts +++ b/src/signer/ethSigner.ts @@ -56,6 +56,12 @@ export class EthSigner implements SignerInterface { ); } + /** + * Signs the provided message with the given account address. + * @param {TypedData} typedData - The message data to be signed. + * @param {string} accountAddress - The address of the signing account. + * @return {Promise} - The signature of the message. + */ public async signMessage(typedData: TypedData, accountAddress: string): Promise { const msgHash = getMessageHash(typedData, accountAddress); const signature: RecoveredSignatureType = secp256k1.sign( @@ -65,6 +71,14 @@ export class EthSigner implements SignerInterface { return this.formatEthSignature(signature); } + /** + * Signs a transaction using the provided transactions and details. + * + * @param {Call[]} transactions - The transactions to be signed. + * @param {InvocationsSignerDetails} details - The details needed for signing. + * @return {Promise} - The signed transaction. + * @throws {Error} - Throws an error if the signTransaction version is unsupported. + */ public async signTransaction( transactions: Call[], details: InvocationsSignerDetails @@ -101,6 +115,12 @@ export class EthSigner implements SignerInterface { return this.formatEthSignature(signature); } + /** + * Signs a deploy account transaction. + * @param {DeployAccountSignerDetails} details - The details of the deploy account transaction. + * @return {Promise} - The signature of the signed transaction. + * @throws {Error} - If the version of the deploy account transaction is not supported. + */ public async signDeployAccountTransaction( details: DeployAccountSignerDetails ): Promise { @@ -136,6 +156,13 @@ export class EthSigner implements SignerInterface { return this.formatEthSignature(signature); } + /** + * Signs a declare transaction. + * + * @param {DeclareSignerDetails} details - The details of the declare transaction. + * @returns {Promise} - The signature of the declare transaction. + * @throws {Error} - If the version of the declare transaction is unsupported. + */ public async signDeclareTransaction( // contractClass: ContractClass, // Should be used once class hash is present in ContractClass details: DeclareSignerDetails diff --git a/src/utils/address.ts b/src/utils/address.ts index 7cfbe2860..f4185a0d8 100644 --- a/src/utils/address.ts +++ b/src/utils/address.ts @@ -33,7 +33,14 @@ export function validateAndParseAddress(address: BigNumberish): string { return result; } -// from https://github.com/ethers-io/ethers.js/blob/fc1e006575d59792fa97b4efb9ea2f8cca1944cf/packages/address/src.ts/index.ts#L12 +/** + * Computes the checksum address for the given Ethereum address. + * + * From https://github.com/ethers-io/ethers.js/blob/fc1e006575d59792fa97b4efb9ea2f8cca1944cf/packages/address/src.ts/index.ts#L12 + * @param {BigNumberish} address - The Ethereum address to compute the checksum for. + * + * @returns {string} The checksum address. + */ export function getChecksumAddress(address: BigNumberish): string { const chars = removeHexPrefix(validateAndParseAddress(address)).toLowerCase().split(''); const hex = removeHexPrefix(keccakBn(address)); diff --git a/src/utils/assert.ts b/src/utils/assert.ts index f32cc5bc4..4d0830ebb 100644 --- a/src/utils/assert.ts +++ b/src/utils/assert.ts @@ -1,3 +1,9 @@ +/** + * Asserts that the given condition is true, otherwise throws an error with an optional message. + * @param {any} condition - The condition to check. + * @param {string} [message] - The optional message to include in the error. + * @throws {Error} Throws an error if the condition is false. + */ export default function assert(condition: any, message?: string): asserts condition { if (!condition) { throw new Error(message || 'Assertion failure'); diff --git a/src/utils/calldata/cairo.ts b/src/utils/calldata/cairo.ts index d105e7462..538582242 100644 --- a/src/utils/calldata/cairo.ts +++ b/src/utils/calldata/cairo.ts @@ -14,32 +14,141 @@ import { CairoUint256 } from '../cairoDataTypes/uint256'; import { CairoUint512 } from '../cairoDataTypes/uint512'; // Intended for internal usage, maybe should be exported somewhere else and not exported to utils +/** + * Checks if the given name ends with "_len". + * + * @param {string} name - The name to be checked. + * @returns - True if the name ends with "_len", false otherwise. + */ export const isLen = (name: string) => /_len$/.test(name); +/** + * Checks if a given type is felt. + * + * @param {string} type - The type to check. + * @returns - True if the type is felt, false otherwise. + */ export const isTypeFelt = (type: string) => type === 'felt' || type === 'core::felt252'; +/** + * Checks if the given type is an array type. + * + * @param {string} type - The type to check. + * @returns - `true` if the type is an array type, `false` otherwise. + */ export const isTypeArray = (type: string) => /\*/.test(type) || type.startsWith('core::array::Array::') || type.startsWith('core::array::Span::'); +/** + * Checks if the given type is a tuple type. + * + * @param {string} type - The type to be checked. + * @returns - `true` if the type is a tuple type, otherwise `false`. + */ export const isTypeTuple = (type: string) => /^\(.*\)$/i.test(type); +/** + * Checks whether a given type is a named tuple. + * + * @param {string} type - The type to be checked. + * @returns - True if the type is a named tuple, false otherwise. + */ export const isTypeNamedTuple = (type: string) => /\(.*\)/i.test(type) && type.includes(':'); +/** + * Checks if a given type exists in a collection of structs. + * + * @param {string} type - The type to check for existence. + * @param {AbiStructs} structs - The collection of structs to search in. + * @returns - True if the type exists in the structs, false otherwise. + */ export const isTypeStruct = (type: string, structs: AbiStructs) => type in structs; +/** + * Checks if a given type exists in the provided enumeration. + * + * @param {string} type - The type to check. + * @param {AbiEnums} enums - The enumeration to search in. + * @returns - True if the type exists in the enumeration, otherwise false. + */ export const isTypeEnum = (type: string, enums: AbiEnums) => type in enums; +/** + * Determines if the given type is an Option type. + * + * @param {string} type - The type to check. + * @returns - True if the type is an Option type, false otherwise. + */ export const isTypeOption = (type: string) => type.startsWith('core::option::Option::'); +/** + * Checks whether a given type starts with 'core::result::Result::'. + * + * @param {string} type - The type to check. + * @returns - True if the type starts with 'core::result::Result::', false otherwise. + */ export const isTypeResult = (type: string) => type.startsWith('core::result::Result::'); +/** + * Checks if the given value is a valid Uint type. + * + * @param {string} type - The value to check. + * @returns - Returns true if the value is a valid Uint type, otherwise false. + */ export const isTypeUint = (type: string) => Object.values(Uint).includes(type as Uint); // Legacy Export +/** + * Checks if the given type is `uint256`. + * + * @param {string} type - The type to be checked. + * @returns - Returns true if the type is `uint256`, otherwise false. + */ export const isTypeUint256 = (type: string) => CairoUint256.isAbiType(type); +/** + * Checks if the given type is a literal type. + * + * @param {string} type - The type to check. + * @returns - True if the type is a literal type, false otherwise. + */ export const isTypeLiteral = (type: string) => Object.values(Literal).includes(type as Literal); +/** + * Checks if the given type is a boolean type. + * + * @param {string} type - The type to be checked. + * @returns - Returns true if the type is a boolean type, otherwise false. + */ export const isTypeBool = (type: string) => type === 'core::bool'; +/** + * Checks if the provided type is equal to 'core::starknet::contract_address::ContractAddress'. + * @param {string} type - The type to be checked. + * @returns - true if the type matches 'core::starknet::contract_address::ContractAddress', false otherwise. + */ export const isTypeContractAddress = (type: string) => type === 'core::starknet::contract_address::ContractAddress'; +/** + * Determines if the given type is an Ethereum address type. + * + * @param {string} type - The type to check. + * @returns - Returns true if the given type is 'core::starknet::eth_address::EthAddress', otherwise false. + */ export const isTypeEthAddress = (type: string) => type === 'core::starknet::eth_address::EthAddress'; +/** + * Checks if the given type is 'core::bytes_31::bytes31'. + * + * @param {string} type - The type to check. + * @returns - True if the type is 'core::bytes_31::bytes31', false otherwise. + */ export const isTypeBytes31 = (type: string) => type === 'core::bytes_31::bytes31'; +/** + * Checks if the given type is equal to the 'core::byte_array::ByteArray'. + * + * @param {string} type - The type to check. + * @returns - True if the given type is equal to 'core::byte_array::ByteArray', false otherwise. + */ export const isTypeByteArray = (type: string) => type === 'core::byte_array::ByteArray'; export const isTypeSecp256k1Point = (type: string) => type === 'core::starknet::secp256k1::Secp256k1Point'; export const isCairo1Type = (type: string) => type.includes('::'); +/** + * Retrieves the array type from the given type string. + * + * @param {string} type - The type string. + * @returns - The array type. + */ export const getArrayType = (type: string) => { if (isCairo1Type(type)) { return type.substring(type.indexOf('<') + 1, type.lastIndexOf('>')); diff --git a/src/utils/calldata/formatter.ts b/src/utils/calldata/formatter.ts index 19d152531..a0adc3a68 100644 --- a/src/utils/calldata/formatter.ts +++ b/src/utils/calldata/formatter.ts @@ -15,6 +15,14 @@ const guard = { }, }; +/** + * Formats the given data based on the provided type definition. + * + * @param {any} data - The data to be formatted. + * @param {any} type - The type definition for the data. + * @param {any} [sameType] - The same type definition to be used (optional). + * @returns - The formatted data. + */ export default function formatter(data: any, type: any, sameType?: any) { // match data element with type element return Object.entries(data).reduce((acc, [key, value]: [any, any]) => { diff --git a/src/utils/calldata/propertyOrder.ts b/src/utils/calldata/propertyOrder.ts index 27e8d449f..bdc7cb32c 100644 --- a/src/utils/calldata/propertyOrder.ts +++ b/src/utils/calldata/propertyOrder.ts @@ -26,6 +26,11 @@ import extractTupleMemberTypes from './tuple'; import { isString } from '../shortString'; +/** + * Creates a new Error object indicating that the provided key in the object includes an Uint256 object without the 'low' and 'high' keys. + * @param {string} key - The key indicating the property in the object. + * @return - The Error object indicating the missing 'low' and 'high' keys. + */ function errorU256(key: string) { return Error( `Your object includes the property : ${key}, containing an Uint256 object without the 'low' and 'high' keys.` @@ -44,6 +49,13 @@ export default function orderPropsByAbi( structs: AbiStructs, enums: AbiEnums ): object { + /** + * Orders an input item based on its ABI type. + * + * @param {any} unorderedItem - The unordered item to be ordered. + * @param {string} abiType - The ABI type of the item. + * @returns - The ordered item. + */ const orderInput = (unorderedItem: any, abiType: string): any => { if (isTypeArray(abiType)) { return orderArray(unorderedItem, abiType); @@ -96,6 +108,14 @@ export default function orderPropsByAbi( return unorderedItem; }; + /** + * Orders the properties of the input object based on the given ABI entries. + * + * @param {object} unorderedObject2 - The input object whose properties need to be ordered. + * @param {Array} abiObject - An array of ABI entries representing the desired order of properties. + * @returns - The ordered object with properties based on the given ABI entries. + * @throws {Error} If the input object is missing a required property or if a property has an invalid value. + */ const orderStruct = (unorderedObject2: RawArgsObject, abiObject: AbiEntry[]): object => { const orderedObject2 = abiObject.reduce((orderedObject, abiParam) => { const setProperty = (value?: any) => @@ -115,6 +135,14 @@ export default function orderPropsByAbi( return orderedObject2; }; + /** + * Orders the elements in the array according to the given ABI parameter. + * + * @param {Array | string} myArray - The array to be ordered. Can be either an array of any type or a string. + * @param {string} abiParam - The ABI parameter used to determine the order of the elements. + * + * @return - The ordered array or the input string if it is not an array. + */ function orderArray(myArray: Array | string, abiParam: string): Array | string { const typeInArray = getArrayType(abiParam); if (isString(myArray)) { @@ -123,6 +151,13 @@ export default function orderPropsByAbi( return myArray.map((myElem) => orderInput(myElem, typeInArray)); } + /** + * Orders the properties of the input object based on the provided ABI parameter. + * + * @param {object} unorderedObject2 - The input object with unordered properties. + * @param {string} abiParam - The ABI parameter for ordering the properties. + * @return - The ordered object with properties arranged according to ABI parameter. + */ function orderTuple(unorderedObject2: RawArgsObject, abiParam: string): object { const typeList = extractTupleMemberTypes(abiParam); const orderedObject2 = typeList.reduce((orderedObject: object, abiTypeCairoX: any, index) => { @@ -139,6 +174,12 @@ export default function orderPropsByAbi( return orderedObject2; } + /** + * Applies a specific order to the given unordered object based on the provided ABI entry. + * @param {CairoEnum} unorderedObject2 - The unordered object. + * @param {AbiEntry} abiObject - The ABI entry. + * @returns {CairoEnum} The ordered object. + */ const orderEnum = (unorderedObject2: CairoEnum, abiObject: AbiEntry): CairoEnum => { if (isTypeResult(abiObject.name)) { const unorderedResult = unorderedObject2 as CairoResult; diff --git a/src/utils/calldata/requestParser.ts b/src/utils/calldata/requestParser.ts index 5a4a099b0..deeb3e943 100644 --- a/src/utils/calldata/requestParser.ts +++ b/src/utils/calldata/requestParser.ts @@ -93,6 +93,12 @@ function parseTuple(element: object, typeStr: string): Tupled[] { }); } +/** + * Parses a string representation of a byte array and returns an array of strings. + * + * @param {string} element - The string representation of the byte array. + * @return {string[]} An array of strings representing the byte array. + */ function parseByteArray(element: string): string[] { const myByteArray: ByteArray = byteArrayFromString(element); return [ diff --git a/src/utils/calldata/responseParser.ts b/src/utils/calldata/responseParser.ts index 298bfa711..fbf7fd433 100644 --- a/src/utils/calldata/responseParser.ts +++ b/src/utils/calldata/responseParser.ts @@ -84,6 +84,7 @@ function parseBaseTypes(type: string, it: Iterator) { * @param responseIterator - iterator of the response * @param element - element of the field {name: string, type: string} * @param structs - structs from abi + * @param enums * @return {any} - parsed arguments in format that contract is expecting */ function parseResponseValue( diff --git a/src/utils/calldata/tuple.ts b/src/utils/calldata/tuple.ts index 263704d3e..3c887c6c0 100644 --- a/src/utils/calldata/tuple.ts +++ b/src/utils/calldata/tuple.ts @@ -1,12 +1,26 @@ /* eslint-disable no-plusplus */ import { isCairo1Type, isTypeNamedTuple } from './cairo'; +/** + * Parses a named tuple. + * + * @param {string} namedTuple - The named tuple to parse in the format "name:type". + * @returns - The parsed named tuple as an object with properties "name" and "type". + */ function parseNamedTuple(namedTuple: string): any { const name = namedTuple.substring(0, namedTuple.indexOf(':')); const type = namedTuple.substring(name.length + ':'.length); return { name, type }; } +/** + * Parses and extracts sub-tuples from a given string. + * + * @param {string} s - The input string to parse. + * @return - An object containing the sub-tuples and the remaining string. + * - subTuple: {Array} - An array of strings representing the extracted sub-tuples. + * - result: {string} - The remaining string after extracting the sub-tuples. + */ function parseSubTuple(s: string) { if (!s.includes('(')) return { subTuple: [], result: s }; const subTuple: string[] = []; @@ -37,6 +51,12 @@ function parseSubTuple(s: string) { }; } +/** + * Extracts tuples from a given type. + * + * @param {string} type - The type containing tuples. + * @returns {string[]} - An array of extracted tuples. + */ function extractCairo0Tuple(type: string) { const cleanType = type.replace(/\s/g, '').slice(1, -1); // remove first lvl () and spaces @@ -58,6 +78,14 @@ function extractCairo0Tuple(type: string) { return recomposed; } +/** + * Finds the offset at which a closure ends in a given input string. + * + * @param {string} input - The input string. + * @param {string} open - The opening closure character. + * @param {string} close - The closing closure character. + * @return {number} - The offset at which the closure ends, or Number.POSITIVE_INFINITY if no closure is found. + */ function getClosureOffset(input: string, open: string, close: string): number { for (let i = 0, counter = 0; i < input.length; i++) { if (input[i] === open) { @@ -69,6 +97,12 @@ function getClosureOffset(input: string, open: string, close: string): number { return Number.POSITIVE_INFINITY; } +/** + * Extracts individual elements from a tuple string. + * + * @param {string} type - The tuple string to extract elements from. + * @returns {string[]} - An array containing the individual elements of the tuple string. + */ function extractCairo1Tuple(type: string): string[] { // un-named tuples support const input = type.slice(1, -1); // remove first lvl () diff --git a/src/utils/calldata/validate.ts b/src/utils/calldata/validate.ts index 1d6593706..a578c1c7a 100644 --- a/src/utils/calldata/validate.ts +++ b/src/utils/calldata/validate.ts @@ -33,6 +33,15 @@ import { isTypeUint, } from './cairo'; +/** + * Validates a felt parameter. + * + * @param {any} parameter - The parameter to validate. + * @param {AbiEntry} input - The input AbiEntry containing the name and type of the parameter. + * @throws {Error} Throws an error if the parameter is not a string, number, or bigint. + * @throws {Error} Throws an error if the parameter is a string but not a valid hexadecimal string. + * @throws {Error} Throws an error if the parameter is outside the range [0, 2^252 - 1]. + */ const validateFelt = (parameter: any, input: AbiEntry) => { assert( isString(parameter) || isNumber(parameter) || isBigInt(parameter), @@ -47,6 +56,14 @@ const validateFelt = (parameter: any, input: AbiEntry) => { ); }; +/** + * Validates a parameter and checks if it is a string of less than 32 characters. + * + * @param {any} parameter - The parameter to be validated. + * @param {AbiEntry} input - The ABI entry object related to the parameter. + * @returns {void} + * @throws {Error} - If the parameter is not a string or has a length greater than or equal to 32. + */ const validateBytes31 = (parameter: any, input: AbiEntry) => { assert(isString(parameter), `Validate: arg ${input.name} should be a string.`); assert( @@ -55,10 +72,25 @@ const validateBytes31 = (parameter: any, input: AbiEntry) => { ); }; +/** + * Validate a byte array parameter against a specific ABI entry. + * + * @param {any} parameter - The parameter to be validated. + * @param {AbiEntry} input - The ABI entry to validate against. + * @throws {TypeError} - If the parameter is not a string. + */ const validateByteArray = (parameter: any, input: AbiEntry) => { assert(isString(parameter), `Validate: arg ${input.name} should be a string.`); }; +/** + * Validates a given parameter against the specified Cairo type. + * + * @param {any} parameter - The parameter to be validated. + * @param {AbiEntry} input - The AbiEntry object that represents the Cairo type. + * @returns {void} + * @throws {Error} If the parameter is not of the expected type or exceeds the specified range. + */ const validateUint = (parameter: any, input: AbiEntry) => { if (isNumber(parameter)) { assert( @@ -163,6 +195,13 @@ const validateUint = (parameter: any, input: AbiEntry) => { } }; +/** + * Validates a boolean parameter against a given ABI entry. + * + * @param {any} parameter - The parameter to be validated. + * @param {AbiEntry} input - The ABI entry against which the parameter should be validated. + * @throws {AssertionError} - If the parameter is not a boolean. + */ const validateBool = (parameter: any, input: AbiEntry) => { assert( isBoolean(parameter), @@ -170,6 +209,13 @@ const validateBool = (parameter: any, input: AbiEntry) => { ); }; +/** + * Validates a struct parameter based on the input type and structure definition. + * + * @param {any} parameter - The parameter to be validated. + * @param {AbiEntry} input - The AbiEntry object that represents the struct input. + * @param {AbiStructs} structs - The AbiStructs object that contains the structure definitions. + */ const validateStruct = (parameter: any, input: AbiEntry, structs: AbiStructs) => { // c1v2 uint256 or u512 in struct if (input.type === Uint.u256 || input.type === Uint.u512) { @@ -205,6 +251,13 @@ const validateStruct = (parameter: any, input: AbiEntry, structs: AbiStructs) => }); }; +/** + * Validates if the given parameter is a valid Enum based on the input definition. + * + * @param {any} parameter - The parameter to be validated as an Enum. + * @param {AbiEntry} input - The input definition for the Enum. + * @throws {Error} If the parameter is not a valid Enum. + */ const validateEnum = (parameter: any, input: AbiEntry) => { assert( typeof parameter === 'object' && !Array.isArray(parameter), @@ -226,6 +279,17 @@ const validateEnum = (parameter: any, input: AbiEntry) => { ); }; +/** + * Validates that the given parameter is a tuple (defined as an object). + * + * @param {any} parameter - The parameter to validate. + * @param {AbiEntry} input - The input for which the validation is performed. + * @throws {AssertionError} - If the parameter is not a tuple. + * @returns + * + * @example + * validateTuple({ prop1: 'value1', prop2: 'value2' }, { name: 'param' }); + */ const validateTuple = (parameter: any, input: AbiEntry) => { assert( typeof parameter === 'object' && !Array.isArray(parameter), @@ -277,6 +341,15 @@ const validateArray = (parameter: any, input: AbiEntry, structs: AbiStructs, enu } }; +/** + * Validates the fields of the given ABI method. + * + * @param {FunctionAbi} abiMethod - The ABI method to validate. + * @param {Array} args - The arguments passed to the method. + * @param {AbiStructs} structs - The ABI structs used for validation. + * @param {AbiEnums} enums - The ABI enums used for validation. + * @throws {Error} If the validation fails. + */ export default function validateFields( abiMethod: FunctionAbi, args: Array, diff --git a/src/utils/contract.ts b/src/utils/contract.ts index 09d51301a..1fb6a5315 100644 --- a/src/utils/contract.ts +++ b/src/utils/contract.ts @@ -13,6 +13,12 @@ import { decompressProgram } from './stark'; import { isString } from './shortString'; +/** + * Checks if a given contract is in Sierra (Safe Intermediate Representation) format. + * + * @param {CairoContract | string} contract - The contract to check. Can be either a CairoContract object or a string representation of the contract. + * @return {boolean} - Returns true if the contract is a Sierra contract, otherwise false. + */ export function isSierra( contract: CairoContract | string ): contract is SierraContractClass | CompiledSierra { @@ -20,6 +26,15 @@ export function isSierra( return 'sierra_program' in compiledContract; } +/** + * Extracts contract hashes from `DeclareContractPayload`. + * + * @param {DeclareContractPayload} payload - The payload containing contract information. + * + * @return {CompleteDeclareContractPayload} - The `CompleteDeclareContractPayload` with extracted contract hashes. + * + * @throws {Error} - If extraction of compiledClassHash or classHash fails. + */ export function extractContractHashes( payload: DeclareContractPayload ): CompleteDeclareContractPayload { diff --git a/src/utils/events/index.ts b/src/utils/events/index.ts index d6d623575..9d0b3614c 100644 --- a/src/utils/events/index.ts +++ b/src/utils/events/index.ts @@ -14,6 +14,12 @@ import responseParser from '../calldata/responseParser'; import { starkCurve } from '../ec'; import { addHexPrefix, utf8ToArray } from '../encode'; +/** + * Retrieves the events from the given ABI. + * + * @param {Abi} abi - The ABI to extract events from. + * @return {AbiEvents} - An object containing the extracted events. + */ export function getAbiEvents(abi: Abi): AbiEvents { return abi .filter((abiEntry) => abiEntry.type === 'event' && (abiEntry.size || abiEntry.kind !== 'enum')) @@ -33,6 +39,7 @@ export function getAbiEvents(abi: Abi): AbiEvents { * @param providerReceivedEvents ProviderEvent[] - Array of raw events * @param abiEvents AbiEvents - Events defined in the abi * @param abiStructs AbiStructs - Structs defined in the abi + * @param abiEnums * @return ParsedEvents - parsed events corresponding to the abi */ export function parseEvents( diff --git a/src/utils/hash/classHash.ts b/src/utils/hash/classHash.ts index ac9166eea..794892e4a 100644 --- a/src/utils/hash/classHash.ts +++ b/src/utils/hash/classHash.ts @@ -241,7 +241,13 @@ function hashEntryPointSierra(data: SierraContractEntryPointFields[]) { return poseidonHashMany(base); } -function hashAbi(sierra: CompiledSierra) { +/** + * Computes the ABI hash of a compiled `sierra` object. + * + * @param {CompiledSierra} sierra - The compiled Sierra object. + * @return {bigint} - The ABI hash as a BigInt. + */ +function hashAbi(sierra: CompiledSierra): bigint { const indentString = formatSpaces(stringify(sierra.abi, null)); return BigInt(addHexPrefix(starkCurve.keccak(utf8ToArray(indentString)).toString(16))); } diff --git a/src/utils/provider.ts b/src/utils/provider.ts index 6f10ac51d..cb6081a35 100644 --- a/src/utils/provider.ts +++ b/src/utils/provider.ts @@ -109,7 +109,14 @@ export class Block { tag: BlockIdentifier = null; - private setIdentifier(__identifier: BlockIdentifier) { + /** + * Sets the identifier of the block. + * + * @param {BlockIdentifier} __identifier - The identifier of the block. + * + * @returns {void} + */ + private setIdentifier(__identifier: BlockIdentifier): void { if (isString(__identifier)) { if (isHex(__identifier)) { this.hash = __identifier; @@ -170,11 +177,24 @@ export class Block { } */ } +/** + * Check if the given transaction details is a V3 transaction. + * + * @param {InvocationsDetailsWithNonce} details - The transaction details to be checked. + * @return {boolean} - Returns true if the transaction is a V3 transaction, otherwise false. + */ export function isV3Tx(details: InvocationsDetailsWithNonce): details is V3TransactionDetails { const version = details.version ? toHex(details.version) : ETransactionVersion.V3; return version === ETransactionVersion.V3 || version === ETransactionVersion.F3; } +/** + * Determines if the given response matches the specified version. + * + * @param {('0.5' | '0.6' | '0.7')} version - The version to compare against the response. + * @param {string} response - The response to check against the version. + * @returns {boolean} - True if the response matches the version, false otherwise. + */ export function isVersion(version: '0.5' | '0.6' | '0.7', response: string) { const [majorS, minorS] = version.split('.'); const [majorR, minorR] = response.split('.'); diff --git a/src/utils/responseParser/rpc.ts b/src/utils/responseParser/rpc.ts index 996b31a75..e8b459c7a 100644 --- a/src/utils/responseParser/rpc.ts +++ b/src/utils/responseParser/rpc.ts @@ -39,10 +39,22 @@ export class RPCResponseParser this.margin = margin; } + /** + * Converts the estimated fee to the maximum fee. + * + * @param {number} estimatedFee - The estimated fee value. + * @return {number} - The maximum fee value. + */ private estimatedFeeToMaxFee(estimatedFee: Parameters[0]) { return estimatedFeeToMaxFee(estimatedFee, this.margin?.maxFee); } + /** + * Estimate the fee within the specified bounds. + * + * @param {object} estimate - The estimate object containing the necessary parameters. + * @returns {object} - The estimated fee within the specified bounds. + */ private estimateFeeToBounds(estimate: Parameters[0]) { return estimateFeeToBounds( estimate, @@ -51,10 +63,22 @@ export class RPCResponseParser ); } + /** + * Parses the response from a "getBlock" request. + * + * @param {BlockWithTxHashes} res - The response object with block information and transaction hashes. + * @return {GetBlockResponse} - The parsed result with the status set to 'PENDING'. + */ public parseGetBlockResponse(res: BlockWithTxHashes): GetBlockResponse { return { status: 'PENDING', ...res } as GetBlockResponse; } + /** + * Parses a transaction receipt and returns a processed response. + * + * @param {TransactionReceipt} res - The transaction receipt to parse. + * @return {GetTransactionReceiptResponse} - The parsed transaction receipt. + */ public parseTransactionReceipt(res: TransactionReceipt): GetTxReceiptResponseWithoutHelper { // HOTFIX RPC 0.5 to align with RPC 0.6 // This case is RPC 0.5. It can be only v2 thx with FRI units @@ -71,6 +95,12 @@ export class RPCResponseParser return res as GetTxReceiptResponseWithoutHelper; } + /** + * Parses the response of a fee estimate request. + * + * @param {FeeEstimate[]} res - The response array of fee estimates. + * @return {EstimateFeeResponse} The parsed fee estimate response. + */ public parseFeeEstimateResponse(res: FeeEstimate[]): EstimateFeeResponse { const val = res[0]; return { @@ -85,6 +115,12 @@ export class RPCResponseParser }; } + /** + * Parses a bulk fee estimate response. + * + * @param {FeeEstimate[]} res - The array of fee estimates to parse. + * @return {EstimateFeeResponseBulk} - The parsed bulk fee estimate response. + */ public parseFeeEstimateBulkResponse(res: FeeEstimate[]): EstimateFeeResponseBulk { return res.map((val) => ({ overall_fee: toBigInt(val.overall_fee), @@ -98,6 +134,12 @@ export class RPCResponseParser })); } + /** + * Parses the simulate transaction response. + * + * @param {any} res - The simulate transaction response. + * @returns {SimulateTransactionResponse} - The parsed simulate transaction response. + */ public parseSimulateTransactionResponse( // TODO: revisit // set as 'any' to avoid a mapped type circular recursion error stemming from @@ -115,6 +157,12 @@ export class RPCResponseParser }); } + /** + * Parses the contract class response. + * + * @param {ContractClassPayload} res - The response payload to parse. + * @return {ContractClassResponse} - The parsed contract class response. + */ public parseContractClassResponse(res: ContractClassPayload): ContractClassResponse { return { ...(res as ContractClassResponse), diff --git a/src/utils/stark.ts b/src/utils/stark.ts index 65955fc6b..28e295d81 100644 --- a/src/utils/stark.ts +++ b/src/utils/stark.ts @@ -104,6 +104,21 @@ export function estimatedFeeToMaxFee( return addPercent(estimatedFee, overhead); } +/** + * Calculates the maximum resource bounds for fee estimation. + * + * @param {FeeEstimate|0n} estimate - The estimate for the fee. If a BigInt is provided, + * the returned bounds will be set to '0x0'. + * @param {number} [amountOverhead=feeMarginPercentage.L1_BOUND_MAX_AMOUNT] - The percentage + * overhead added to + * the gas consumed or + * overall fee amount. + * @param {number} [priceOverhead=feeMarginPercentage.L1_BOUND_MAX_PRICE_PER_UNIT] - The percentage + * overhead added to + * the gas price per unit. + * @throws {Error} If the estimate object is undefined or does not have the required properties. + * @returns {ResourceBounds} The maximum resource bounds for fee estimation. + */ export function estimateFeeToBounds( estimate: FeeEstimate | 0n, amountOverhead: number = feeMarginPercentage.L1_BOUND_MAX_AMOUNT, @@ -131,6 +146,13 @@ export function estimateFeeToBounds( }; } +/** + * Converts the data availability mode from EDataAvailabilityMode to EDAMode. + * + * @param {EDataAvailabilityMode} dam - The data availability mode to be converted. + * @return {EDAMode} The converted data availability mode. + * @throws {Error} If the data availability mode is not a valid value. + */ export function intDAM(dam: EDataAvailabilityMode) { if (dam === EDataAvailabilityMode.L1) return EDAMode.L1; if (dam === EDataAvailabilityMode.L2) return EDAMode.L2; diff --git a/src/utils/starknetId.ts b/src/utils/starknetId.ts index b8f5e0c70..147533a97 100644 --- a/src/utils/starknetId.ts +++ b/src/utils/starknetId.ts @@ -11,6 +11,11 @@ const basicAlphabetSize = BigInt(basicAlphabet.length); const bigAlphabetSize = BigInt(bigAlphabet.length); const bigAlphabetSizePlusOne = BigInt(bigAlphabet.length + 1); +/** + * Extracts stars from a given string and returns the modified string and the number of stars extracted. + * @param {string} str - The input string from which to extract stars. + * @returns {[string, number]} - An array containing the modified string and the number of stars extracted. + */ function extractStars(str: string): [string, number] { let k = 0; while (str.endsWith(bigAlphabet[bigAlphabet.length - 1])) { @@ -20,6 +25,11 @@ function extractStars(str: string): [string, number] { return [str, k]; } +/** + * Decodes an array of BigInts into a string using the given algorithm. + * @param {bigint[]} encoded - The encoded array of BigInts. + * @return {string} The decoded string. + */ export function useDecoded(encoded: bigint[]): string { let decoded = ''; @@ -61,6 +71,12 @@ export function useDecoded(encoded: bigint[]): string { return decoded.concat('stark'); } +/** + * Encodes a string into a bigint value. + * + * @param {string} decoded - The string to be encoded. + * @returns {bigint} - The encoded bigint value. + */ export function useEncoded(decoded: string): bigint { let encoded = BigInt(0); let multiplier = BigInt(1); @@ -109,6 +125,13 @@ export const enum StarknetIdContract { TESTNET_SEPOLIA = '0x0707f09bc576bd7cfee59694846291047e965f4184fe13dac62c56759b3b6fa7', } +/** + * Returns the Starknet ID contract address based on the provided chain ID. + * + * @param {StarknetChainId} chainId - The chain ID of the Starknet network. + * @return {string} The Starknet ID contract address. + * @throws {Error} Throws an error if the Starknet ID contract is not deployed on the network. + */ export function getStarknetIdContract(chainId: StarknetChainId): string { switch (chainId) { case StarknetChainId.SN_MAIN: @@ -131,6 +154,15 @@ export const enum StarknetIdIdentityContract { TESTNET_SEPOLIA = '0x070DF8B4F5cb2879f8592849fA8f3134da39d25326B8558cc9C8FE8D47EA3A90', } +/** + * Returns the Starknet ID identity contract address for the given chain ID. + * + * @param {StarknetChainId} chainId - The chain ID for the specified network. + * + * @return {string} - The Starknet ID identity contract address for the specified network. + * + * @throws {Error} - If the Starknet ID verifier contract is not deployed on the network. + */ export function getStarknetIdIdentityContract(chainId: StarknetChainId): string { switch (chainId) { case StarknetChainId.SN_MAIN: @@ -150,6 +182,13 @@ export function getStarknetIdIdentityContract(chainId: StarknetChainId): string export const StarknetIdMulticallContract = '0x034ffb8f4452df7a613a0210824d6414dbadcddce6c6e19bf4ddc9e22ce5f970'; +/** + * Returns the Starknet.id multicall contract address based on the provided chainId. + * + * @param {StarknetChainId} chainId - The chainId of the network. + * @return {string} - The address of the Starknet.id multicall contract. + * @throws {Error} - If the Starknet.id multicall contract is not deployed on the network. + */ export function getStarknetIdMulticallContract(chainId: StarknetChainId): string { switch (chainId) { case StarknetChainId.SN_MAIN: @@ -172,6 +211,13 @@ export const enum StarknetIdVerifierContract { TESTNET_SEPOLIA = '0x0182EcE8173C216A395f4828e1523541b7e3600bf190CB252E1a1A0cE219d184', } +/** + * Returns the address of the Starknet ID Verifier contract based on the specified chain ID. + * + * @param {StarknetChainId} chainId - The ID of the Starknet chain. + * @return {string} - The address of the Starknet ID Verifier contract. + * @throws {Error} - If the Starknet ID Verifier contract is not deployed on the specified network. + */ export function getStarknetIdVerifierContract(chainId: StarknetChainId): string { switch (chainId) { case StarknetChainId.SN_MAIN: @@ -194,6 +240,13 @@ export const enum StarknetIdPfpContract { TESTNET_SEPOLIA = '0x058061bb6bdc501eE215172c9f87d557C1E0f466dC498cA81b18f998Bf1362b2', } +/** + * Retrieves the contract address of the Starknet.id profile picture verifier contract based on the given chain ID. + * + * @param {StarknetChainId} chainId - The chain ID of the network. + * @returns {string} - The contract address of the Starknet.id profile picture verifier contract. + * @throws {Error} - Throws an error if the Starknet.id profile picture verifier contract is not yet deployed on the network. + */ export function getStarknetIdPfpContract(chainId: StarknetChainId): string { switch (chainId) { case StarknetChainId.SN_MAIN: @@ -218,6 +271,13 @@ export const enum StarknetIdPopContract { TESTNET_SEPOLIA = '0x0023FE3b845ed5665a9eb3792bbB17347B490EE4090f855C1298d03BB5F49B49', } +/** + * Retrieves the Starknet ID Proof of Personhood (IdPop) verifier contract address for the given chain ID. + * + * @param {StarknetChainId} chainId - The chain ID of the Starknet network. + * @return {string} - The Starknet ID Pop contract address. + * @throws {Error} - If the Starknet ID Pop contract is not deployed on the specified network. + */ export function getStarknetIdPopContract(chainId: StarknetChainId): string { switch (chainId) { case StarknetChainId.SN_MAIN: @@ -236,7 +296,15 @@ export function getStarknetIdPopContract(chainId: StarknetChainId): string { } } -// Functions to build CairoCustomEnum for multicall contracts +/** + * Executes a method and returns a CairoCustomEnum object. + * + * Functions to build CairoCustomEnum for multicall contracts + * @param {Object} staticEx - An optional object defining the "Static" value of the CairoCustomEnum. + * @param {number[]} ifEqual - An optional array defining the "IfEqual" value of the CairoCustomEnum. + * @param {number[]} ifNotEqual - An optional array defining the "IfNotEqual" value of the CairoCustomEnum. + * @return {CairoCustomEnum} - The created CairoCustomEnum object. + */ export function execution( staticEx: {} | undefined, ifEqual: number[] | undefined = undefined, @@ -249,6 +317,13 @@ export function execution( }); } +/** + * Creates a new instance of CairoCustomEnum. + * + * @param {BigNumberish | undefined} hardcoded - The hardcoded value for the CairoCustomEnum. + * @param {number[] | undefined} reference - The reference array for the CairoCustomEnum. + * @returns {CairoCustomEnum} The new instance of CairoCustomEnum. + */ export function dynamicFelt( hardcoded: BigNumberish | undefined, reference: number[] | undefined = undefined @@ -259,6 +334,13 @@ export function dynamicFelt( }); } +/** + * Creates a new instance of CairoCustomEnum with the given parameters. + * @param {BigNumberish | undefined} hardcoded - The hardcoded value. + * @param {BigNumberish[] | undefined} [reference] - The reference value (optional). + * @param {BigNumberish[] | undefined} [arrayReference] - The array reference value (optional). + * @return {CairoCustomEnum} - The new instance of CairoCustomEnum. + */ export function dynamicCallData( hardcoded: BigNumberish | undefined, reference: BigNumberish[] | undefined = undefined, diff --git a/src/utils/transaction.ts b/src/utils/transaction.ts index 2daf8da92..308290223 100644 --- a/src/utils/transaction.ts +++ b/src/utils/transaction.ts @@ -98,6 +98,14 @@ export const getExecuteCalldata = (calls: Call[], cairoVersion: CairoVersion = ' return fromCallsToExecuteCalldata(calls); }; +/** + * Builds a UDCCall object. + * + * @param {UniversalDeployerContractPayload | UniversalDeployerContractPayload[]} payload - The payload data for the UDCCall. Can be a single payload object or an array of payload objects + *. + * @param {string} address - The address to be used in the UDCCall. + * @returns {{ calls: Array, addresses: Array }} - The UDCCall object containing an array of calls and an array of addresses. + */ export function buildUDCCall( payload: UniversalDeployerContractPayload | UniversalDeployerContractPayload[], address: string diff --git a/src/utils/typedData.ts b/src/utils/typedData.ts index 9a62b06b5..18ca08240 100644 --- a/src/utils/typedData.ts +++ b/src/utils/typedData.ts @@ -103,10 +103,23 @@ function validateTypedData(data: unknown): data is TypedData { ); } +/** + * Prepares the selector for use. + * + * @param {string} selector - The selector to be prepared. + * @returns {string} The prepared selector. + */ export function prepareSelector(selector: string): string { return isHex(selector) ? selector : getSelectorFromName(selector); } +/** + * Checks if the given Starknet type is a Merkle tree type. + * + * @param {StarknetType} type - The StarkNet type to check. + * + * @returns {boolean} - True if the type is a Merkle tree type, false otherwise. + */ export function isMerkleTreeType(type: StarknetType): type is StarknetMerkleType { return type.type === 'merkletree'; } diff --git a/src/utils/url.ts b/src/utils/url.ts index e18c4da08..9f1bb47ce 100644 --- a/src/utils/url.ts +++ b/src/utils/url.ts @@ -46,6 +46,14 @@ export function isUrl(s?: string): boolean { return false; } +/** + * Builds a URL using the provided base URL, default path, and optional URL or path. + * + * @param {string} baseUrl - The base URL of the URL being built. + * @param {string} defaultPath - The default path to use if no URL or path is provided. + * @param {string} [urlOrPath] - The optional URL or path to append to the base URL. + * @return {string} The built URL. + */ export function buildUrl(baseUrl: string, defaultPath: string, urlOrPath?: string) { return isUrl(urlOrPath) ? urlOrPath! : urljoin(baseUrl, urlOrPath ?? defaultPath); } diff --git a/src/wallet/account.ts b/src/wallet/account.ts index 9bc7616cc..cef733a97 100644 --- a/src/wallet/account.ts +++ b/src/wallet/account.ts @@ -115,7 +115,10 @@ export class WalletAccount extends Account implements AccountInterface { } /** - * ACCOUNT METHODS + * Executes a batch of calls on a smart contract. + * + * @param {AllowArray} calls - The array of calls to execute on the smart contract. + * @returns - A promise that resolves with the result of the execution. */ override execute(calls: AllowArray) { const txCalls = [].concat(calls as any).map((it) => { @@ -134,6 +137,13 @@ export class WalletAccount extends Account implements AccountInterface { return addInvokeTransaction(this.walletProvider, params); } + /** + * Overrides the declare method. + * + * @param {DeclareContractPayload} payload - The payload for declaring a contract. + * @return {Promise} - A promise that resolves with the transaction object. + * @throws {Error} - Throws an error if compiledClassHash is missing. + */ override declare(payload: DeclareContractPayload) { const declareContractPayload = extractContractHashes(payload); @@ -157,6 +167,12 @@ export class WalletAccount extends Account implements AccountInterface { return addDeclareTransaction(this.walletProvider, params); } + /** + * Deploys a contract or multiple contracts using the UniversalDeployer. + * + * @param {UniversalDeployerContractPayload | UniversalDeployerContractPayload[]} payload - The contract payload(s) to be deployed. + * @return {Promise} - The response object containing the result of the deployment. + */ override async deploy( payload: UniversalDeployerContractPayload | UniversalDeployerContractPayload[] ): Promise { @@ -169,6 +185,16 @@ export class WalletAccount extends Account implements AccountInterface { }; } + /** + * Deploys an account for a contract. + * + * @param {DeployAccountContractPayload} payload - The payload containing the necessary data for deployment. + * @param {string} payload.addressSalt - Optional. The address salt for the contract. Defaults to '0'. + * @param {string} payload.constructorCalldata - The constructor calldata for the contract. + * @param {string} payload.classHash - The class hash of the contract. + * + * @return - A promise that resolves when the account deployment is complete. + */ override deployAccount(payload: DeployAccountContractPayload) { const params = { contract_address_salt: payload.addressSalt?.toString() || '0', @@ -181,6 +207,12 @@ export class WalletAccount extends Account implements AccountInterface { return addDeployAccountTransaction(this.walletProvider, params); } + /** + * Signs the given message using the wallet provider. + * + * @param {TypedData} typedData - The typed data to be signed. + * @return - A promise that resolves with the signed message. + */ override signMessage(typedData: TypedData) { return signMessage(this.walletProvider, typedData); } diff --git a/src/wallet/connect.ts b/src/wallet/connect.ts index 02a50da7a..68f24dc22 100644 --- a/src/wallet/connect.ts +++ b/src/wallet/connect.ts @@ -153,10 +153,32 @@ export function supportedSpecs(swo: StarknetWindowObject) { return swo.request({ type: 'starknet_supportedSpecs' }); } -export function onAccountChange(swo: StarknetWindowObject, callback: AccountChangeEventHandler) { +/** + * Attaches an event handler function to the "accountsChanged" event of a StarknetWindowObject. + * When the accounts are changed, the specified callback function will be called. + * + * @param {StarknetWindowObject} swo - The StarknetWindowObject to attach the event handler to. + * @param {AccountChangeEventHandler} callback - The function to be called when the accounts are changed. + * It will receive the changed accounts as a parameter. + * @returns {void} + */ +export function onAccountChange( + swo: StarknetWindowObject, + callback: AccountChangeEventHandler +): void { swo.on('accountsChanged', callback); } -export function onNetworkChanged(swo: StarknetWindowObject, callback: NetworkChangeEventHandler) { +/** + * Register a callback function to be called when the network is changed. + * + * @param {StarknetWindowObject} swo - The StarknetWindowObject instance. + * @param {NetworkChangeEventHandler} callback - The callback function to be called when the network is changed. + * @return {void} + */ +export function onNetworkChanged( + swo: StarknetWindowObject, + callback: NetworkChangeEventHandler +): void { swo.on('networkChanged', callback); } From 72d4edc28e99de5ff1d27cf47e4b29f9cbf884a0 Mon Sep 17 00:00:00 2001 From: Ivan Krcatovic Date: Thu, 18 Apr 2024 14:59:51 +0200 Subject: [PATCH 2/8] removed override, and non exported method comments --- src/channel/rpc_0_6.ts | 192 -------------------------- src/provider/extensions/starknetId.ts | 59 -------- src/signer/default.ts | 6 - src/signer/ethSigner.ts | 27 ---- src/utils/calldata/propertyOrder.ts | 41 ------ src/utils/calldata/requestParser.ts | 6 - src/utils/calldata/tuple.ts | 34 ----- src/utils/calldata/validate.ts | 73 ---------- src/utils/hash/classHash.ts | 8 +- src/utils/provider.ts | 7 - src/utils/responseParser/rpc.ts | 48 ------- src/wallet/account.ts | 34 +---- 12 files changed, 2 insertions(+), 533 deletions(-) diff --git a/src/channel/rpc_0_6.ts b/src/channel/rpc_0_6.ts index 2281085b4..f89ce7eff 100644 --- a/src/channel/rpc_0_6.ts +++ b/src/channel/rpc_0_6.ts @@ -71,26 +71,10 @@ export class RpcChannel { this.requestId = 0; } - /** - * Sets the chain ID for the Starknet. - * - * @param {StarknetChainId} chainId - The chain ID to be set. - * - * @return - */ public setChainId(chainId: StarknetChainId) { this.chainId = chainId; } - /** - * Fetches data from a remote server using the provided method, parameters, and ID. - * - * @param {string} method - The method to be called on the remote server. - * @param {?object} params - Optional parameters to be passed to the remote server. - * @param {string|number} id - The ID to identify the request. Default value is 0. - * - * @return - A Promise that resolves to the Response object representing the fetched data. - */ public fetch(method: string, params?: object, id: string | number = 0) { const rpcRequestBody: JRPC.RequestBody = { id, @@ -105,17 +89,6 @@ export class RpcChannel { }); } - /** - * Handles errors in the software library. - * - * @param {string} method - The name of the method that encountered the error. - * @param {any} params - The parameters passed to the method. - * @param {JRPC.Error} [rpcError] - The error object returned by the remote procedure call. Defaults to undefined. - * @param {any} [otherError] - Any other error object encountered. Defaults to undefined. - * @throws {LibraryError} - If rpcError is provided, it throws a LibraryError with the error code, message, and data. - * @throws {LibraryError} - If otherError instance is provided, it throws the same LibraryError. - * @throws {Error} - If otherError is provided, it throws a generic Error with the error message. - */ protected errorHandler(method: string, params: any, rpcError?: JRPC.Error, otherError?: any) { if (rpcError) { const { code, message, data } = rpcError; @@ -132,14 +105,6 @@ export class RpcChannel { } } - /** - * Fetches data from the specified API endpoint. - * - * @param method - The method name of the API endpoint. - * @param params - Optional parameters for the API endpoint. - * @returns A Promise that resolves to the result of the API endpoint. - * @throws If an error occurs during the fetch operation. - */ protected async fetchEndpoint( method: T, params?: RPC.Methods[T]['params'] @@ -155,35 +120,16 @@ export class RpcChannel { } } - /** - * Retrieves the chain ID from the Starknet endpoint. - * If the chain ID has already been fetched, it returns the cached value. - * - * @returns - A promise that resolves to the chain ID. - */ public async getChainId() { this.chainId ??= (await this.fetchEndpoint('starknet_chainId')) as StarknetChainId; return this.chainId; } - /** - * Returns the version of the Starknet JSON-RPC specification being used - * - * @returns - A Promise that resolves with the spec version of the Starknet chain. - */ public async getSpecVersion() { this.specVersion ??= (await this.fetchEndpoint('starknet_specVersion')) as StarknetChainId; return this.specVersion; } - /** - * Retrieves the nonce for a given contract address and block identifier. - * - * @param {BigNumberish} contractAddress - The contract address to retrieve the nonce for. - * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The block identifier to retrieve the nonce from (optional, defaults to this.blockIdentifier). - * - * @return - A promise that resolves to the nonce value. - */ public getNonceForAddress( contractAddress: BigNumberish, blockIdentifier: BlockIdentifier = this.blockIdentifier @@ -212,68 +158,31 @@ export class RpcChannel { return this.fetchEndpoint('starknet_blockNumber'); } - /** - * Retrieves a block with transaction hashes. - * - * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The identifier of the block to retrieve. - * @return {Promise} - A promise that resolves with the block containing transaction hashes. - */ public getBlockWithTxHashes(blockIdentifier: BlockIdentifier = this.blockIdentifier) { const block_id = new Block(blockIdentifier).identifier; return this.fetchEndpoint('starknet_getBlockWithTxHashes', { block_id }); } - /** - * Retrieves a block with its transactions. - * - * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The identifier of the block to retrieve. Defaults to the current block identifier. - * @return {Promise} A promise that resolves to the block with its transactions. - */ public getBlockWithTxs(blockIdentifier: BlockIdentifier = this.blockIdentifier) { const block_id = new Block(blockIdentifier).identifier; return this.fetchEndpoint('starknet_getBlockWithTxs', { block_id }); } - /** - * Retrieve the state update for a given block. - * - * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The identifier of the block to retrieve the state update for. - * @return {Promise} - A promise that resolves with the state update of the specified block. - */ public getBlockStateUpdate(blockIdentifier: BlockIdentifier = this.blockIdentifier) { const block_id = new Block(blockIdentifier).identifier; return this.fetchEndpoint('starknet_getStateUpdate', { block_id }); } - /** - * Fetches the transaction traces for a given block identifier. - * - * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The block identifier. - * @returns {Promise} - A promise that resolves with an array of transaction traces. - */ public getBlockTransactionsTraces(blockIdentifier: BlockIdentifier = this.blockIdentifier) { const block_id = new Block(blockIdentifier).identifier; return this.fetchEndpoint('starknet_traceBlockTransactions', { block_id }); } - /** - * Retrieves the number of transactions in a given block. - * - * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The identifier of the block. Defaults to the current block identifier. - * - * @return {Promise} - A Promise that resolves to the number of transactions in the block. - */ public getBlockTransactionCount(blockIdentifier: BlockIdentifier = this.blockIdentifier) { const block_id = new Block(blockIdentifier).identifier; return this.fetchEndpoint('starknet_getBlockTransactionCount', { block_id }); } - /** - * Fetches transaction details by its hash. - * - * @param {BigNumberish} txHash - The hash of the transaction. - * @returns {Promise} - A promise that resolves with the transaction details. - */ public getTransactionByHash(txHash: BigNumberish) { const transaction_hash = toHex(txHash); return this.fetchEndpoint('starknet_getTransactionByHash', { @@ -281,35 +190,16 @@ export class RpcChannel { }); } - /** - * Retrieves a transaction from the StarkNet blockchain by its block identifier and index. - * - * @param {BlockIdentifier} blockIdentifier - The identifier of the block containing the transaction. - * @param {number} index - The index of the transaction within the block. - * @return {Promise} - A Promise that resolves to the requested transaction object. - */ public getTransactionByBlockIdAndIndex(blockIdentifier: BlockIdentifier, index: number) { const block_id = new Block(blockIdentifier).identifier; return this.fetchEndpoint('starknet_getTransactionByBlockIdAndIndex', { block_id, index }); } - /** - * Retrieves the transaction receipt for a given transaction hash. - * - * @param {BigNumberish} txHash - The transaction hash to retrieve the receipt for. - * @return {Promise} A promise that resolves with the transaction receipt object. - */ public getTransactionReceipt(txHash: BigNumberish) { const transaction_hash = toHex(txHash); return this.fetchEndpoint('starknet_getTransactionReceipt', { transaction_hash }); } - /** - * Retrieves the transaction trace for a given transaction hash. - * - * @param {BigNumberish} txHash - The transaction hash to fetch the trace for. - * @returns {Promise} - The transaction trace object. - */ public getTransactionTrace(txHash: BigNumberish) { const transaction_hash = toHex(txHash); return this.fetchEndpoint('starknet_traceTransaction', { transaction_hash }); @@ -317,9 +207,6 @@ export class RpcChannel { /** * Get the status of a transaction - * - * @param {BigNumberish} transactionHash - The hash of the transaction. - * @return {Promise} - A promise that resolves to the transaction status object. */ public getTransactionStatus(transactionHash: BigNumberish) { const transaction_hash = toHex(transactionHash); @@ -353,15 +240,6 @@ export class RpcChannel { }); } - /** - * Asynchronously waits for a transaction to be confirmed on the blockchain. - * - * @param {BigNumberish} txHash - The transaction hash to wait for. - * @param {waitForTransactionOptions} [options] - Optional parameters for the method. - * @return {Promise} - A promise that resolves with the transaction receipt. - * @throws {Error} - If the transaction is rejected or encounters an error. - * @throws {Error} - If the maximum number of retries is reached. - */ public async waitForTransaction(txHash: BigNumberish, options?: waitForTransactionOptions) { const transactionHash = toHex(txHash); let { retries } = this; @@ -444,15 +322,6 @@ export class RpcChannel { return txReceipt as RPC.SPEC.TXN_RECEIPT; } - /** - * Retrieves the storage value at the specified key for a given contract address and block identifier. - * - * @param {BigNumberish} contractAddress - The address of the contract. - * @param {BigNumberish} key - The key to retrieve the storage value from. - * @param {BlockIdentifier} [blockIdentifier] - The identifier of the block. Defaults to the current block identifier. - * - * @return {Promise} - A promise resolving to the storage value at the specified key. - */ public getStorageAt( contractAddress: BigNumberish, key: BigNumberish, @@ -468,13 +337,6 @@ export class RpcChannel { }); } - /** - * Gets the class hash of a contract at a given block. - * - * @param {BigNumberish} contractAddress - The contract address. - * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The block identifier. - * @returns {Promise} - A Promise that resolves with the class hash of the contract at the given block. - */ public getClassHashAt( contractAddress: BigNumberish, blockIdentifier: BlockIdentifier = this.blockIdentifier @@ -487,13 +349,6 @@ export class RpcChannel { }); } - /** - * Retrieves the class information for the given class hash. - * - * @param {BigNumberish} classHash - The hash of the class. - * @param {BlockIdentifier} [blockIdentifier] - The block identifier. Default value is set to 'this.blockIdentifier'. - * @returns {Promise} - A promise that resolves to the class information object. - */ public getClass( classHash: BigNumberish, blockIdentifier: BlockIdentifier = this.blockIdentifier @@ -506,13 +361,6 @@ export class RpcChannel { }); } - /** - * Retrieves the class at the specified contract address and block identifier. - * - * @param {BigNumberish} contractAddress - The address of the contract. - * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The block identifier. - * @return {Promise} - A promise that resolves with the class information. - */ public getClassAt( contractAddress: BigNumberish, blockIdentifier: BlockIdentifier = this.blockIdentifier @@ -525,16 +373,6 @@ export class RpcChannel { }); } - /** - * Retrieves the estimated fee for a given set of account invocations. - * - * @param {AccountInvocations} invocations - The list of account invocations. - * @param {getEstimateFeeBulkOptions} options - The options for getting estimated fee. - * - blockIdentifier: The identifier of the block to use. Default is the current block identifier. - * - skipValidate: A flag indicating whether to skip validation. Default is true. - * - * @return {Promise} - The estimated fee. - */ public async getEstimateFee( invocations: AccountInvocations, { blockIdentifier = this.blockIdentifier, skipValidate = true }: getEstimateFeeBulkOptions @@ -554,13 +392,6 @@ export class RpcChannel { }); } - /** - * Invokes a function on a contract. - * - * @param {Invocation} functionInvocation - The function invocation details. - * @param {InvocationsDetailsWithNonce} details - The transaction details. - * @returns {Promise} - A promise that resolves to the transaction hash or the transaction object. - */ public async invoke(functionInvocation: Invocation, details: InvocationsDetailsWithNonce) { let promise; if (!isV3Tx(details)) { @@ -599,14 +430,6 @@ export class RpcChannel { return this.waitMode ? this.waitForTransaction((await promise).transaction_hash) : promise; } - /** - * Declares a contract transaction on the StarkNet blockchain. - * - * @param {DeclareContractTransaction} transaction - The transaction details. - * @param {InvocationsDetailsWithNonce} details - The details of the transaction invocations. - * @throws {Error} If the parameters of the transaction are incorrect. - * @returns {Promise} A promise that resolves to the transaction hash. - */ public async declare( { contract, signature, senderAddress, compiledClassHash }: DeclareContractTransaction, details: InvocationsDetailsWithNonce @@ -679,14 +502,6 @@ export class RpcChannel { return this.waitMode ? this.waitForTransaction((await promise).transaction_hash) : promise; } - /** - * Deploy an account contract transaction. - * - * @param {DeployAccountContractTransaction} deployAccountTransaction - The transaction details. - * @param {InvocationsDetailsWithNonce} details - The additional transaction details. - * - * @return {Promise} - Promise resolved with the transaction result or transaction hash if `waitMode` is enabled. - */ public async deployAccount( { classHash, constructorCalldata, addressSalt, signature }: DeployAccountContractTransaction, details: InvocationsDetailsWithNonce @@ -729,13 +544,6 @@ export class RpcChannel { return this.waitMode ? this.waitForTransaction((await promise).transaction_hash) : promise; } - /** - * Calls a contract on the StarkNet protocol. - * - * @param {Call} call - The call object representing the contract call. - * @param {BlockIdentifier} [blockIdentifier=this.blockIdentifier] - The identifier of the block to execute the contract call. - * @returns {Promise} - A promise that resolves with the result of the contract call. - */ public callContract(call: Call, blockIdentifier: BlockIdentifier = this.blockIdentifier) { const block_id = new Block(blockIdentifier).identifier; return this.fetchEndpoint('starknet_call', { diff --git a/src/provider/extensions/starknetId.ts b/src/provider/extensions/starknetId.ts index 7288086ed..1c9848ee5 100644 --- a/src/provider/extensions/starknetId.ts +++ b/src/provider/extensions/starknetId.ts @@ -18,13 +18,6 @@ import { import type { ProviderInterface } from '..'; export class StarknetId { - /** - * Retrieves the Stark name associated with a specific address. - * - * @param {BigNumberish} address - The address to query the Stark name for. - * @param {string} [StarknetIdContract] - The Starknet ID contract address. Optional. - * @returns {Promise} - A Promise that resolves to the Stark name associated with the address. - */ async getStarkName(address: BigNumberish, StarknetIdContract?: string) { return StarknetId.getStarkName( // After Mixin, this is ProviderInterface @@ -34,14 +27,6 @@ export class StarknetId { ); } - /** - * Retrieves the address associated with a given Stark name. - * - * @param {string} name - The Stark name. - * @param {string} [StarknetIdContract] - The contract address of the StarknetId smart contract. - * - * @returns {Promise} - The address associated with the Stark name. - */ public async getAddressFromStarkName(name: string, StarknetIdContract?: string): Promise { return StarknetId.getAddressFromStarkName( // After Mixin, this is ProviderInterface @@ -51,18 +36,6 @@ export class StarknetId { ); } - /** - * Retrieves the Stark profile for a given address. - * - * @param {BigNumberish} address - The address for which to retrieve the Stark profile. - * @param {string} [StarknetIdContract] - The address of the StarknetId contract. - * @param {string} [StarknetIdIdentityContract] - The address of the StarknetIdIdentity contract. - * @param {string} [StarknetIdVerifierContract] - The address of the StarknetIdVerifier contract. - * @param {string} [StarknetIdPfpContract] - The address of the StarknetIdPfp contract. - * @param {string} [StarknetIdPopContract] - The address of the StarknetIdPop contract. - * @param {string} [StarknetIdMulticallContract] - The address of the StarknetIdMulticall contract. - * @returns {Promise} A Promise that resolves to the Stark profile. - */ async getStarkProfile( address: BigNumberish, StarknetIdContract?: string, @@ -85,15 +58,6 @@ export class StarknetId { ); } - /** - * Retrieves the Starkname associated with a given Ethereum address. - * - * @param {ProviderInterface} provider - The provider interface. - * @param {BigNumberish} address - The Ethereum address. - * @param {string} [StarknetIdContract] - The address of the Starknet Id contract. If not provided, it will be derived based on the chainId. - * @returns {Promise} - The Starkname associated with the given Ethereum address. - * @throws {Error} - If the Starkname is not found or if an error occurred while retrieving the Starkname. - */ static async getStarkName( provider: ProviderInterface, address: BigNumberish, @@ -127,15 +91,6 @@ export class StarknetId { } } - /** - * Retrieves the address associated with a Stark name. - * - * @param {ProviderInterface} provider - The provider to use for interacting with the blockchain. - * @param {string} name - The Stark name to retrieve the address for. - * @param {string} [StarknetIdContract] - The address of the StarknetId contract. If not provided, it will be retrieved based on the chain Id. - * @returns {Promise} - The address associated with the Stark name. - * @throws {Error} - If the address cannot be retrieved. - */ static async getAddressFromStarkName( provider: ProviderInterface, name: string, @@ -162,20 +117,6 @@ export class StarknetId { } } - /** - * Retrieves the Stark Profile of a user using their Ethereum address. - * - * @param {ProviderInterface} provider - The provider interface used to communicate with the blockchain. - * @param {BigNumberish} address - The Ethereum address of the user. - * @param {string} [StarknetIdContract] - The contract address of the Starknet ID contract. - * @param {string} [StarknetIdIdentityContract] - The contract address of the Starknet ID Identity contract. - * @param {string} [StarknetIdVerifierContract] - The contract address of the Starknet ID Verifier contract. - * @param {string} [StarknetIdPfpContract] - The contract address of the Starknet ID Pfp contract. - * @param {string} [StarknetIdPopContract] - The contract address of the Starknet ID Proof-of-Personhood contract. - * @param {string} [StarknetIdMulticallContract] - The contract address of the Starknet ID Multicall contract. - * @returns {Promise} - The Stark Profile of the user, including their name, social media accounts, proof-of-personhood status, and profile picture. - * @throws {Error} - If there was an error while retrieving the Stark Profile. - */ static async getStarkProfile( provider: ProviderInterface, address: BigNumberish, diff --git a/src/signer/default.ts b/src/signer/default.ts index 94171c025..1915c8274 100644 --- a/src/signer/default.ts +++ b/src/signer/default.ts @@ -135,12 +135,6 @@ export class Signer implements SignerInterface { return this.signRaw(msgHash as string); } - /** - * Signs a raw message hash using the `starkCurve` and the provided private key. - * - * @param {string} msgHash - The raw message hash to sign. - * @returns {Promise} - A Promise that resolves to the generated signature. - */ protected async signRaw(msgHash: string): Promise { return starkCurve.sign(msgHash, this.pk); } diff --git a/src/signer/ethSigner.ts b/src/signer/ethSigner.ts index afe429b3a..d54dcd23e 100644 --- a/src/signer/ethSigner.ts +++ b/src/signer/ethSigner.ts @@ -56,12 +56,6 @@ export class EthSigner implements SignerInterface { ); } - /** - * Signs the provided message with the given account address. - * @param {TypedData} typedData - The message data to be signed. - * @param {string} accountAddress - The address of the signing account. - * @return {Promise} - The signature of the message. - */ public async signMessage(typedData: TypedData, accountAddress: string): Promise { const msgHash = getMessageHash(typedData, accountAddress); const signature: RecoveredSignatureType = secp256k1.sign( @@ -71,14 +65,6 @@ export class EthSigner implements SignerInterface { return this.formatEthSignature(signature); } - /** - * Signs a transaction using the provided transactions and details. - * - * @param {Call[]} transactions - The transactions to be signed. - * @param {InvocationsSignerDetails} details - The details needed for signing. - * @return {Promise} - The signed transaction. - * @throws {Error} - Throws an error if the signTransaction version is unsupported. - */ public async signTransaction( transactions: Call[], details: InvocationsSignerDetails @@ -115,12 +101,6 @@ export class EthSigner implements SignerInterface { return this.formatEthSignature(signature); } - /** - * Signs a deploy account transaction. - * @param {DeployAccountSignerDetails} details - The details of the deploy account transaction. - * @return {Promise} - The signature of the signed transaction. - * @throws {Error} - If the version of the deploy account transaction is not supported. - */ public async signDeployAccountTransaction( details: DeployAccountSignerDetails ): Promise { @@ -156,13 +136,6 @@ export class EthSigner implements SignerInterface { return this.formatEthSignature(signature); } - /** - * Signs a declare transaction. - * - * @param {DeclareSignerDetails} details - The details of the declare transaction. - * @returns {Promise} - The signature of the declare transaction. - * @throws {Error} - If the version of the declare transaction is unsupported. - */ public async signDeclareTransaction( // contractClass: ContractClass, // Should be used once class hash is present in ContractClass details: DeclareSignerDetails diff --git a/src/utils/calldata/propertyOrder.ts b/src/utils/calldata/propertyOrder.ts index bdc7cb32c..27e8d449f 100644 --- a/src/utils/calldata/propertyOrder.ts +++ b/src/utils/calldata/propertyOrder.ts @@ -26,11 +26,6 @@ import extractTupleMemberTypes from './tuple'; import { isString } from '../shortString'; -/** - * Creates a new Error object indicating that the provided key in the object includes an Uint256 object without the 'low' and 'high' keys. - * @param {string} key - The key indicating the property in the object. - * @return - The Error object indicating the missing 'low' and 'high' keys. - */ function errorU256(key: string) { return Error( `Your object includes the property : ${key}, containing an Uint256 object without the 'low' and 'high' keys.` @@ -49,13 +44,6 @@ export default function orderPropsByAbi( structs: AbiStructs, enums: AbiEnums ): object { - /** - * Orders an input item based on its ABI type. - * - * @param {any} unorderedItem - The unordered item to be ordered. - * @param {string} abiType - The ABI type of the item. - * @returns - The ordered item. - */ const orderInput = (unorderedItem: any, abiType: string): any => { if (isTypeArray(abiType)) { return orderArray(unorderedItem, abiType); @@ -108,14 +96,6 @@ export default function orderPropsByAbi( return unorderedItem; }; - /** - * Orders the properties of the input object based on the given ABI entries. - * - * @param {object} unorderedObject2 - The input object whose properties need to be ordered. - * @param {Array} abiObject - An array of ABI entries representing the desired order of properties. - * @returns - The ordered object with properties based on the given ABI entries. - * @throws {Error} If the input object is missing a required property or if a property has an invalid value. - */ const orderStruct = (unorderedObject2: RawArgsObject, abiObject: AbiEntry[]): object => { const orderedObject2 = abiObject.reduce((orderedObject, abiParam) => { const setProperty = (value?: any) => @@ -135,14 +115,6 @@ export default function orderPropsByAbi( return orderedObject2; }; - /** - * Orders the elements in the array according to the given ABI parameter. - * - * @param {Array | string} myArray - The array to be ordered. Can be either an array of any type or a string. - * @param {string} abiParam - The ABI parameter used to determine the order of the elements. - * - * @return - The ordered array or the input string if it is not an array. - */ function orderArray(myArray: Array | string, abiParam: string): Array | string { const typeInArray = getArrayType(abiParam); if (isString(myArray)) { @@ -151,13 +123,6 @@ export default function orderPropsByAbi( return myArray.map((myElem) => orderInput(myElem, typeInArray)); } - /** - * Orders the properties of the input object based on the provided ABI parameter. - * - * @param {object} unorderedObject2 - The input object with unordered properties. - * @param {string} abiParam - The ABI parameter for ordering the properties. - * @return - The ordered object with properties arranged according to ABI parameter. - */ function orderTuple(unorderedObject2: RawArgsObject, abiParam: string): object { const typeList = extractTupleMemberTypes(abiParam); const orderedObject2 = typeList.reduce((orderedObject: object, abiTypeCairoX: any, index) => { @@ -174,12 +139,6 @@ export default function orderPropsByAbi( return orderedObject2; } - /** - * Applies a specific order to the given unordered object based on the provided ABI entry. - * @param {CairoEnum} unorderedObject2 - The unordered object. - * @param {AbiEntry} abiObject - The ABI entry. - * @returns {CairoEnum} The ordered object. - */ const orderEnum = (unorderedObject2: CairoEnum, abiObject: AbiEntry): CairoEnum => { if (isTypeResult(abiObject.name)) { const unorderedResult = unorderedObject2 as CairoResult; diff --git a/src/utils/calldata/requestParser.ts b/src/utils/calldata/requestParser.ts index deeb3e943..5a4a099b0 100644 --- a/src/utils/calldata/requestParser.ts +++ b/src/utils/calldata/requestParser.ts @@ -93,12 +93,6 @@ function parseTuple(element: object, typeStr: string): Tupled[] { }); } -/** - * Parses a string representation of a byte array and returns an array of strings. - * - * @param {string} element - The string representation of the byte array. - * @return {string[]} An array of strings representing the byte array. - */ function parseByteArray(element: string): string[] { const myByteArray: ByteArray = byteArrayFromString(element); return [ diff --git a/src/utils/calldata/tuple.ts b/src/utils/calldata/tuple.ts index 3c887c6c0..263704d3e 100644 --- a/src/utils/calldata/tuple.ts +++ b/src/utils/calldata/tuple.ts @@ -1,26 +1,12 @@ /* eslint-disable no-plusplus */ import { isCairo1Type, isTypeNamedTuple } from './cairo'; -/** - * Parses a named tuple. - * - * @param {string} namedTuple - The named tuple to parse in the format "name:type". - * @returns - The parsed named tuple as an object with properties "name" and "type". - */ function parseNamedTuple(namedTuple: string): any { const name = namedTuple.substring(0, namedTuple.indexOf(':')); const type = namedTuple.substring(name.length + ':'.length); return { name, type }; } -/** - * Parses and extracts sub-tuples from a given string. - * - * @param {string} s - The input string to parse. - * @return - An object containing the sub-tuples and the remaining string. - * - subTuple: {Array} - An array of strings representing the extracted sub-tuples. - * - result: {string} - The remaining string after extracting the sub-tuples. - */ function parseSubTuple(s: string) { if (!s.includes('(')) return { subTuple: [], result: s }; const subTuple: string[] = []; @@ -51,12 +37,6 @@ function parseSubTuple(s: string) { }; } -/** - * Extracts tuples from a given type. - * - * @param {string} type - The type containing tuples. - * @returns {string[]} - An array of extracted tuples. - */ function extractCairo0Tuple(type: string) { const cleanType = type.replace(/\s/g, '').slice(1, -1); // remove first lvl () and spaces @@ -78,14 +58,6 @@ function extractCairo0Tuple(type: string) { return recomposed; } -/** - * Finds the offset at which a closure ends in a given input string. - * - * @param {string} input - The input string. - * @param {string} open - The opening closure character. - * @param {string} close - The closing closure character. - * @return {number} - The offset at which the closure ends, or Number.POSITIVE_INFINITY if no closure is found. - */ function getClosureOffset(input: string, open: string, close: string): number { for (let i = 0, counter = 0; i < input.length; i++) { if (input[i] === open) { @@ -97,12 +69,6 @@ function getClosureOffset(input: string, open: string, close: string): number { return Number.POSITIVE_INFINITY; } -/** - * Extracts individual elements from a tuple string. - * - * @param {string} type - The tuple string to extract elements from. - * @returns {string[]} - An array containing the individual elements of the tuple string. - */ function extractCairo1Tuple(type: string): string[] { // un-named tuples support const input = type.slice(1, -1); // remove first lvl () diff --git a/src/utils/calldata/validate.ts b/src/utils/calldata/validate.ts index a578c1c7a..1d6593706 100644 --- a/src/utils/calldata/validate.ts +++ b/src/utils/calldata/validate.ts @@ -33,15 +33,6 @@ import { isTypeUint, } from './cairo'; -/** - * Validates a felt parameter. - * - * @param {any} parameter - The parameter to validate. - * @param {AbiEntry} input - The input AbiEntry containing the name and type of the parameter. - * @throws {Error} Throws an error if the parameter is not a string, number, or bigint. - * @throws {Error} Throws an error if the parameter is a string but not a valid hexadecimal string. - * @throws {Error} Throws an error if the parameter is outside the range [0, 2^252 - 1]. - */ const validateFelt = (parameter: any, input: AbiEntry) => { assert( isString(parameter) || isNumber(parameter) || isBigInt(parameter), @@ -56,14 +47,6 @@ const validateFelt = (parameter: any, input: AbiEntry) => { ); }; -/** - * Validates a parameter and checks if it is a string of less than 32 characters. - * - * @param {any} parameter - The parameter to be validated. - * @param {AbiEntry} input - The ABI entry object related to the parameter. - * @returns {void} - * @throws {Error} - If the parameter is not a string or has a length greater than or equal to 32. - */ const validateBytes31 = (parameter: any, input: AbiEntry) => { assert(isString(parameter), `Validate: arg ${input.name} should be a string.`); assert( @@ -72,25 +55,10 @@ const validateBytes31 = (parameter: any, input: AbiEntry) => { ); }; -/** - * Validate a byte array parameter against a specific ABI entry. - * - * @param {any} parameter - The parameter to be validated. - * @param {AbiEntry} input - The ABI entry to validate against. - * @throws {TypeError} - If the parameter is not a string. - */ const validateByteArray = (parameter: any, input: AbiEntry) => { assert(isString(parameter), `Validate: arg ${input.name} should be a string.`); }; -/** - * Validates a given parameter against the specified Cairo type. - * - * @param {any} parameter - The parameter to be validated. - * @param {AbiEntry} input - The AbiEntry object that represents the Cairo type. - * @returns {void} - * @throws {Error} If the parameter is not of the expected type or exceeds the specified range. - */ const validateUint = (parameter: any, input: AbiEntry) => { if (isNumber(parameter)) { assert( @@ -195,13 +163,6 @@ const validateUint = (parameter: any, input: AbiEntry) => { } }; -/** - * Validates a boolean parameter against a given ABI entry. - * - * @param {any} parameter - The parameter to be validated. - * @param {AbiEntry} input - The ABI entry against which the parameter should be validated. - * @throws {AssertionError} - If the parameter is not a boolean. - */ const validateBool = (parameter: any, input: AbiEntry) => { assert( isBoolean(parameter), @@ -209,13 +170,6 @@ const validateBool = (parameter: any, input: AbiEntry) => { ); }; -/** - * Validates a struct parameter based on the input type and structure definition. - * - * @param {any} parameter - The parameter to be validated. - * @param {AbiEntry} input - The AbiEntry object that represents the struct input. - * @param {AbiStructs} structs - The AbiStructs object that contains the structure definitions. - */ const validateStruct = (parameter: any, input: AbiEntry, structs: AbiStructs) => { // c1v2 uint256 or u512 in struct if (input.type === Uint.u256 || input.type === Uint.u512) { @@ -251,13 +205,6 @@ const validateStruct = (parameter: any, input: AbiEntry, structs: AbiStructs) => }); }; -/** - * Validates if the given parameter is a valid Enum based on the input definition. - * - * @param {any} parameter - The parameter to be validated as an Enum. - * @param {AbiEntry} input - The input definition for the Enum. - * @throws {Error} If the parameter is not a valid Enum. - */ const validateEnum = (parameter: any, input: AbiEntry) => { assert( typeof parameter === 'object' && !Array.isArray(parameter), @@ -279,17 +226,6 @@ const validateEnum = (parameter: any, input: AbiEntry) => { ); }; -/** - * Validates that the given parameter is a tuple (defined as an object). - * - * @param {any} parameter - The parameter to validate. - * @param {AbiEntry} input - The input for which the validation is performed. - * @throws {AssertionError} - If the parameter is not a tuple. - * @returns - * - * @example - * validateTuple({ prop1: 'value1', prop2: 'value2' }, { name: 'param' }); - */ const validateTuple = (parameter: any, input: AbiEntry) => { assert( typeof parameter === 'object' && !Array.isArray(parameter), @@ -341,15 +277,6 @@ const validateArray = (parameter: any, input: AbiEntry, structs: AbiStructs, enu } }; -/** - * Validates the fields of the given ABI method. - * - * @param {FunctionAbi} abiMethod - The ABI method to validate. - * @param {Array} args - The arguments passed to the method. - * @param {AbiStructs} structs - The ABI structs used for validation. - * @param {AbiEnums} enums - The ABI enums used for validation. - * @throws {Error} If the validation fails. - */ export default function validateFields( abiMethod: FunctionAbi, args: Array, diff --git a/src/utils/hash/classHash.ts b/src/utils/hash/classHash.ts index 794892e4a..ac9166eea 100644 --- a/src/utils/hash/classHash.ts +++ b/src/utils/hash/classHash.ts @@ -241,13 +241,7 @@ function hashEntryPointSierra(data: SierraContractEntryPointFields[]) { return poseidonHashMany(base); } -/** - * Computes the ABI hash of a compiled `sierra` object. - * - * @param {CompiledSierra} sierra - The compiled Sierra object. - * @return {bigint} - The ABI hash as a BigInt. - */ -function hashAbi(sierra: CompiledSierra): bigint { +function hashAbi(sierra: CompiledSierra) { const indentString = formatSpaces(stringify(sierra.abi, null)); return BigInt(addHexPrefix(starkCurve.keccak(utf8ToArray(indentString)).toString(16))); } diff --git a/src/utils/provider.ts b/src/utils/provider.ts index cb6081a35..2facfe6b9 100644 --- a/src/utils/provider.ts +++ b/src/utils/provider.ts @@ -109,13 +109,6 @@ export class Block { tag: BlockIdentifier = null; - /** - * Sets the identifier of the block. - * - * @param {BlockIdentifier} __identifier - The identifier of the block. - * - * @returns {void} - */ private setIdentifier(__identifier: BlockIdentifier): void { if (isString(__identifier)) { if (isHex(__identifier)) { diff --git a/src/utils/responseParser/rpc.ts b/src/utils/responseParser/rpc.ts index e8b459c7a..996b31a75 100644 --- a/src/utils/responseParser/rpc.ts +++ b/src/utils/responseParser/rpc.ts @@ -39,22 +39,10 @@ export class RPCResponseParser this.margin = margin; } - /** - * Converts the estimated fee to the maximum fee. - * - * @param {number} estimatedFee - The estimated fee value. - * @return {number} - The maximum fee value. - */ private estimatedFeeToMaxFee(estimatedFee: Parameters[0]) { return estimatedFeeToMaxFee(estimatedFee, this.margin?.maxFee); } - /** - * Estimate the fee within the specified bounds. - * - * @param {object} estimate - The estimate object containing the necessary parameters. - * @returns {object} - The estimated fee within the specified bounds. - */ private estimateFeeToBounds(estimate: Parameters[0]) { return estimateFeeToBounds( estimate, @@ -63,22 +51,10 @@ export class RPCResponseParser ); } - /** - * Parses the response from a "getBlock" request. - * - * @param {BlockWithTxHashes} res - The response object with block information and transaction hashes. - * @return {GetBlockResponse} - The parsed result with the status set to 'PENDING'. - */ public parseGetBlockResponse(res: BlockWithTxHashes): GetBlockResponse { return { status: 'PENDING', ...res } as GetBlockResponse; } - /** - * Parses a transaction receipt and returns a processed response. - * - * @param {TransactionReceipt} res - The transaction receipt to parse. - * @return {GetTransactionReceiptResponse} - The parsed transaction receipt. - */ public parseTransactionReceipt(res: TransactionReceipt): GetTxReceiptResponseWithoutHelper { // HOTFIX RPC 0.5 to align with RPC 0.6 // This case is RPC 0.5. It can be only v2 thx with FRI units @@ -95,12 +71,6 @@ export class RPCResponseParser return res as GetTxReceiptResponseWithoutHelper; } - /** - * Parses the response of a fee estimate request. - * - * @param {FeeEstimate[]} res - The response array of fee estimates. - * @return {EstimateFeeResponse} The parsed fee estimate response. - */ public parseFeeEstimateResponse(res: FeeEstimate[]): EstimateFeeResponse { const val = res[0]; return { @@ -115,12 +85,6 @@ export class RPCResponseParser }; } - /** - * Parses a bulk fee estimate response. - * - * @param {FeeEstimate[]} res - The array of fee estimates to parse. - * @return {EstimateFeeResponseBulk} - The parsed bulk fee estimate response. - */ public parseFeeEstimateBulkResponse(res: FeeEstimate[]): EstimateFeeResponseBulk { return res.map((val) => ({ overall_fee: toBigInt(val.overall_fee), @@ -134,12 +98,6 @@ export class RPCResponseParser })); } - /** - * Parses the simulate transaction response. - * - * @param {any} res - The simulate transaction response. - * @returns {SimulateTransactionResponse} - The parsed simulate transaction response. - */ public parseSimulateTransactionResponse( // TODO: revisit // set as 'any' to avoid a mapped type circular recursion error stemming from @@ -157,12 +115,6 @@ export class RPCResponseParser }); } - /** - * Parses the contract class response. - * - * @param {ContractClassPayload} res - The response payload to parse. - * @return {ContractClassResponse} - The parsed contract class response. - */ public parseContractClassResponse(res: ContractClassPayload): ContractClassResponse { return { ...(res as ContractClassResponse), diff --git a/src/wallet/account.ts b/src/wallet/account.ts index cef733a97..9bc7616cc 100644 --- a/src/wallet/account.ts +++ b/src/wallet/account.ts @@ -115,10 +115,7 @@ export class WalletAccount extends Account implements AccountInterface { } /** - * Executes a batch of calls on a smart contract. - * - * @param {AllowArray} calls - The array of calls to execute on the smart contract. - * @returns - A promise that resolves with the result of the execution. + * ACCOUNT METHODS */ override execute(calls: AllowArray) { const txCalls = [].concat(calls as any).map((it) => { @@ -137,13 +134,6 @@ export class WalletAccount extends Account implements AccountInterface { return addInvokeTransaction(this.walletProvider, params); } - /** - * Overrides the declare method. - * - * @param {DeclareContractPayload} payload - The payload for declaring a contract. - * @return {Promise} - A promise that resolves with the transaction object. - * @throws {Error} - Throws an error if compiledClassHash is missing. - */ override declare(payload: DeclareContractPayload) { const declareContractPayload = extractContractHashes(payload); @@ -167,12 +157,6 @@ export class WalletAccount extends Account implements AccountInterface { return addDeclareTransaction(this.walletProvider, params); } - /** - * Deploys a contract or multiple contracts using the UniversalDeployer. - * - * @param {UniversalDeployerContractPayload | UniversalDeployerContractPayload[]} payload - The contract payload(s) to be deployed. - * @return {Promise} - The response object containing the result of the deployment. - */ override async deploy( payload: UniversalDeployerContractPayload | UniversalDeployerContractPayload[] ): Promise { @@ -185,16 +169,6 @@ export class WalletAccount extends Account implements AccountInterface { }; } - /** - * Deploys an account for a contract. - * - * @param {DeployAccountContractPayload} payload - The payload containing the necessary data for deployment. - * @param {string} payload.addressSalt - Optional. The address salt for the contract. Defaults to '0'. - * @param {string} payload.constructorCalldata - The constructor calldata for the contract. - * @param {string} payload.classHash - The class hash of the contract. - * - * @return - A promise that resolves when the account deployment is complete. - */ override deployAccount(payload: DeployAccountContractPayload) { const params = { contract_address_salt: payload.addressSalt?.toString() || '0', @@ -207,12 +181,6 @@ export class WalletAccount extends Account implements AccountInterface { return addDeployAccountTransaction(this.walletProvider, params); } - /** - * Signs the given message using the wallet provider. - * - * @param {TypedData} typedData - The typed data to be signed. - * @return - A promise that resolves with the signed message. - */ override signMessage(typedData: TypedData) { return signMessage(this.walletProvider, typedData); } From b05a2ca6da43b4b042041f6cf060f28b6d8728e4 Mon Sep 17 00:00:00 2001 From: Ivan Krcatovic Date: Thu, 18 Apr 2024 17:13:03 +0200 Subject: [PATCH 3/8] Modified comment param --- src/utils/address.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/address.ts b/src/utils/address.ts index f4185a0d8..514a337d1 100644 --- a/src/utils/address.ts +++ b/src/utils/address.ts @@ -37,7 +37,7 @@ export function validateAndParseAddress(address: BigNumberish): string { * Computes the checksum address for the given Ethereum address. * * From https://github.com/ethers-io/ethers.js/blob/fc1e006575d59792fa97b4efb9ea2f8cca1944cf/packages/address/src.ts/index.ts#L12 - * @param {BigNumberish} address - The Ethereum address to compute the checksum for. + * @param {BigNumberish} address - The address to compute the checksum for. * * @returns {string} The checksum address. */ From d83ee613f5fd4af2a99828107d70683a155d86bb Mon Sep 17 00:00:00 2001 From: Ivan Krcatovic Date: Thu, 18 Apr 2024 17:15:31 +0200 Subject: [PATCH 4/8] removed invalid comment --- src/utils/address.ts | 2 +- src/utils/starknetId.ts | 5 ----- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/src/utils/address.ts b/src/utils/address.ts index 514a337d1..f4185a0d8 100644 --- a/src/utils/address.ts +++ b/src/utils/address.ts @@ -37,7 +37,7 @@ export function validateAndParseAddress(address: BigNumberish): string { * Computes the checksum address for the given Ethereum address. * * From https://github.com/ethers-io/ethers.js/blob/fc1e006575d59792fa97b4efb9ea2f8cca1944cf/packages/address/src.ts/index.ts#L12 - * @param {BigNumberish} address - The address to compute the checksum for. + * @param {BigNumberish} address - The Ethereum address to compute the checksum for. * * @returns {string} The checksum address. */ diff --git a/src/utils/starknetId.ts b/src/utils/starknetId.ts index 147533a97..ad643b486 100644 --- a/src/utils/starknetId.ts +++ b/src/utils/starknetId.ts @@ -11,11 +11,6 @@ const basicAlphabetSize = BigInt(basicAlphabet.length); const bigAlphabetSize = BigInt(bigAlphabet.length); const bigAlphabetSizePlusOne = BigInt(bigAlphabet.length + 1); -/** - * Extracts stars from a given string and returns the modified string and the number of stars extracted. - * @param {string} str - The input string from which to extract stars. - * @returns {[string, number]} - An array containing the modified string and the number of stars extracted. - */ function extractStars(str: string): [string, number] { let k = 0; while (str.endsWith(bigAlphabet[bigAlphabet.length - 1])) { From 6717987c016ed066fa477a1358768d4aeeb82a28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Pavi=C4=8Di=C4=87?= Date: Fri, 19 Apr 2024 15:12:39 +0200 Subject: [PATCH 5/8] Update src/utils/address.ts --- src/utils/address.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/address.ts b/src/utils/address.ts index f4185a0d8..514a337d1 100644 --- a/src/utils/address.ts +++ b/src/utils/address.ts @@ -37,7 +37,7 @@ export function validateAndParseAddress(address: BigNumberish): string { * Computes the checksum address for the given Ethereum address. * * From https://github.com/ethers-io/ethers.js/blob/fc1e006575d59792fa97b4efb9ea2f8cca1944cf/packages/address/src.ts/index.ts#L12 - * @param {BigNumberish} address - The Ethereum address to compute the checksum for. + * @param {BigNumberish} address - The address to compute the checksum for. * * @returns {string} The checksum address. */ From 2b0a16dfd1ba788eb6410802d8dedd2987202bf6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Pavi=C4=8Di=C4=87?= Date: Fri, 19 Apr 2024 15:49:45 +0200 Subject: [PATCH 6/8] Update src/utils/address.ts --- src/utils/address.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/address.ts b/src/utils/address.ts index 514a337d1..a611d627f 100644 --- a/src/utils/address.ts +++ b/src/utils/address.ts @@ -34,7 +34,7 @@ export function validateAndParseAddress(address: BigNumberish): string { } /** - * Computes the checksum address for the given Ethereum address. + * Computes the checksum address for the given Starknet address. * * From https://github.com/ethers-io/ethers.js/blob/fc1e006575d59792fa97b4efb9ea2f8cca1944cf/packages/address/src.ts/index.ts#L12 * @param {BigNumberish} address - The address to compute the checksum for. From a1d720e50b3003a9cd2634075c9a7f57f50a6f9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Pavi=C4=8Di=C4=87?= Date: Fri, 19 Apr 2024 15:57:55 +0200 Subject: [PATCH 7/8] Update src/utils/calldata/cairo.ts --- src/utils/calldata/cairo.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/calldata/cairo.ts b/src/utils/calldata/cairo.ts index 538582242..fe67bb761 100644 --- a/src/utils/calldata/cairo.ts +++ b/src/utils/calldata/cairo.ts @@ -53,7 +53,7 @@ export const isTypeTuple = (type: string) => /^\(.*\)$/i.test(type); */ export const isTypeNamedTuple = (type: string) => /\(.*\)/i.test(type) && type.includes(':'); /** - * Checks if a given type exists in a collection of structs. + * Checks if a given type is a struct. * * @param {string} type - The type to check for existence. * @param {AbiStructs} structs - The collection of structs to search in. From 5a1c92a4f29a1dbba79ebbf8a3bc4180012b58e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Pavi=C4=8Di=C4=87?= Date: Fri, 19 Apr 2024 15:58:01 +0200 Subject: [PATCH 8/8] Update src/utils/calldata/cairo.ts --- src/utils/calldata/cairo.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/calldata/cairo.ts b/src/utils/calldata/cairo.ts index fe67bb761..09b419703 100644 --- a/src/utils/calldata/cairo.ts +++ b/src/utils/calldata/cairo.ts @@ -61,7 +61,7 @@ export const isTypeNamedTuple = (type: string) => /\(.*\)/i.test(type) && type.i */ export const isTypeStruct = (type: string, structs: AbiStructs) => type in structs; /** - * Checks if a given type exists in the provided enumeration. + * Checks if a given type is an enum. * * @param {string} type - The type to check. * @param {AbiEnums} enums - The enumeration to search in.