### Install @starknet-io/types-js Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/configuration.md Install the library using npm. This command fetches the latest version of the package. ```bash npm install @starknet-io/types-js ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/configuration.md Commands to install project dependencies and build the library in various formats (all, CJS, ESM, types only). Essential for local development and distribution. ```bash # Install dependencies npm install # Build all formats npm run build # Build only CJS npm run build:cjs # Build only ESM npm run build:esm # Build only types npm run build:types ``` -------------------------------- ### Install Starknet Types JS (RPC 0.10.2) Source: https://github.com/starknet-io/types-js/blob/main/README.md Install the latest version of the Starknet types JS package, compatible with Starknet 0.14.2. ```bash npm i @starknet-io/types-js@0.10.2 ``` -------------------------------- ### ES Modules Import Example Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/configuration.md Example of importing the library in a modern JavaScript environment using ES Modules. ```typescript import { API } from '@starknet-io/types-js' ``` -------------------------------- ### Install Starknet Types JS (RPC 0.10.0) Source: https://github.com/starknet-io/types-js/blob/main/README.md Install the Starknet types JS package for RPC version 0.10.0, compatible with Starknet 0.14.1. ```bash npm i @starknet-io/types-js@0.10.0 ``` -------------------------------- ### CommonJS Import Example Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/configuration.md Example of importing the library in a Node.js environment using the CommonJS module system. ```typescript const types = require('@starknet-io/types-js') ``` -------------------------------- ### Install Starknet Types JS (RPC 0.8) Source: https://github.com/starknet-io/types-js/blob/main/README.md Install the Starknet types JS package for RPC version 0.8, compatible with Starknet 0.13. ```bash npm i @starknet-io/types-js@0.8.4 ``` -------------------------------- ### Install Starknet Types JS (RPC 0.9) Source: https://github.com/starknet-io/types-js/blob/main/README.md Install the Starknet types JS package for RPC version 0.9, compatible with Starknet 0.14. ```bash npm i @starknet-io/types-js@0.9.2 ``` -------------------------------- ### Block Tags Example Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/constants.md Demonstrates using block tags like 'latest' for fetching block information. Requires importing BLOCK_TAG. ```typescript import { BLOCK_TAG } from '@starknet-io/types-js' const block = await rpc.getBlockWithTxs({ block_id: 'latest' }) ``` -------------------------------- ### Paymaster Execute Transaction Example Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/05-snip-29-paymaster.md An example demonstrating the complete flow of submitting a transaction for paymaster execution, including building, signing, and executing the transaction. ```typescript import type { EXECUTABLE_USER_TRANSACTION } from '@starknet-io/types-js' // Step 1: Get build response (from previous example) const buildResponse = await paymasterRpc.request({ type: 'paymaster_buildTransaction', params: { transaction, parameters } }) // Step 2: Sign the typed data (invoke only) let signature if (buildResponse.type === 'invoke' || buildResponse.type === 'deploy_and_invoke') { signature = await wallet.signTypedData(buildResponse.typed_data) } // Step 3: Execute transaction const executableTx: EXECUTABLE_USER_TRANSACTION = buildResponse.type === 'deploy' ? { type: 'deploy', deployment: buildResponse.deployment } : buildResponse.type === 'invoke' ? { type: 'invoke', invoke: { user_address: userAddress, typed_data: buildResponse.typed_data, signature: signature! } } : { type: 'deploy_and_invoke', deployment: buildResponse.deployment, invoke: { user_address: buildResponse.deployment.address, typed_data: buildResponse.typed_data, signature: signature! } } const result = await paymasterRpc.request({ type: 'paymaster_executeTransaction', params: { transaction: executableTx, parameters: buildResponse.parameters } }) console.log('Submitted! Tracking ID:', result.tracking_id) console.log('Transaction hash:', result.transaction_hash) ``` -------------------------------- ### Integrate with Wallet Provider Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/configuration.md Example of interacting with a Starknet wallet provider (e.g., starknetId) to request accounts. This demonstrates how to use the wallet provider interface for user authentication. ```typescript import type { RpcTypeToMessageMap } from '@starknet-io/types-js' if (window.starknetId) { const request = window.starknetId.request as ( call: any ) => Promise const accounts = await request({ type: 'wallet_requestAccounts' }) } ``` -------------------------------- ### Example Usage of Simulation Flags Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/constants.md Demonstrates using simulation flags with the `simulateTransactions` RPC method. ```typescript import { ESimulationFlag } from '@starknet-io/types-js' const simResult = await rpc.simulateTransactions({ block_id: 'latest', transactions: [...], simulation_flags: [ESimulationFlag.SKIP_VALIDATE], }) ``` -------------------------------- ### StarkNet Wallet Provider Detection Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/04-wallet-api-methods.md Checks for the availability of the StarkNet wallet provider in the browser environment. Essential for guiding users to install a wallet if none is detected. ```typescript if (window.starknetId) { console.log('Wallet available') } else { console.log('Please install a Starknet wallet') } ``` -------------------------------- ### Get Account Deployment Data Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/04-wallet-api-methods.md Obtain the necessary data to initialize a new Starknet account. This is useful for deploying accounts. ```typescript const deploymentData = await window.starknetId.request({ type: 'wallet_deploymentData' }) // Returns data needed for deploy_account transaction console.log('Expected address:', deploymentData.address) ``` -------------------------------- ### Install Minor and Patch Versions Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/configuration.md Commands for upgrading the library to the latest minor version (including spec changes) or patch version (bug fixes only). Use '^' for minor and '~' for patch updates. ```bash # Minor version (spec changes) npm install @starknet-io/types-js@^0.10.0 # Patch version (bug fixes only) npm install @starknet-io/types-js@~0.10.2 ``` -------------------------------- ### Example Usage of Transaction Type Constants Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/constants.md Demonstrates how to use transaction type constants for conditional logic. ```typescript import { ETransactionType } from '@starknet-io/types-js' const txType = ETransactionType.INVOKE if (txType === TXN_TYPE_INVOKE) { console.log('Invoke transaction') } ``` -------------------------------- ### Starknet JSON-RPC Methods Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/SUMMARY.txt Documentation for over 35 Starknet JSON-RPC methods, including full TypeScript signatures, parameter tables, return types, error conditions, and code examples. ```APIDOC ## Starknet JSON-RPC Methods This section details the Starknet JSON-RPC methods available through the library. Each method is documented with its full TypeScript signature, parameter specifications, return type, potential error conditions, and practical code examples. ### Method Documentation Structure: - **Full TypeScript signature** - **Parameter table** (name, type, required, description) - **Return type and structure** - **Error conditions and codes** - **Throwing/rejecting conditions** - **Code examples** (realistic, not test code) - **Patterns and best practices** - **Source location** (file:line) Refer to the `api-reference/01-starknet-read-methods.md`, `api-reference/02-starknet-write-methods.md`, and `api-reference/03-starknet-trace-methods.md` files for specific method details. ``` -------------------------------- ### Handling TOO_MANY_BLOCKS_BACK Error Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/errors.md Demonstrates how to handle the TOO_MANY_BLOCKS_BACK error by splitting queries into smaller chunks. The 'Bad' example shows an invalid query exceeding the 1024 block limit, while the 'Good' example illustrates the correct approach. ```typescript // Bad: exceeds 1024 block range const events = await rpc.getEvents({ filter: { from_block: { block_number: 0 }, to_block: { block_number: 2000 } }, chunk_size: 100 }) // Good: split into multiple queries const chunk1 = await rpc.getEvents({ filter: { from_block: { block_number: 0 }, to_block: { block_number: 1000 } }, chunk_size: 100 }) ``` -------------------------------- ### Querying Starknet Block Data Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/README.md Example of how to fetch block data, including transaction details and proof facts, using the `starknet_getBlockWithTxs` method. Ensure the `API` type is imported from `@starknet-io/types-js`. ```typescript import type { API } from '@starknet-io/types-js' const block = await rpc.request({ method: 'starknet_getBlockWithTxs', params: { block_id: 'latest', response_flags: ['INCLUDE_PROOF_FACTS'] } }) ``` -------------------------------- ### Integrate with JSON-RPC Client Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/configuration.md Shows how to use the types-js library with a JSON-RPC client for full type support when interacting with Starknet nodes. The example demonstrates fetching storage data. ```typescript import type { Methods } from '@starknet-io/types-js' import { JsonRpcProvider } from 'some-rpc-client' class StarknetProvider { private rpc: JsonRpcProvider constructor(rpcUrl: string) { this.rpc = new JsonRpcProvider(rpcUrl) } async getBalance(address: string) { // Full type support const nonce = await this.rpc.request({ method: 'starknet_getStorageAt', params: { contract_address: address, key: '0x...', block_id: 'latest' } }) return nonce } } ``` -------------------------------- ### Simulating Starknet Transactions Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/README.md Example of simulating transactions using `starknet_simulateTransactions`. This allows for validation skipping and retrieving initial reads. The `simulation` result can be destructured into `simulated_transactions` and `initial_reads`. ```typescript const simulation = await rpc.request({ method: 'starknet_simulateTransactions', params: { block_id: 'latest', transactions: [myTx], simulation_flags: ['SKIP_VALIDATE'], trace_flags: ['RETURN_INITIAL_READS'] } }) if (!Array.isArray(simulation)) { const { simulated_transactions, initial_reads } = simulation } ``` -------------------------------- ### Get Starknet Contract Class Definition Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/01-starknet-read-methods.md Retrieves the contract class definition for a given class hash at a specific block. Use this to get the ABI, program, and entry points of a contract. ```typescript const classData = await rpc.getClass({ block_id: 'latest', class_hash: '0x...' }) ``` -------------------------------- ### Wallet API Methods Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/SUMMARY.txt Documentation for 13 Wallet API methods, including their TypeScript signatures, parameter details, return values, error handling, and usage examples. ```APIDOC ## Wallet API Methods This section covers the 13 methods provided by the Wallet API. Each method includes a detailed TypeScript signature, a table outlining parameters (name, type, required status, and description), the expected return type and structure, and information on error conditions and code examples. ### Method Documentation Structure: - **Full TypeScript signature** - **Parameter table** (name, type, required, description) - **Return type and structure** - **Error conditions and codes** - **Throwing/rejecting conditions** - **Code examples** (realistic, not test code) - **Patterns and best practices** - **Source location** (file:line) Refer to the `api-reference/04-wallet-api-methods.md` file for specific method details. ``` -------------------------------- ### Get Supported RPC Specification Versions Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/04-wallet-api-methods.md Retrieve a list of supported StarkNet RPC specification versions from the wallet. This is useful for ensuring compatibility between the dApp and the wallet. ```typescript const specs = await window.starknetId.request({ type: 'wallet_supportedSpecs' }) // Returns: ["0.7.0", "0.8.0"] ``` -------------------------------- ### Paymaster Build Transaction - Invoke Example Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/05-snip-29-paymaster.md Builds a sponsored invoke transaction and retrieves fee estimates and data to be signed. Use this when performing contract calls with paymaster sponsorship. ```typescript import type { USER_TRANSACTION, EXECUTION_PARAMETERS } from '@starknet-io/types-js' const transaction: USER_TRANSACTION = { type: 'invoke', invoke: { user_address: userAddress, calls: [ { contract_address: tokenAddress, entry_point: 'approve', calldata: [ spenderAddress, amount ] }, { contract_address: swapAddress, entry_point: 'swap', calldata: [ amount ] } ] } } const params: EXECUTION_PARAMETERS = { version: '0x1', fee_mode: { mode: 'sponsored' // Paymaster pays }, time_bounds: { execute_after: Math.floor(Date.now() / 1000), execute_before: Math.floor(Date.now() / 1000) + 3600 } } const response = await paymasterRpc.request({ type: 'paymaster_buildTransaction', params: { transaction, parameters: params } }) if (response.type === 'invoke') { console.log('Fee estimate:', response.fee.estimated_fee_in_strk) console.log('Sign this data:', response.typed_data) // User signs the typed_data const signature = await wallet.signTypedData(response.typed_data) // Prepare execute call with signature } ``` -------------------------------- ### Get Starknet Spec Version Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/01-starknet-read-methods.md Retrieve the version of the Starknet JSON-RPC specification used by the node. The result is a semver string. ```typescript import { Methods } from '@starknet-io/types-js' const version: string = '0.7.1' // Result would be a semver string like "0.7.1" ``` -------------------------------- ### Sponsor a Transaction with Paymaster Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/05-snip-29-paymaster.md This snippet demonstrates the complete flow for sponsoring a transaction using a paymaster. It covers getting deployment data, defining the transaction, building it with the paymaster, showing fee estimates, signing, and executing the transaction. ```typescript import { PAYMASTER_API } from '@starknet-io/types-js' async function sponsorTransaction(wallet, paymasterRpc) { // Get user's current deployment data (if new account) const deploymentData = await wallet.deploymentData() // Define the transaction const transaction = { type: 'deploy_and_invoke', deployment: deploymentData, invoke: { user_address: deploymentData.address, calls: [ { contract_address: tokenAddress, entry_point: 'approve', calldata: [ spender, amount ] } ] } } // Build with paymaster const buildResponse = await paymasterRpc.request({ type: 'paymaster_buildTransaction', params: { transaction, parameters: { version: '0x1', fee_mode: { mode: 'sponsored' }, time_bounds: { execute_after: Math.floor(Date.now() / 1000), execute_before: Math.floor(Date.now() / 1000) + 3600 } } } }) // Show fee estimate to user console.log( 'This transaction would cost:', buildResponse.fee.estimated_fee_in_strk, 'STRK (being paid by paymaster)' ) // Sign if needed let signature if (buildResponse.type !== 'deploy') { signature = await wallet.signTypedData(buildResponse.typed_data) } // Execute const executableTx = { type: buildResponse.type, deployment: buildResponse.deployment, ...(buildResponse.type !== 'deploy' && { invoke: { user_address: deploymentData.address, typed_data: buildResponse.typed_data, signature: signature! } }) } const result = await paymasterRpc.request({ type: 'paymaster_executeTransaction', params: { transaction: executableTx, parameters: buildResponse.parameters } }) return result } ``` -------------------------------- ### Get Supported Wallet API Versions Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/04-wallet-api-methods.md Retrieve a list of supported StarkNet wallet API versions from the wallet. This may differ from RPC specification versions and helps in determining feature compatibility. ```typescript const apiVersions = await window.starknetId.request({ type: 'wallet_supportedWalletApi' }) // Returns: ["1.0", "1.1"] ``` -------------------------------- ### Get Block With Transactions and Receipts Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/01-starknet-read-methods.md Retrieve block information with full transactions and their execution receipts. This provides comprehensive details including gas used and events. ```typescript const block = await rpc.getBlockWithReceipts({ block_id: { block_number: 100 } }) // Contains: transactions + receipts (including gas used, events, etc.) ``` -------------------------------- ### Get Storage Proof Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/03-starknet-trace-methods.md Obtain Merkle paths for state proofs, useful for verifying contract state at a specific block. Supports filtering by class hashes, contract addresses, and storage keys. ```typescript starknet_getStorageProof: { params: { block_id: Exclude class_hashes?: FELT[] contract_addresses?: ADDRESS[] contracts_storage_keys?: CONTRACT_STORAGE_KEYS[] } result: StorageProof errors: BLOCK_NOT_FOUND | STORAGE_PROOF_NOT_SUPPORTED } ``` ```typescript { classes_proof: NODE_HASH_TO_NODE_MAPPING // Class trie proof contracts_proof: { nodes: NODE_HASH_TO_NODE_MAPPING // Contracts trie proof leaves: ContractProofLeaf[] // Nonce and class hash } contracts_storage_proofs: StorageProofItem[] } ``` ```typescript const proof = await rpc.getStorageProof({ block_id: { block_number: 1000 }, contract_addresses: ['0x...'], contracts_storage_keys: [{ contract_address: '0x ...', storage_keys: ['0x...'] }] }) // Returns proof nodes for verification ``` -------------------------------- ### Get Nonce and Increment for Next Transaction Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/errors.md This TypeScript snippet demonstrates how to fetch the current nonce for an account and prepare it for the next transaction by incrementing it. This is crucial for handling the INVALID_TRANSACTION_NONCE error. ```typescript const nonce = await rpc.getNonce({ block_id: 'latest', contract_address: accountAddress }) // Use nonce + 1 for next transaction ``` -------------------------------- ### Get Starknet Contract Class Definition at Address Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/01-starknet-read-methods.md Retrieves the contract class definition for a contract deployed at a specific address at a given block. Useful for inspecting contract details without a transaction. ```typescript const classData = await rpc.getClassAt({ block_id: { block_number: 1000 }, contract_address: '0x...' }) ``` -------------------------------- ### Trace Starknet Block Transactions Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/03-starknet-trace-methods.md Use `starknet_traceBlockTransactions` to retrieve execution traces for all transactions within a specified block. You can optionally include `RETURN_INITIAL_READS` trace flag to get state values read during execution. ```typescript const traces = await rpc.traceBlockTransactions({ block_id: 100, trace_flags: ['RETURN_INITIAL_READS'] }) if (Array.isArray(traces)) { // Without RETURN_INITIAL_READS traces.forEach(({transaction_hash, trace_root}) => { console.log(`Tx ${transaction_hash}: ${trace_root.function_invocation.result}`) }) } else { // With RETURN_INITIAL_READS const {traces, initial_reads} = traces console.log('Initial reads:', initial_reads) traces.forEach(({transaction_hash, trace_root}) => { console.log(`Tx ${transaction_hash}: ${trace_root.function_invocation.result}`) }) } ``` -------------------------------- ### Request Accounts from Wallet Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/README.md Requests accounts from the user's wallet. Use this when you need to connect to a Starknet wallet and get the user's account addresses. The `silent_mode` parameter controls whether the wallet should prompt the user. ```typescript import type { WALLET_API } from '@starknet-io/types-js' const accounts = await window.starknetId.request({ type: 'wallet_requestAccounts', params: { silent_mode: false } }) ``` -------------------------------- ### Build Project Source: https://github.com/starknet-io/types-js/blob/main/README.md Run the build script for development. ```bash npm run build ``` -------------------------------- ### Lint Project Source: https://github.com/starknet-io/types-js/blob/main/README.md Run the lint script for development testing. ```bash npm run lint ``` -------------------------------- ### wallet_deploymentData Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/04-wallet-api-methods.md Fetches the necessary data for initializing a new Starknet account. This includes the deployment address, class hash, salt, and calldata. ```APIDOC ## wallet_deploymentData ### Description Get account deployment data for initializing a new account. ### Method POST (Assumed, based on typical wallet request patterns) ### Endpoint `/` (Assumed, typically part of a JSON-RPC endpoint) ### Parameters #### Query Parameters None explicitly defined, but `type` and `params` are used in the SDK example. #### Request Body - **type** (string) - Required - Must be 'wallet_deploymentData' - **params** (ApiVersionRequest) - Optional - Parameters for the request. - **api_version** (string) - No - API version. ### Request Example ```json { "type": "wallet_deploymentData" } ``` ### Response #### Success Response (200) - **result** (AccountDeploymentData) - Data needed for deploy_account transaction. - **address** (Address) - Expected deployment address. - **class_hash** (FELT) - Account class hash. - **salt** (FELT) - Address salt. - **calldata** (FELT[]) - Constructor calldata. - **sigdata** (FELT[]) - Optional - Additional signature data. - **version** (0 | 1) - Cairo version. #### Response Example ```json { "result": { "address": "0x...", "class_hash": "0x...", "salt": "0x...", "calldata": ["0x..."], "version": 1 } } ``` ### Errors - `ACCOUNT_ALREADY_DEPLOYED` - Account already initialized - `API_VERSION_NOT_SUPPORTED` - `UNKNOWN_ERROR` ``` -------------------------------- ### Get Transaction Status Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/01-starknet-read-methods.md Fetches the current status of a transaction using its hash. This includes its state in the mempool. ```typescript const status = await rpc.getTransactionStatus({ transaction_hash: '0x...' }) // Returns: { finality_status: 'ACCEPTED_ON_L2', execution_status: 'SUCCEEDED' } ``` -------------------------------- ### Get Block Hash and Number Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/01-starknet-read-methods.md Retrieves the hash and number of the most recent accepted block. This method requires no parameters. ```typescript const {block_hash, block_number} = await rpc.blockHashAndNumber() ``` -------------------------------- ### Starknet Trace & Simulation Methods Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/INDEX.md Documentation for methods related to execution analysis, including transaction tracing, simulation, and storage proofs. ```APIDOC ## Starknet Trace & Simulation Methods ### Description Provides tools for analyzing transaction execution and simulating network states. ### Methods - `starknet_traceTransaction`: Get transaction execution trace. - `starknet_traceBlockTransactions`: Get all traces in block. - `starknet_simulateTransactions`: Simulate transactions without submission. - `starknet_getNonce`: Get account nonce. - `starknet_getCompiledCasm`: Get compiled Cairo bytecode. - `starknet_getStorageProof`: Get merkle proofs for state. - `starknet_getMessagesStatus`: Get L1→L2 message status. ### Details: - Execution trace structure documentation - Simulation flag explanations - Trace format variations (with/without RETURN_INITIAL_READS) - Fee estimation without validation - Revert reason checking patterns - Storage proof generation ``` -------------------------------- ### Import StarkNet Types Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/README.md Import specific types like FELT and ADDRESS, or entire namespaces such as API, WALLET_API, and PAYMASTER_API from the library. Also shows importing constants and enums. ```typescript // Type imports import type { FELT, ADDRESS } from '@starknet-io/types-js' // Namespace imports import { API, WALLET_API, PAYMASTER_API } from '@starknet-io/types-js' // Constants import { STATUS_ACCEPTED_ON_L2, ESimulationFlag } from '@starknet-io/types-js' ``` -------------------------------- ### Get Starknet Chain ID Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/01-starknet-read-methods.md Retrieves the unique identifier for the current Starknet chain. The ID is returned in ASCII hex encoding. ```typescript const chainId = await rpc.chainId() // Returns: "0x534e5f4d41494e" // Mainnet // or: "0x534e5f5345504f4c4941" // Sepolia ``` -------------------------------- ### Get Wallet Permissions Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/04-wallet-api-methods.md Retrieves the current permissions granted by the wallet. This can be used to check if specific methods, like `wallet_signTypedData`, are permitted. ```typescript const permissions = await window.starknetId.request({ type: 'wallet_getPermissions' }) const hasSignTypeData = permissions.some(p => p.method === 'wallet_signTypedData') if (hasSignTypeData) { console.log('Can sign typed data') } ``` -------------------------------- ### Get Starknet Block Number Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/01-starknet-read-methods.md Fetches the number of the most recently accepted block on the Starknet network. This is a simple query for the latest block height. ```typescript const blockNum = await rpc.blockNumber() // Returns: 123456 ``` -------------------------------- ### Get Starknet Block Transaction Count Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/01-starknet-read-methods.md Queries the total number of transactions within a specified block. Use 'latest' for the most recent block. ```typescript const count = await rpc.getBlockTransactionCount({ block_id: 'latest' }) ``` -------------------------------- ### Recommended Constant Usage Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/constants.md Demonstrates recommended patterns for using constants and enums directly or for type-safe patterns with imported types. ```typescript import { STATUS_ACCEPTED_ON_L2, TXN_TYPE_INVOKE, ESimulationFlag, PRICE_UNIT_WEI } from '@starknet-io/types-js' // Use constants directly if (tx.finality_status === STATUS_ACCEPTED_ON_L2) { } // Or use enums for better IDE support if (txType === ETransactionType.INVOKE) { } // Constants in simulation const flags = [ESimulationFlag.SKIP_VALIDATE] ``` ```typescript import type { TXN_STATUS, TXN_TYPE, SIMULATION_FLAG } from '@starknet-io/types-js' const status: TXN_STATUS = 'ACCEPTED_ON_L2' const type: TXN_TYPE = 'INVOKE' const flags: SIMULATION_FLAG[] = ['SKIP_VALIDATE'] ``` -------------------------------- ### paymaster_getSupportedTokens Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/05-snip-29-paymaster.md Get a list of tokens that the paymaster accepts for fee payment. Returns an array of supported tokens, each with its address, decimals, and price in STRK. ```APIDOC ## paymaster_getSupportedTokens ### Description Get list of tokens the paymaster accepts for fee payment. ### Method N/A (This is a JSON-RPC method call, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (object) - Empty object ### Request Example ```json { "type": "paymaster_getSupportedTokens", "params": {} } ``` ### Response #### Success Response (200) - **result** (TOKEN_DATA[]) - Array of supported tokens **TOKEN_DATA Structure:** ```typescript { token_address: ADDRESS // Contract address decimals: number // Decimal places (e.g., 18) price_in_strk: u256 // Current price in STRK } ``` #### Response Example ```json [ { "token_address": "0x...", "decimals": 6, "price_in_strk": "0x2540be400" } ] ``` ``` -------------------------------- ### Get Starknet Contract Class Hash at Address Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/01-starknet-read-methods.md Fetches the class hash of a contract deployed at a specific address for a given block. This is a read-only operation. ```typescript starknet_getClassHashAt: { params: { block_id: BLOCK_ID contract_address: ADDRESS } result: FELT errors: BLOCK_NOT_FOUND | CONTRACT_NOT_FOUND } ``` -------------------------------- ### Get Transaction Receipt Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/01-starknet-read-methods.md Retrieves the receipt for a transaction using its hash. The receipt contains information such as gas consumed, events emitted, and execution status. ```typescript const receipt = await rpc.getTransactionReceipt({ transaction_hash: '0x...' }) // Contains: execution_status, finality_status, gas_consumed, actual_fee, events[] ``` -------------------------------- ### Simulate Transactions with Traces Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/03-starknet-trace-methods.md Simulates a sequence of transactions on a specified block state, returning detailed execution traces and fee estimations. Use 'RETURN_INITIAL_READS' to include initial state reads. ```typescript const simulations = await rpc.simulateTransactions({ block_id: 'latest', transactions: [ { type: 'INVOKE', sender_address: '0x...', calldata: ['0x...'], signature: ['0x...'], nonce: '0x1', max_fee: '0x0', version: '0x1' }, { type: 'INVOKE', sender_address: '0x...', calldata: ['0x...'], signature: ['0x...'], nonce: '0x2', max_fee: '0x0', version: '0x1' } ], simulation_flags: ['SKIP_VALIDATE', 'SKIP_FEE_CHARGE'], trace_flags: ['RETURN_INITIAL_READS'] }) if (Array.isArray(simulations)) { // Without trace flags simulations.forEach(({transaction_trace, fee_estimation}) => { console.log(`Gas: ${fee_estimation.gas_consumed}, Fee: ${fee_estimation.overall_fee}`) if (transaction_trace.function_invocation.revert_error) { console.log('Reverted:', transaction_trace.function_invocation.revert_error) } }) } else { // With trace flags const {simulated_transactions, initial_reads} = simulations console.log('Initial state reads:', initial_reads) simulated_transactions.forEach(({transaction_trace, fee_estimation}, i) => { console.log(`Tx ${i}: Gas=${fee_estimation.gas_consumed}`) }) } ``` -------------------------------- ### Get Transaction Details by Hash Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/01-starknet-read-methods.md Retrieves the full details and status of a transaction identified by its hash. Optional response flags can include additional fields. ```typescript const tx = await rpc.getTransactionByHash({ transaction_hash: '0x...' }) // Contains: type, sender_address, calldata, signature, etc. ``` -------------------------------- ### Get Compiled CASM Bytecode Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/03-starknet-trace-methods.md Retrieve the CASM bytecode compiled from a Cairo class hash. Use this to inspect contract bytecode or for debugging purposes. ```typescript starknet_getCompiledCasm: { params: { class_hash: FELT } result: CASM_COMPILED_CONTRACT_CLASS errors: COMPILATION_ERROR | CLASS_HASH_NOT_FOUND } ``` ```typescript { bytecode: number[] // Compiled bytecode prime: string // Prime field element compiler_version?: string // Compiler version hints?: { [address: number]: string[] } // Hints for execution } ``` ```typescript const casm = await rpc.getCompiledCasm({ class_hash: '0x...' }) console.log('Bytecode length:', casm.bytecode.length) console.log('Hints:', Object.keys(casm.hints || {}).length) ``` -------------------------------- ### Import Wallet API Types Source: https://github.com/starknet-io/types-js/blob/main/README.md Import specific Wallet API types or the entire Wallet API namespace from the Starknet types JS package. ```typescript // type import import type { SomeWalletApiType } from '@starknet-io/types-js'; // or entire namespace import import { WALLET_API } from '@starknet-io/types-js'; ``` -------------------------------- ### General Wallet API Request Pattern Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/04-wallet-api-methods.md Demonstrates the standard pattern for making requests to the StarkNet wallet provider, including error handling for user rejections. ```typescript try { const result = await window.starknetId.request({ type: 'METHOD_NAME', params: { /* parameters */ } }) console.log('Success:', result) } catch (error) { // Handle errors if (error.message === 'USER_REFUSED_OP') { console.log('User rejected the operation') } } ``` -------------------------------- ### Submitting an Invoke Transaction to Starknet Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/README.md Demonstrates how to submit an invoke transaction using the `starknet_addInvokeTransaction` method. Requires transaction details such as sender address, calldata, signature, nonce, max fee, and version. The `API` type should be imported. ```typescript import type { API } from '@starknet-io/types-js' const result = await rpc.request({ method: 'starknet_addInvokeTransaction', params: { invoke_transaction: { type: 'INVOKE', sender_address: userAddress, calldata: ['0x...'], signature: ['0x...', '0x...'], nonce: '0x1', max_fee: '0x1000000000000', version: '0x1' } } }) ``` -------------------------------- ### Get Storage Value at Key Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/01-starknet-read-methods.md Retrieves the storage value for a given contract address and key. Supports optional response flags to include block information. ```typescript const value = await rpc.getStorageAt({ contract_address: '0x...', key: '0x...', block_id: 'latest', response_flags: ['INCLUDE_LAST_UPDATE_BLOCK'] }) // Returns: { value: FELT, block_number?: BLOCK_NUMBER } ``` -------------------------------- ### Starknet Write Operations Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/INDEX.md Documentation for state-modifying Starknet RPC methods, including submitting, declaring, and deploying transactions, as well as fee estimation. ```APIDOC ## Starknet Write Operations ### Description Allows modification of the Starknet state by submitting transactions. ### Methods - `starknet_addInvokeTransaction`: Submit invoke transaction. - `starknet_addDeclareTransaction`: Declare contract class. - `starknet_addDeployAccountTransaction`: Deploy account contract. - `starknet_estimateFee`: Estimate transaction fees. - `starknet_estimateMessageFee`: Estimate L1→L2 message fee. ### Details for each method: - Full type signature with nested structures - Parameter documentation - Return value structure - Error handling (25+ distinct errors per method) - Complete examples showing transaction structure - Fee estimation patterns ``` -------------------------------- ### Constants and Enums Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/README.md Demonstrates the usage of constants and enums provided by the Starknet.io Types JS library. These include direct constants for status checks and enums for IDE support. ```typescript import { STATUS_ACCEPTED_ON_L2, TXN_TYPE_INVOKE, ESimulationFlag, ETransactionType } from '@starknet-io/types-js' // Direct constant if (status === STATUS_ACCEPTED_ON_L2) { } // Enum for IDE support const flags: typeof ESimulationFlag[] = [ESimulationFlag.SKIP_VALIDATE] ``` -------------------------------- ### Get Account Nonce Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/03-starknet-trace-methods.md Retrieves the current nonce for a given account address at a specific block. The nonce is used to determine the sequence number for the next transaction. ```typescript const nonce = await rpc.getNonce({ block_id: 'latest', contract_address: accountAddress }) // For next transaction, use nonce + 1 ``` -------------------------------- ### Trace a Starknet Transaction Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/03-starknet-trace-methods.md Use `starknet_traceTransaction` to get the execution trace of a specific transaction, including all internal calls. This method requires the transaction hash as a parameter. ```typescript const trace = await rpc.traceTransaction({ transaction_hash: '0x...' }) // Structure: // { // validate_entrypoint: { steps: 1234, ... }, // execute_entrypoint: { steps: 5678, ... }, // function_invocation: { // call_type: 'CALL', // events: [ { keys: [...], data: [...] } ], // internal_calls: [ { ... } ], // result: ['0x1', '0x2'] // } // } if (trace.function_invocation.revert_error) { console.log('Transaction reverted:', trace.function_invocation.revert_error) } ``` -------------------------------- ### Sync Status Structure Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/types.md Provides information about the node's synchronization status with the Starknet network. Includes details on starting, current, and highest known blocks. ```typescript type SYNC_STATUS = { starting_block_hash: BLOCK_HASH starting_block_num: BLOCK_NUMBER current_block_hash: BLOCK_HASH current_block_num: BLOCK_NUMBER highest_block_hash: BLOCK_HASH highest_block_num: BLOCK_NUMBER } ``` -------------------------------- ### Starknet Read Operations Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/INDEX.md Documentation for read-only Starknet RPC methods, including block information, state retrieval, transaction details, and event querying. ```APIDOC ## Starknet Read Operations ### Description Provides access to read-only data from the Starknet network. ### Methods - `starknet_specVersion`: Get RPC spec version. - `starknet_getBlockWithTxHashes`: Get block with transaction hashes. - `starknet_getBlockWithTxs`: Get block with full transactions. - `starknet_getBlockWithReceipts`: Get block with receipts. - `starknet_getStateUpdate`: Get state changes in block. - `starknet_getStorageAt`: Get storage value. - `starknet_getTransactionStatus`: Get transaction status. - `starknet_getTransactionByHash`: Get transaction details. - `starknet_getTransactionByBlockIdAndIndex`: Get transaction by position. - `starknet_getTransactionReceipt`: Get transaction receipt. - `starknet_getClass`: Get contract class by hash. - `starknet_getClassHashAt`: Get contract's class hash. - `starknet_getClassAt`: Get contract's class definition. - `starknet_getBlockTransactionCount`: Get transaction count in block. - `starknet_call`: Call contract function (read-only). - `starknet_chainId`: Get chain ID. - `starknet_blockNumber`: Get latest block number. - `starknet_blockHashAndNumber`: Get latest block hash and number. - `starknet_syncing`: Get sync status. - `starknet_getEvents`: Get events with pagination. ### Details for each method: - Full type signature - Parameter table with types and descriptions - Return type documentation - Error conditions - Usage examples - Special notes and patterns ``` -------------------------------- ### Package.json Configuration for Dual ESM/CJS Support Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/configuration.md Configures the package for modern module systems, enabling both ESM and CJS formats. The 'sideEffects: false' flag optimizes tree-shaking. ```json { "name": "@starknet-io/types-js", "version": "0.10.2", "type": "module", "sideEffects": false, "exports": { ".": { "types": "./dist/types/index.d.ts", "import": "./dist/esm/index.js", "default": "./dist/cjs/index.js" }, "./package.json": "./package.json" } } ``` -------------------------------- ### Import PAYMASTER_API Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/05-snip-29-paymaster.md Import the PAYMASTER_API type from the @starknet-io/types-js library. This is required for using the SNIP-29 Paymaster API. ```typescript import { PAYMASTER_API } from '@starknet-io/types-js' ``` -------------------------------- ### ES Modules Build Output Configuration Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/configuration.md Configuration for the ES Modules (ESM) build format, suitable for modern bundlers and ES module systems. ```json { "module": "./dist/esm/index.js", "exports": { ".": { "import": "./dist/esm/index.js" } } } ``` -------------------------------- ### Generic Error Handling Pattern Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/errors.md Illustrates a general try-catch block for handling StarkNet RPC and wallet errors. It shows how to differentiate between API errors by code and wallet errors by message. ```typescript try { const result = await rpc.someMethod({...}) // Success } catch (error) { // API error with code if (error.code === 20) { console.error('Contract not found') } // Wallet error else if (error.message === 'USER_REFUSED_OP') { console.error('User rejected') } // Generic error else { console.error('Unknown error:', error.message) } } ``` -------------------------------- ### starknet_getStorageProof Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/03-starknet-trace-methods.md Retrieves Merkle paths for state proofs, allowing for verification of contract states at a specific block. Supports filtering by class hashes, contract addresses, and storage keys. ```APIDOC ## starknet_getStorageProof ### Description Get merkle paths for state proofs. ### Method GET (assumed, based on typical RPC patterns) ### Endpoint `/rpc` (assumed, based on typical RPC patterns) ### Parameters #### Query Parameters - **block_id** (BLOCK_ID) - Required - Block (not pre_confirmed) - **class_hashes** (FELT[]) - Optional - Classes to prove - **contract_addresses** (ADDRESS[]) - Optional - Contracts to prove - **contracts_storage_keys** (CONTRACT_STORAGE_KEYS[]) - Optional - Storage slots to prove ### Response #### Success Response (200) - **classes_proof** (NODE_HASH_TO_NODE_MAPPING) - Class trie proof - **contracts_proof** ({ nodes: NODE_HASH_TO_NODE_MAPPING, leaves: ContractProofLeaf[] }) - Contracts trie proof and leaves - **contracts_storage_proofs** (StorageProofItem[]) - Storage proof items ### Response Example ```json { "classes_proof": {}, "contracts_proof": { "nodes": {}, "leaves": [] }, "contracts_storage_proofs": [] } ``` ``` -------------------------------- ### Get Block With Full Transactions Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/01-starknet-read-methods.md Retrieve block information including full transaction objects. Optionally, specify response_flags to include additional fields like proof facts for each transaction. ```typescript import { BLOCK_ID, TXN_RESPONSE_FLAG } from '@starknet-io/types-js' const block = { block_id: 'latest', response_flags: ['INCLUDE_PROOF_FACTS'] } // Returns block with complete transaction objects ``` -------------------------------- ### Contract ABI Entry Point Type Constants Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/constants.md Defines the types of entry points within a contract's ABI. ```typescript ABI_TYPE_FUNCTION = 'function' ABI_TYPE_CONSTRUCTOR = 'constructor' ABI_TYPE_L1_HANDLER = 'l1_handler' EVENT_ABI_TYPE = 'event' STRUCT_ABI_TYPE = 'struct' ABI_TYPE_ENUM = 'enum' ``` -------------------------------- ### Get L1-L2 Message Status Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/03-starknet-trace-methods.md Check the status of messages sent from L1 to L2 using the Ethereum transaction hash. Provides handler transaction hash, finality, and execution status. ```typescript starknet_getMessagesStatus: { params: { transaction_hash: L1_TXN_HASH } result: L1L2MessagesStatus errors: TXN_HASH_NOT_FOUND } ``` ```typescript const statuses = await rpc.getMessagesStatus({ transaction_hash: '0x...' // Ethereum tx hash }) statuses.forEach((status, i) => { if (status.execution_status === 'SUCCEEDED') { console.log(`Message ${i}: Handler tx ${status.l1_handler_txn_hash}`) } }) ``` -------------------------------- ### Code Quality Checks Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/configuration.md Commands for maintaining code quality, including type checking, linting with Biome, and code formatting. 'npm run pretest' runs all checks. ```bash # Type checking npm run ts:check # Linting with Biome npm run lint # Format code npm run format # Run all checks npm run pretest ``` -------------------------------- ### SNIP-29 Paymaster API Methods Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/SUMMARY.txt Documentation for 4 Paymaster API methods compliant with SNIP-29, featuring TypeScript signatures, parameter specifications, return types, error handling, and code examples. ```APIDOC ## SNIP-29 Paymaster API Methods This section documents the 4 Paymaster API methods that adhere to the SNIP-29 standard. Documentation for each method includes its complete TypeScript signature, a parameter table detailing name, type, requirement, and description, the return type and structure, and guidance on error conditions and code examples. ### Method Documentation Structure: - **Full TypeScript signature** - **Parameter table** (name, type, required, description) - **Return type and structure** - **Error conditions and codes** - **Throwing/rejecting conditions** - **Code examples** (realistic, not test code) - **Patterns and best practices** - **Source location** (file:line) Refer to the `api-reference/05-snip-29-paymaster.md` file for specific method details. ``` -------------------------------- ### Paymaster Build Transaction - Deploy and Invoke Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/05-snip-29-paymaster.md Builds a sponsored transaction that includes both deploying a new account and invoking functions. The response provides deployment data and data to be signed for the invoke part. ```typescript const response = await paymasterRpc.request({ type: 'paymaster_buildTransaction', params: { transaction: { type: 'deploy_and_invoke', deployment: deployData, invoke: { user_address: deployData.address, calls: setupCalls } }, parameters: { ... } } }) // Returns both deployment data and typed_data to sign ``` -------------------------------- ### Submit Deploy Account Transaction Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/02-starknet-write-methods.md Use this method to submit a transaction for initializing a new account contract. Ensure the BROADCASTED_DEPLOY_ACCOUNT_TXN structure is correctly populated with all required fields. ```typescript const deployParams = { type: 'DEPLOY_ACCOUNT', class_hash: '0x...', contract_address_salt: '0x123...', constructor_calldata: ['0x...'], // pubkey or other init params signature: ['0x...'], nonce: '0x0', max_fee: '0x1000000000000', version: '0x1' } const result = await rpc.addDeployAccountTransaction({ deploy_account_transaction: deployParams }) // Returns: { // transaction_hash: '0x...', // contract_address: '0x...' // New account address // } ``` -------------------------------- ### Get Transaction by Block ID and Index Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/01-starknet-read-methods.md Fetches a transaction based on its position within a specific block, identified by block ID and index. Optional response flags can include additional fields. ```typescript const tx = await rpc.getTransactionByBlockIdAndIndex({ block_id: 'latest', index: 0 }) ``` -------------------------------- ### Get Block With Transaction Hashes Source: https://github.com/starknet-io/types-js/blob/main/_autodocs/api-reference/01-starknet-read-methods.md Retrieve block information containing only transaction hashes. Use this when full transaction data is not required. The block_id can be a hash, number, or tag like 'latest' or 'pending'. ```typescript import { BLOCK_ID } from '@starknet-io/types-js' const blockId: BLOCK_ID = { block_number: 12345 } // or: const blockId = { block_hash: '0x...' } // or: const blockId = 'latest' // Returns block with tx_hashes array ```