### Complete WebSocket Channel Example Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/websocket_channel.md A comprehensive example demonstrating the setup of a WebSocket channel, subscription to new block headers, contract events, and transaction receipts, including error handling and cleanup. ```typescript import { WebSocketChannel, SubscriptionNewHeadsEvent, SubscriptionStarknetEventsEvent, SubscribeEventsParams, TimeoutError, WebSocketNotConnectedError, } from 'starknet'; async function main() { // Create WebSocket channel const channel = new WebSocketChannel({ nodeUrl: 'wss://starknet-sepolia.public.blastapi.io/rpc/v0_9', autoReconnect: true, reconnectOptions: { retries: 5, delay: 2000, }, requestTimeout: 30000, maxBufferSize: 1000, }); try { // Wait for connection await channel.waitForConnection(); console.log('Connected to WebSocket'); // Subscribe to new block headers const headsSub: SubscriptionNewHeadsEvent = await channel.subscribeNewHeads({ blockIdentifier: 'latest', }); headsSub.on((blockHeader) => { console.log(`New block ${blockHeader.block_number}: ${blockHeader.block_hash}`); }); // Subscribe to contract events with filtering const eventParams: SubscribeEventsParams = { fromAddress: '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7', // ETH token finalityStatus: 'ACCEPTED_ON_L2', }; const eventsSub: SubscriptionStarknetEventsEvent = await channel.subscribeEvents(eventParams); eventsSub.on((eventData) => { console.log('Contract event:', eventData.event); }); // Subscribe to transaction receipts (RPC 0.9+) const receiptsSub = await channel.subscribeNewTransactionReceipts({ finalityStatus: ['ACCEPTED_ON_L2'], }); receiptsSub.on((receipt) => { console.log('New transaction receipt:', receipt.transaction_receipt.transaction_hash); }); // Keep running for demonstration await new Promise((resolve) => setTimeout(resolve, 60000)); // Clean up subscriptions await headsSub.unsubscribe(); await eventsSub.unsubscribe(); await receiptsSub.unsubscribe(); } catch (error) { if (error instanceof TimeoutError) { console.error('Connection timeout:', error.message); } else if (error instanceof WebSocketNotConnectedError) { console.error('WebSocket not connected:', error.message); } else { console.error('Unexpected error:', error); } } finally { // Close the connection channel.disconnect(); await channel.waitForDisconnection(); console.log('Disconnected from WebSocket'); } } main().catch(console.error); ``` -------------------------------- ### Start Local Development Server Source: https://github.com/starknet-io/starknet.js/blob/develop/www/README.md Starts a local development server for live previewing changes. Typically opens in a browser automatically. ```bash yarn start # or npm run start ``` -------------------------------- ### Install and Use a Starknet.js Plugin Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/plugins.md Demonstrates how to install a custom plugin using npm and then integrate it into a Starknet.js application by calling the `use` method on the provider. ```bash npm install my-starknet-plugin ``` ```typescript import { RpcProvider } from 'starknet'; import { myStarknetPlugin } from 'my-starknet-plugin'; const provider = new RpcProvider({ nodeUrl }); provider.use(myStarknetPlugin()); ``` -------------------------------- ### Install Dependencies Source: https://github.com/starknet-io/starknet.js/blob/develop/CONTRIBUTING.md Run this command in your terminal to install all necessary project dependencies. ```bash npm install ``` -------------------------------- ### Install Starknet.js Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/intro.md Install the Starknet.js library using npm. Use the '@next' tag for the latest features from the develop branch. ```bash # use the main branch npm install starknet # to use latest features (merges in develop branch) npm install starknet@next ``` -------------------------------- ### Install Starknet.js Source: https://github.com/starknet-io/starknet.js/blob/develop/README.md Install the latest official release or pre-release versions of the starknet package using npm. ```bash # latest official release (main branch) $ npm install starknet # or for latest pre-release version (develop branch) $ npm install starknet@next # or for latest beta release version (beta branch) $ npm install starknet@beta ``` -------------------------------- ### Install Dependencies Source: https://github.com/starknet-io/starknet.js/blob/develop/www/README.md Installs project dependencies using Yarn or npm. ```bash yarn # or npm i ``` -------------------------------- ### Run Documentation Locally Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/intro.md Set up a local development server to preview documentation changes. This requires installing Docusaurus dependencies. ```bash cd www npm install # install docusaurus npm run start # fires up a local documentation site ``` -------------------------------- ### Create Ledger Transporter and Signer (Node.js) Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/signature.md Example of creating a transporter for a Node.js script using `TransportNodeHid` and initializing a `LedgerSigner231`. This is used to get the public key and subsequently deploy an account. ```typescript import TransportNodeHid from '@ledgerhq/hw-transport-node-hid'; const myLedgerTransport: Transport = await TransportNodeHid.create(); const myLedgerSigner = new LedgerSigner231(myLedgerTransport, 0); const pubK = await myLedgerSigner.getPubKey(); const fullPubK = await myLedgerSigner.getFullPubKey(); // ... // deploy here an account related to this public key // ... const ledgerAccount = new Account({ provider: myProvider, address: ledger0addr, signer: myLedgerSigner, }); ``` -------------------------------- ### Connect to Starknet-Devnet Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/provider_instance.md Examples for connecting to a local starknet-devnet instance, specifying the correct RPC version based on the devnet version. ```typescript // For RPC 0.10.0 (starknet-devnet v0.7.0) const myProvider = new RpcProvider({ nodeUrl: 'http://127.0.0.1:5050/rpc' }); // For RPC 0.9.1 (starknet-devnet v0.6.1) const myProvider = new RpcProvider({ nodeUrl: 'http://127.0.0.1:5050/rpc' }); ``` -------------------------------- ### Conventional Commit Example - Correct Source: https://github.com/starknet-io/starknet.js/blob/develop/CONTRIBUTING.md Examples of correctly formatted commit messages following the Conventional Commits specification. 'feat' and 'fix' types are used for changelog compilation. ```bash fix: repair some bug test: rectify failing test chore: adjust formatting chore: add comments fix: repair some other bug ``` -------------------------------- ### Example Contract Addresses Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/multiCall.md Define the addresses of the contracts you intend to interact with. ```typescript const ethTokenAddress = '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7'; const bridgeAddress = '0x078f36c1d59dd29e00a0bb60aa2a9409856f4f9841c47f165aba5bab4225aa6b'; ``` -------------------------------- ### Sponsored Transaction Setup Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/paymaster.md Configure and use a PaymasterRpc for sponsored transactions. Ensure the PAYMASTER_API_KEY environment variable is set. ```typescript const myPaymasterRpc = new PaymasterRpc({ nodeUrl: 'https://sepolia.paymaster.avnu.fi', headers: { 'x-paymaster-api-key': process.env.PAYMASTER_API_KEY }, }); const myAccount = new Account({ provider: myProvider, address: accountAddress, signer: privateKey, paymaster: myPaymasterRpc, }); const feesDetails: PaymasterDetails = { feeMode: { mode: 'sponsored' }, }; const res = await myAccount.executePaymasterTransaction([myCall], feesDetails); const txR = await myProvider.waitForTransaction(res.transaction_hash); ``` -------------------------------- ### Subscribe to All New Blocks Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/websocket_channel.md Example of subscribing to all new block headers using the Starknet.js channel. This method requires no parameters to receive all block updates. ```typescript // Subscribe to all new blocks const sub1 = await channel.subscribeNewHeads(); ``` -------------------------------- ### Raw Event Data Structure Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/events.md Example of the raw structure of an event as retrieved from a Starknet transaction receipt. ```json [ { from_address: '0x47cb13bf174043adde61f7bea49ab2d9ebc575b0431f85bcbfa113a6f93fc4', keys: ['0x3ba972537cb2f8e811809bba7623a2119f4f1133ac9e955a53d5a605af72bf2', '0x8'], data: ['0x4d6567612050616e69632e'], }, ] ``` -------------------------------- ### Set Test RPC URL and Account Details Source: https://github.com/starknet-io/starknet.js/blob/develop/CONTRIBUTING.md Configure these environment variables to point to a specific RPC node and account for testing purposes. Examples for Pathfinder and Sepolia testnet are provided. ```bash export TEST_RPC_URL=http://192.168.1.44:9545/rpc/v0_9 # example of a Pathfinder node located in your local network export TEST_RPC_URL=https://starknet-sepolia.public.blastapi.io/rpc/v0_9 # example of a public Sepolia testnet node export TEST_ACCOUNT_ADDRESS=0x065A822f0000000000000000000000000c26641 export TEST_ACCOUNT_PRIVATE_KEY=0x02a80000000000000000000000001754438a ``` -------------------------------- ### Connect to Mainnet RPC Nodes Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/provider_instance.md Examples of instantiating RpcProvider to connect to various Mainnet RPC node providers like Zan, Lava, and Alchemy, specifying different RPC versions. ```typescript // Zan node RPC 0.10.0 for Mainnet (0.9 also available): const providerZanMainnet = new RpcProvider({ nodeUrl: 'https://api.zan.top/public/starknet-mainnet/rpc/v0_10', }); // Lava node RPC 0.9.1 for Mainnet: const providerMainnetLava = new RpcProvider({ nodeUrl: 'https://g.w.lavanet.xyz:443/gateway/strk/rpc-http/' + lavaMainnetKey, }); // Alchemy node RPC 0.9.1 for Mainnet (0.10 also available): const providerAlchemyMainnet = new RpcProvider({ nodeUrl: 'https://starknet-mainnet.g.alchemy.com/starknet/version/rpc/v0_9/' + alchemyKey, }); // Public Lava node RPC 0.9.1 for Mainnet (0.8 also available): const providerLavaMainnet = new RpcProvider({ nodeUrl: 'https://rpc.starknet.lava.build/rpc/v0_9', }); ``` -------------------------------- ### Run Full Project Test Coverage Source: https://github.com/starknet-io/starknet.js/blob/develop/CONTRIBUTING.md Execute this command to get a complete test coverage report for the entire project. This is useful for identifying areas that need more testing. ```bash npm run test:coverage ``` -------------------------------- ### Connect to Sepolia Testnet RPC Nodes Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/provider_instance.md Examples of instantiating RpcProvider to connect to Sepolia Testnet RPC node providers like Zan and Lava, specifying different RPC versions. ```typescript // Zan node RPC 0.10.0 for Mainnet (0.9 also available): const providerZanSepoliaTestnet = new RpcProvider({ nodeUrl: 'https://api.zan.top/public/starknet-sepolia/rpc/v0_10', }); // Zan node RPC 0.9.0 for Sepolia Testnet (0.8 also available): const providerZanSepoliaTestnet = new RpcProvider({ nodeUrl: 'https://api.zan.top/public/starknet-sepolia/rpc/v0_9', }); // Public Lava node RPC 0.9.1 for Sepolia Testnet (0.8 also available): const providerSepoliaTestnetLavaPublic = new RpcProvider({ nodeUrl: 'https://rpc.starknet-testnet.lava.build/rpc/v0_9', }); ``` -------------------------------- ### Deploying Account for Paymaster Transactions Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/paymaster.md Deploy an account if it's not already deployed before processing a paymaster transaction. This example estimates fees and executes the transaction. ```typescript // starknetWalletObject is the wallet selected by get-starknet v4. // Get data to deploy the account: const deploymentData: AccountDeploymentData = await wallet.deploymentData(starknetWalletObject); const feesDetails: PaymasterDetails = { feeMode: { mode: 'default', gasToken }, deploymentData: { ...deploymentData, version: 1 as 1 }, }; // MyWalletAccount is the WalletAccount instance related to the selected wallet. const estimatedFees: PaymasterFeeEstimate = await MyWalletAccount.estimatePaymasterTransactionFee( [], feesDetails ); const resp = await MyWalletAccount.executePaymasterTransaction( [], feesDetails, estimatedFees.suggested_max_fee_in_gas_token ); const txR = await newAccount.provider.waitForTransaction(resp.transaction_hash); ``` -------------------------------- ### Adding Plugins at Runtime Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/plugins.md Plugins can be added dynamically to an existing provider instance at runtime using the `.use()` method. This is useful for extending functionality after the initial setup. ```typescript const provider = new RpcProvider({ nodeUrl, plugins: false }); // Provider starts without any plugins // provider.getStarkName() ❌ Error // Add plugin at runtime provider.use(starknetId()); // Now plugin methods are available await provider.getStarkName(address); // ✅ Works ``` -------------------------------- ### Interact with Deployed Contract using Generated Types Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/abi_typescript.md An example demonstrating how to interact with a deployed Starknet contract using TypeScript types generated from its ABI. Ensure the ABI is correctly imported. ```typescript import { Contract, RpcProvider, constants } from 'starknet'; import { ABI } from './abi'; const address = '0x00000005dd3d2f4429af886cd1a3b08289dbcea99a294197e9eb43b0e0325b4b'; const myProvider = new RpcProvider({ nodeUrl: constants.NetworkName.SN_MAIN }); // Create typed contract instance const myContract = new Contract({ abi: ABI, address, providerOrAccount: myProvider, }).typedv2(ABI); // Enjoy type inference and autocompletion const primaryInterfaceId = await myContract.get_primary_interface_id(); const protocolFees = await myContract.get_protocol_fees_collected('0x1'); ``` -------------------------------- ### Rapid Fire Gaming Transactions with FastExecute Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/plugins.md Example of executing multiple transactions in quick succession using the fastExecute method, suitable for gaming applications. Includes a fallback to regular transaction waiting if fast mode times out. ```typescript const calls = [ { contractAddress: gameAddress, entrypoint: 'move', calldata: [...] }, { contractAddress: gameAddress, entrypoint: 'attack', calldata: [...] }, { contractAddress: gameAddress, entrypoint: 'defend', calldata: [...] }, ]; // Execute transactions as fast as possible for (const call of calls) { const resp = await account.fastExecute(call, { tip: estimatedTip }); if (!resp.isReady) { // Fallback to regular wait if fast mode times out await provider.waitForTransaction(resp.txResult.transaction_hash); } console.log(`Transaction ${resp.txResult.transaction_hash} confirmed`); } ``` -------------------------------- ### Build Documentation (from /www directory) Source: https://github.com/starknet-io/starknet.js/blob/develop/www/README.md Builds the documentation from the /www directory, manually setting the Git revision override. ```bash # from the /www documentation directory, manually set the version GIT_REVISION_OVERRIDE=vX.Y.Z npm run build ``` -------------------------------- ### Build Documentation (Module Version) Source: https://github.com/starknet-io/starknet.js/blob/develop/www/README.md Builds the documentation using the version specified in the project's package.json. Executed from the root directory. ```bash # from the root directory, use the module version from package.json npm run docs:build:version ``` -------------------------------- ### Conventional Commit Example - Incorrect Source: https://github.com/starknet-io/starknet.js/blob/develop/CONTRIBUTING.md Examples of incorrectly formatted commit messages that do not adhere to the Conventional Commits specification. ```bash fix: repair some bug fix: rectify failing test fix: adjust formatting fix: add comments fix: repair some other bug ``` -------------------------------- ### Version Documentation (from /www directory) Source: https://github.com/starknet-io/starknet.js/blob/develop/www/README.md Versions the documentation from the /www directory by manually specifying the version. ```bash # from the /www documentation directory, manually set the version npm run docusaurus docs:version X.Y.Z ``` -------------------------------- ### Instantiate WalletAccount with get-starknet v4 Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/walletAccount.md Connect to a Starknet provider and select a wallet using the get-starknet v4 library to create a WalletAccount instance. ```typescript import { connect } from '@starknet-io/get-starknet'; // v4.0.3 min import { WalletAccount, wallet } from 'starknet'; // v7.0.1 min const myFrontendProviderUrl = 'https://starknet-sepolia.public.blastapi.io/rpc/v0_8'; // standard UI to select a wallet: const selectedWalletSWO = await connect({ modalMode: 'alwaysAsk', modalTheme: 'light' }); const myWalletAccount = await WalletAccount.connect( { nodeUrl: myFrontendProviderUrl }, selectedWalletSWO ); ``` -------------------------------- ### Import Account and RpcProvider Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/connect_account.md Import necessary classes from the starknet.js library to initialize providers and accounts. ```typescript import { Account, RpcProvider } from 'starknet'; ``` -------------------------------- ### Cairo Event Structure Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/events.md Example of a Cairo struct defining an event with keyed and data fields. ```rust #[derive(Drop, starknet::Event)] struct EventPanic { #[key] errorType: u8, errorDescription: felt252, } ``` -------------------------------- ### Wait for Transaction and Get Receipt Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/events.md Waits for a transaction to be confirmed and retrieves its receipt using Starknet.js. ```typescript const txReceipt = await myProvider.waitForTransaction(transactionHash); ``` -------------------------------- ### Build Documentation (Manually Set Version) Source: https://github.com/starknet-io/starknet.js/blob/develop/www/README.md Builds the documentation with a manually specified Git revision override. Executed from the root directory. ```bash # from the root directory, manually set the version npm run docs:build --git-revision-override=vX.Y.Z ``` -------------------------------- ### Instantiate WalletAccountV5 with get-starknet v5 Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/walletAccount.md Connect to a wallet and instantiate a WalletAccountV5. Requires a provider URL and a selected wallet object. The provider is used for reading blockchain data. ```typescript import { createStore, type Store } from '@starknet-io/get-starknet/discovery'; // v5.0.0 min import { type WalletWithStarknetFeatures } from '@starknet-io/get-starknet/standard/features'; import { WalletAccountV5, walletV5 } from 'starknet'; // v7.2.0 min const myFrontendProviderUrl = 'https://free-rpc.nethermind.io/sepolia-juno/v0_8'; const store: Store = createStore(); const walletsList: WalletWithStarknetFeatures[] = store.getWallets(); // Create you own Component to select one of these wallets. // Hereunder, selection of 2nd wallet of the list. const selectedWallet: WalletWithStarknetFeatures = walletsList[1]; const myWalletAccount: WalletAccountV5 = await WalletAccountV5.connect( { nodeUrl: myFrontendProviderUrl }, selectedWallet ); ``` -------------------------------- ### Version Documentation (Module Version) Source: https://github.com/starknet-io/starknet.js/blob/develop/www/README.md Versions the documentation using the module version from package.json. Executed from the root directory. ```bash # from the root directory, use the module version from package.json npm run docs:version ``` -------------------------------- ### Get Write Chain ID Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/walletAccount.md Request the chain ID for writing to Starknet using the wallet provider. ```typescript const writeChainId = await wallet.requestChainId(myWalletAccount.walletProvider); ``` -------------------------------- ### Import RpcProvider Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/provider_instance.md Import the RpcProvider class from the starknet library. This is the first step to connect to a Starknet network. ```typescript import { RpcProvider } from 'starknet'; ``` -------------------------------- ### Parsed Event Data Structure Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/events.md Example of parsed event data after using Starknet.js's parseEvents method. ```json events = [ { EventPanic: { errorType: 8n, errorDescription: 93566154138418073030976302n }, }, ]; ``` -------------------------------- ### Get Chain ID for Reading with WalletAccountV5 Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/walletAccount.md Retrieve the chain ID for reading from Starknet directly from the WalletAccountV5 instance. ```typescript const readChainId = await myWalletAccount.getChainId(); ``` -------------------------------- ### Create and Deploy Custom Account Abstraction Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/create_account.md Generates keys, declares a custom account contract, calculates its address, funds it, and deploys the account abstraction. Requires a running starknet-devnet instance. ```typescript // new account abstraction // Generate public and private key pair. const AAprivateKey = stark.randomAddress(); console.log('New account:\nprivateKey=', AAprivateKey); const AAstarkKeyPub = ec.starkCurve.getStarkKey(AAprivateKey); console.log('publicKey=', AAstarkKeyPub); // declare the contract const compiledAAaccount = json.parse( fs .readFileSync('./__mocks__/cairo/myAccountAbstraction/myAccountAbstraction.json') .toString('ascii') ); const { transaction_hash: declTH, class_hash: decCH } = await account0.declare({ contract: compiledAAaccount, }); console.log('Customized account class hash =', decCH); await myProvider.waitForTransaction(declTH); // Calculate future address of the account const AAaccountConstructorCallData = CallData.compile({ super_admin_address: account0.address, publicKey: AAstarkKeyPub, }); const AAcontractAddress = hash.calculateContractAddressFromHash( AAstarkKeyPub, AAaccountClassHash, AAaccountConstructorCallData, 0 ); console.log('Precalculated account address=', AAcontractAddress); // fund account address before account creation const { data: answer } = await axios.post( 'http://127.0.0.1:5050/mint', { address: AAcontractAddress, amount: 50_000_000_000_000_000_000, unit: 'FRI', }, { headers: { 'Content-Type': 'application/json' } } ); console.log('Answer mint =', answer); // deploy account const AAaccount = new Account({ provider: myProvider, address: AAcontractAddress, signer: AAprivateKey, }); const { transaction_hash, contract_address } = await AAaccount.deployAccount({ classHash: AAaccountClassHash, constructorCalldata: AAaccountConstructorCallData, addressSalt: AAstarkKeyPub, }); await myProvider.waitForTransaction(transaction_hash); console.log('✅ New customized account created.\n address =', contract_address); ``` -------------------------------- ### Initialize Devnet Provider and Account Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/create_account.md Connects to a local Starknet-devnet RPC provider and initializes a pre-deployed account for interacting with the network. ```typescript import { Account, ec, json, stark, RpcProvider, hash, CallData } from 'starknet'; import fs from 'fs'; import axios from 'axios'; // connect provider const myProvider = new RpcProvider({ nodeUrl: 'http://127.0.0.1:5050/rpc' }); // initialize existing pre-deployed account 0 of Devnet const privateKey0 = '0x71d7bb07b9a64f6f78ac4c816aff4da9'; const accountAddress0 = '0x64b48806902a367c8598f4f95c305e8c1a1acba5f082d294a43793113115691'; const account0 = new Account({ provider: myProvider, address: accountAddress0, signer: privateKey0, }); ``` -------------------------------- ### FastExecute Plugin Usage Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/plugins.md Demonstrates how to initialize the provider with the FastExecute plugin and use the fastExecute method for rapid transaction execution. Requires RPC 0.9+ and provider initialized with BlockTag.PRE_CONFIRMED. ```typescript import { RpcProvider, Account, BlockTag, fastExecute } from 'starknet'; // Plugin is included by default, no need to explicitly add it const provider = new RpcProvider({ nodeUrl, blockIdentifier: BlockTag.PRE_CONFIRMED, // Required for fastExecute to work }); const account = new Account({ provider, address, signer }); // Fast execute is available immediately const resp = await account.fastExecute( call, { tip: recommendedTip }, { retries: 30, retryInterval: 500 } ); if (resp.isReady) { // Next transaction can be sent immediately await account.fastExecute(nextCall); } ``` -------------------------------- ### Enabling Specific Plugins Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/plugins.md Demonstrates how to initialize the RpcProvider and enable only specific plugins, such as StarknetId, while excluding others like FastExecute. ```typescript import { starknetId } from 'starknet'; const provider = new RpcProvider({ nodeUrl, plugins: [starknetId()], // Only StarknetId, no fastExecute }); ``` -------------------------------- ### Cairo Enum Definition Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/cairo_enum.md Defines a custom enum 'MyEnum' with various variants, some of which hold data. This is a Rust/Cairo code example. ```rust #[derive(Drop, Serde, Append)] enum MyEnum { Response: Order, Warning: felt252, Error: (u16,u16), Critical: Array, Empty:(), } fn test(self: @ContractState, val1: u16) -> MyEnum { if val1 < 100 { return MyEnum::Error((3,4)); } if val1 == 100 { return MyEnum::Warning('attention:100'); } if val1 < 150 { let mut arr=ArrayTrait::new(); arr.append(5); arr.append(6); return MyEnum::Critical(arr); } if val1<200 { return MyEnum::Empty(()); } MyEnum::Response(Order { p1: 1, p2: val1 }) } ``` -------------------------------- ### Using Default Plugins Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/plugins.md Default plugins are automatically available on RpcProvider and Account instances. Ensure the nodeUrl is provided and blockIdentifier is set to PRE_CONFIRMED for the fastExecute plugin. ```typescript import { RpcProvider, Account, BlockTag } from 'starknet'; const provider = new RpcProvider({ nodeUrl, blockIdentifier: BlockTag.PRE_CONFIRMED, // Required for fastExecute plugin to work }); const account = new Account({ provider, address, signer: privateKey }); // StarknetId plugin methods (automatically available) const name = await provider.getStarkName(address); const addr = await provider.getAddressFromStarkName('example.stark'); const profile = await provider.getStarkProfile(address); // BrotherId plugin methods (automatically available) const brotherName = await provider.getBrotherName(address); // FastExecute plugin methods (automatically available) const resp = await account.fastExecute(call, { tip: estimatedTip }); if (resp.isReady) { // Next transaction can be sent immediately } // On Account, some methods default to using account.address const myName = await account.getStarkName(); // Uses account.address by default ``` -------------------------------- ### Deploy from Existing Class Hash (Provide ABI) Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/create_contract.md Deploy a contract instance using an existing class hash and a provided ABI for faster deployment. This avoids fetching the ABI from the network. Include the class hash, ABI, account, and constructor arguments. ```typescript // Provide ABI to skip network fetch const myContract = await Contract.factory({ classHash: '0x1234...', // Existing class hash abi: contractAbi, // Your contract ABI account: myAccount, constructorCalldata: { name: 'MyToken', symbol: 'MTK', decimals: 18, initialSupply: 1000n * 10n ** 18n, recipient: myAccount.address, }, }); ``` -------------------------------- ### Use WalletAccount as a Provider Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/walletAccount.md Utilize a WalletAccount instance as a provider to access Starknet RPC methods, such as getting the block number. ```typescript const bl = await myWalletAccount.getBlockNumber(); // bl = 2374543 ``` -------------------------------- ### Removed Global Singletons in v9 Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/migrate.md In v9, `defaultProvider` and `defaultPaymaster` were global singletons that have been removed in v10. This example shows the deprecated usage. ```typescript import { defaultProvider, defaultPaymaster } from 'starknet'; // These no longer exist const result = await defaultProvider.getBlock('latest'); const tokens = await defaultPaymaster.getSupportedTokens(); ``` -------------------------------- ### Version Documentation (Manually Set Version) Source: https://github.com/starknet-io/starknet.js/blob/develop/www/README.md Versions the documentation with a manually specified version override. Executed from the root directory. ```bash # from the root directory, manually set the version npm run docs:version --version-override=X.Y.Z ``` -------------------------------- ### Cairo Enum Definition for Sending Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/cairo_enum.md This is a Rust/Cairo code example defining the same 'MyEnum' structure used for sending data to a Starknet contract. ```rust #[derive(Drop, Serde, Append)] enum MyEnum { Response: Order, Warning: felt252, Error: (u16,u16), Critical: Array, Empty:(), } fn test2a(self: @ContractState, customEnum:MyEnum ) -> u16{ match customEnum{ MyEnum::Response(my_order)=>{return my_order.p2;}, MyEnum::Warning(val)=>{return 0x13_u16;}, MyEnum::Error((a,b))=>{return b;}, MyEnum::Critical(myArray)=>{return 0x3c_u16;}, MyEnum::Empty(_)=>{return 0xab_u16;} } } ``` -------------------------------- ### Cairo Result Enum Example Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/cairo_enum.md This Cairo code defines a function that returns a Result enum. Starknet.js represents this as a CairoResult class. ```rust fn test(self: @ContractState, val1: u16) -> Result { if val1 < 100 { return Result::Err(14); } Result::Ok(val1) } ``` -------------------------------- ### Deploy from Existing Class Hash (Fetch ABI) Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/create_contract.md Deploy a contract instance using an existing class hash. The ABI will be automatically fetched from the network. Provide the class hash, your account, and constructor arguments. ```typescript // ABI will be automatically fetched from the network const myContract = await Contract.factory({ classHash: '0x1234...', // Existing class hash account: myAccount, constructorCalldata: { name: 'MyToken', symbol: 'MTK', decimals: 18, initialSupply: 1000n * 10n ** 18n, recipient: myAccount.address, }, }); // Contract is ready with automatically fetched ABI const totalSupply = await myContract.totalSupply(); ``` -------------------------------- ### Invoke Contract to Emit Event Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/events.md Example of invoking a Starknet contract function that is expected to emit an event. The transaction hash is returned. ```typescript const transactionHash = myContract.invoke('emitEventPanic', [8, 'Mega Panic.']); ``` -------------------------------- ### Cairo Option Enum Example Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/cairo_enum.md This Cairo code defines a function that returns an Option enum. Starknet.js represents this as a CairoOption class. ```rust fn test(self: @ContractState, val1: u16) -> Option { if val1 < 100 { return Option::None(()); } Option::Some(Order { p1: 18, p2: val1 }) } ``` -------------------------------- ### Deploy Website (using SSH) Source: https://github.com/starknet-io/starknet.js/blob/develop/www/README.md Deploys the website using SSH, typically for hosting services that support it. ```bash USE_SSH=true yarn deploy # or USE_SSH=true npm run deploy ``` -------------------------------- ### Get RPC Specification Version Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/provider_instance.md Retrieve the RPC version supported by the connected node. This is useful for ensuring compatibility between Starknet.js and the node. ```typescript const resp = await myProvider.getSpecVersion(); console.log('RPC version =', resp); // result: RPC version = 0.10.0 ``` -------------------------------- ### Initialize LedgerSigner for Older App Version Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/signature.md Demonstrates how to initialize the `LedgerSigner` for the older v1.1.1 Starknet APP version. ```typescript const myLedgerSigner = new LedgerSigner111(myLedgerTransport, 0); ``` -------------------------------- ### Connect to Local Juno Node Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/provider_instance.md Initialize RpcProvider to connect to a local Juno node. Ensure Juno is launched with the correct host option if running on a separate machine in the local network. ```typescript const myProvider = new RpcProvider({ nodeUrl: 'http://127.0.0.1:6060/v0_10' }); ``` -------------------------------- ### Get Chain ID for Writing with WalletAccountV5 Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/walletAccount.md Obtain the chain ID for writing to Starknet by requesting it from the wallet provider associated with the WalletAccountV5. ```typescript const writeChainId = await walletV5.requestChainId(myWalletAccount.walletProvider); ``` -------------------------------- ### Connect to Starknet Devnet Account Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/connect_account.md Initialize an RpcProvider for Starknet Devnet and connect to a pre-deployed account using its address and private key. ```typescript // initialize provider for Devnet const myProvider = new RpcProvider({ nodeUrl: 'http://127.0.0.1:5050/rpc' }); // initialize existing account 0 pre-deployed on Devnet const accountAddress = '0x064b48806902a367c8598f4f95c305e8c1a1acba5f082d294a43793113115691'; const privateKey = '0x0000000000000000000000000000000071d7bb07b9a64f6f78ac4c816aff4da9'; const myAccount = new Account({ provider: myProvider, address: accountAddress, signer: privateKey, }); ``` -------------------------------- ### Handling Hexadecimal Numbers from Cairo 1 Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/define_call_message.md To get a string representation of a hexadecimal number from a Cairo 1 contract, use the `num.toHex()` function. ```typescript const res=myContract.call(...) const address: string = num.toHex(res); ``` -------------------------------- ### Get Actual Fees Paid for Transaction Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/estimate_fees.md Retrieve and log the actual fees paid for a transaction after it has been processed. Handles both successful and other transaction states. ```typescript const txR = await myProvider.waitForTransaction(declareResponse.transaction_hash); txR.match({ success: (txR: SuccessfulTransactionReceiptResponse) => { console.log('Fees paid =', txR.actual_fee); }, _: () => {}, }); ``` -------------------------------- ### Declare and Deploy a New Contract Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/create_contract.md Use this snippet to declare a new contract class and deploy an instance in a single step. Ensure you have the compiled Sierra and CASM files for your contract and an initialized Starknet account. ```typescript import { Contract } from 'starknet'; // Declare and deploy in one step const myContract = await Contract.factory({ contract: compiledSierra, // Compiled Sierra contract casm: compiledCasm, // Compiled CASM file account: myAccount, // Deploying account constructorCalldata: { name: 'MyToken', symbol: 'MTK', decimals: 18, initialSupply: 1000n * 10n ** 18n, recipient: myAccount.address, }, }); console.log('Contract deployed at:', myContract.address); console.log('Class hash:', myContract.classHash); // Contract is immediately ready to use const balance = await myContract.balanceOf(myAccount.address); ``` -------------------------------- ### Default Plugin Behavior in v10 Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/migrate.md StarknetId and BrotherId plugins are automatically installed by default in v10. No changes are needed for existing code using these plugins. ```typescript // These work out of the box in v10 (no changes needed) const provider = new RpcProvider({ nodeUrl }); await provider.getStarkName(address); // ✅ Works const account = new Account(provider, address, privateKey); await account.getStarkName(); // ✅ Works ``` -------------------------------- ### Deploy ERC20 using Contract.factory() Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/use_ERC20.md Recommended method for deploying an ERC20 token contract. Requires compiled contract artifacts (Sierra and CASM) and constructor arguments. ```typescript import { Contract, CallData, cairo } from 'starknet'; // Deploy ERC20 using the factory method const erc20Contract = await Contract.factory({ compiledContract: compiledSierra, account: myAccount, casm: compiledCasm, constructorArguments: { name: 'niceToken', symbol: 'NIT', fixed_supply: cairo.uint256(20n * 10n ** 18n), recipient: myAccount.address, }, }); console.log('ERC20 deployed at:', erc20Contract.address); ``` -------------------------------- ### Initialize Provider and Paymaster in v10 Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/migrate.md In v10, global singletons are removed. Use `RpcProvider.create()` for automatic node version detection or manual creation. Paymasters require a new instance. ```typescript // For Provider: Use RpcProvider.create() for automatic node version detection const myProvider = await RpcProvider.create(); const myProvider = await RpcProvider.create({ nodeUrl: constants.NetworkName.SN_MAIN }); // Or create manually if you know the RPC version const myProvider = new RpcProvider({ nodeUrl: '...' }); // For Paymaster: Create a new instance const myPaymaster = new PaymasterRpc(); const myPaymaster = new PaymasterRpc({ nodeUrl: 'https://sepolia.paymaster.avnu.fi' }); // Usage const result = await myProvider.getBlock('latest'); const tokens = await myPaymaster.getSupportedTokens(); ``` -------------------------------- ### Actual Fees Paid (ETH) Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/estimate_fees.md Example of the JSON response format for actual fees paid when using ETH, showing the unit as WEI and the amount in hexadecimal. ```json { "unit": "WEI", "amount": "0x70c6fff3c000" } ``` -------------------------------- ### Use Batching with RpcProvider Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/provider_instance.md Demonstrates how to use the BatchClient with RpcProvider by setting the batch option to 0 for immediate batching. This reduces overhead by grouping requests. ```typescript const myBatchProvider = new RpcProvider({ batch: 0, }); const [getBlockResponse, blockHashAndNumber, txCount] = await Promise.all([ myBatchProvider.getBlock(), myBatchProvider.getBlockLatestAccepted(), myBatchProvider.getBlockTransactionCount('latest'), ]); // ... usage of getBlockResponse, blockHashAndNumber, txCount ``` -------------------------------- ### Actual Fees Paid (STRK) Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/estimate_fees.md Example of the JSON response format for actual fees paid when using STRK, showing the unit as FRI and the amount in hexadecimal. ```json { "unit": "FRI", "amount": "0x3a4f43814e180000" } ``` -------------------------------- ### Create Contract Instances (Read-Only and Read-Write) Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/connect_contract.md Instantiate a contract object for read-only access using a Provider or for read-write access using an Account. Ensure you have the contract's ABI and address. ```typescript import { Contract, RpcProvider, Account } from 'starknet'; // For read-only access const readOnlyContract = new Contract({ abi: contractAbi, address: contractAddress, providerOrAccount: myProvider, // Provider for reading }); // For read-write access const readWriteContract = new Contract({ abi: contractAbi, address: contractAddress, providerOrAccount: myAccount, // Account for writing }); ``` -------------------------------- ### Update Plugin Imports Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/migrate.md If you import plugin classes directly, update their import paths and class names. For example, `StarknetId` is now `StarknetIdImpl` and imported from `starknet` instead of `starknet/provider/extensions`. ```typescript // Update plugin imports (only if you import them directly) import { StarknetIdImpl } from 'starknet'; // ✅ Was StarknetId import { BrotherIdImpl } from 'starknet'; // ✅ Was BrotherId ``` -------------------------------- ### StarknetId Plugin Initialization Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/plugins.md Illustrates how to initialize the StarknetId plugin using its factory function or use its static methods directly with a provider and address. ```typescript import { starknetId, StarknetIdImpl } from 'starknet'; // Plugin factory const plugin = starknetId(); // Or use static methods directly const name = await StarknetIdImpl.getStarkName(provider, address); ``` -------------------------------- ### Create a Basic WebSocket Channel Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/websocket_channel.md Instantiate the WebSocketChannel with your Starknet node's WebSocket URL and wait for the initial connection. ```typescript const channel = new WebSocketChannel({ nodeUrl: 'wss://your-starknet-node/rpc/v0_9', }); // It's good practice to wait for the initial connection. await channel.waitForConnection(); ``` -------------------------------- ### Build Static Website Source: https://github.com/starknet-io/starknet.js/blob/develop/www/README.md Generates the static content for the website, usually placed in a 'build' directory, ready for hosting. ```bash yarn build # or npm run build ``` -------------------------------- ### Handling WebSocket Channel Errors Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/websocket_channel.md Illustrates how to catch and handle specific errors thrown by the Starknet.js WebSocket channel, such as timeouts or connection issues. Provides examples for TimeoutError and WebSocketNotConnectedError. ```typescript try { const result = await channel.sendReceive('starknet_chainId'); } catch (e) { if (e instanceof TimeoutError) { console.error('The request timed out!'); } else if (e instanceof WebSocketNotConnectedError) { console.error('The WebSocket is not connected.'); } else { console.error('An unknown error occurred:', e); } } ``` -------------------------------- ### Get L1 Messages Status Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/l1_message.md Retrieve the status of messages sent from L1 to L2 using the L1 transaction hash. This function helps track the progress of cross-chain communication. ```typescript // For L1->L2 messages const l1MessagesStatus = await myProvider.getL1MessagesStatus(l1TransactionHash); ``` -------------------------------- ### Subscribe to New Transaction Receipts with Filters Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/websocket_channel.md Example of subscribing to new transaction receipts with filters for finality status and sender addresses. Allows for monitoring specific types of transaction receipts. ```typescript // Subscribe with filters const sub2 = await channel.subscribeNewTransactionReceipts({ finalityStatus: ['ACCEPTED_ON_L2'], // Filter by finality status senderAddress: ['0x1234...', '0x5678...'], // Filter by sender addresses }); ``` -------------------------------- ### Deploy ERC20 using Account Methods Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/use_ERC20.md Alternative method for deploying an ERC20 token using `declareAndDeploy`. Provides more control over the deployment process. ```typescript // Alternative: using declareAndDeploy for more control const erc20CallData = new CallData(compiledSierra.abi); const constructorCallData = erc20CallData.compile('constructor', { name: 'niceToken', symbol: 'NIT', fixed_supply: cairo.uint256(20n * 10n ** 18n), recipient: myAccount.address, }); const deployResponse = await myAccount.declareAndDeploy({ contract: compiledSierra, casm: compiledCasm, constructorCalldata: constructorCallData, }); // Create contract instance const erc20 = new Contract({ abi: compiledSierra.abi, address: deployResponse.deploy.contract_address, providerOrAccount: myAccount, }); ``` -------------------------------- ### Deploy OpenZeppelin Account Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/create_account.md Deploys the OpenZeppelin account contract to the Starknet network. This step requires the account to be pre-funded. ```typescript const OZaccount = new Account({ provider: myProvider, address: OZcontractAddress, signer: privateKey, }); const { transaction_hash, contract_address } = await OZaccount.deployAccount({ classHash: OZaccountClassHash, constructorCalldata: OZaccountConstructorCallData, addressSalt: starkKeyPub, }); await myProvider.waitForTransaction(transaction_hash); console.log('✅ New OpenZeppelin account created.\n address =', contract_address); ``` -------------------------------- ### Deploy Ethereum-compatible Account Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/create_account.md Deploys an Ethereum-compatible account to the StarkNet network using pre-calculated parameters. Requires the provider, account address, and signer. ```typescript const ethAccount = new Account({ provider: myProvider, address: contractETHaddress, signer: ethSigner, }); const deployPayload = { classHash: accountEthClassHash, constructorCalldata: accountETHconstructorCalldata, addressSalt: salt, }; const estimatedFees = await ethAccount.estimateAccountDeployFee(deployPayload, { skipValidate: false, }); const { transaction_hash, contract_address } = await ethAccount.deployAccount(deployPayload, { skipValidate: false, }); await myProvider.waitForTransaction(transaction_hash); console.log('✅ New Ethereum account final address =', contract_address); ``` -------------------------------- ### Get Supported Gas Tokens Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/paymaster.md Retrieve a list of tokens that the Paymaster service supports for paying gas fees. This can be done either through the account instance or directly via the PaymasterRpc instance. ```typescript const supported = await myAccount.paymaster.getSupportedTokens(); ``` ```typescript const supported = await myPaymaster.getSupportedTokens(); ``` -------------------------------- ### Create Provider with Automatic RPC Version Detection Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/provider_instance.md Use RpcProvider.create() to automatically detect the RPC version and configure the provider. This method is slightly slower due to an additional network request. ```typescript // Automatically detects RPC version and configures the correct channel const defaultProvider = await RpcProvider.create(); const defaultProvider = await RpcProvider.create({ nodeUrl: constants.NetworkName.SN_MAIN }); ``` -------------------------------- ### Disabling All Plugins Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/plugins.md Shows how to initialize the RpcProvider without any plugins, which disables features like fastExecute. ```typescript const provider = new RpcProvider({ nodeUrl, plugins: false, // No plugins }); // fastExecute not available // account.fastExecute() ❌ Error ``` -------------------------------- ### Read Ledger Starknet App Version Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/account/signature.md Code snippet to send a command to the Ledger transport to retrieve the installed Starknet application version. The response is parsed to display the version in a standard format. ```typescript const resp = await myLedgerTransport.send(Number('0x5a'), 0, 0, 0); const appVersion = resp[0] + '.' + resp[1] + '.' + resp[2]; console.log('version=', appVersion); ``` -------------------------------- ### Adjust Key Filter for Nested Events Source: https://github.com/starknet-io/starknet.js/blob/develop/www/docs/guides/contracts/events.md When an event is nested within a Cairo component, the key filter needs to be adjusted to account for additional hashes. This example shows how to skip the first hash. ```typescript const keyFilter = [[], [num.toHex(hash.starknetKeccak('EventPanic'))]]; ```