### Basic Hono App Setup
Source: https://hono.dev/
This snippet demonstrates the basic setup of a Hono web application. It initializes a Hono app and defines a simple GET route for the root path that returns 'Hello Hono!'. This is a foundational example for starting with Hono.
```javascript
import { Hono } from 'hono'
const app = new Hono()
app.get('/', (c) => c.text('Hello Hono!'))
export default app
```
--------------------------------
### Basic Hono App Setup (TypeScript)
Source: https://hono.dev/docs
This snippet demonstrates the fundamental setup of a Hono application. It imports the Hono class, creates an app instance, defines a simple GET route for the root path that returns 'Hono!', and exports the app. This is a foundational example for getting started with Hono.
```typescript
import { Hono } from 'hono'
const app = new Hono ()
app.get('/', (c) => c.text('Hono!'))
export default app
```
--------------------------------
### Install Wagmi CLI
Source: https://wagmi.sh/cli/getting-started
Installs the Wagmi CLI tool as a development dependency in your project. This command is compatible with pnpm, npm, yarn, and bun package managers.
```bash
pnpm add -D @wagmi/cli
```
```bash
npm install --save-dev @wagmi/cli
```
```bash
yarn add -D @wagmi/cli
```
```bash
bun add -D @wagmi/cli
```
--------------------------------
### Install ABIType with pnpm, bun, or yarn
Source: https://abitype.dev/guide/getting-started
Installs the ABIType package into your project using your preferred package manager (pnpm, bun, or yarn). ABIType requires typescript@>=5.0.4.
```bash
pnpm add abitype
```
--------------------------------
### Advanced Wagmi CLI Configuration with Contracts and Plugins
Source: https://wagmi.sh/cli/getting-started
An example Wagmi CLI configuration file demonstrating how to include contracts (e.g., ERC-20 ABI from Viem) and plugins like Etherscan and React. It configures fetching ABIs from Etherscan and generating React hooks.
```typescript
import { defineConfig } from '@wagmi/cli'
import { etherscan, react } from '@wagmi/cli/plugins'
import { erc20Abi } from 'viem'
import { mainnet, sepolia } from 'wagmi/chains'
export default defineConfig({
out: 'src/generated.ts',
contracts: [
{
name: 'erc20',
abi: erc20Abi,
},
],
plugins: [
etherscan({
apiKey: process.env.ETHERSCAN_API_KEY!,
chainId: mainnet.id,
contracts: [
{
name: 'EnsRegistry',
address: {
[mainnet.id]: '0x314159265dd8dbb310642f98f50c066173c1259b',
[sepolia.id]: '0x112234455c3a32fd11230c42e7bccd4a84e02010',
},
},
],
}),
react(),
],
})
```
--------------------------------
### Create New Ponder Project using pnpm
Source: https://ponder.sh/docs/0.10/get-started
Initializes a new Ponder project with a chosen template. This command automates the setup of project structure, dependencies, and configuration files. It prompts the user for project name and template choice.
```shell
pnpm create ponder
```
--------------------------------
### Using Generated Wagmi CLI Hooks
Source: https://wagmi.sh/cli/getting-started
Demonstrates how to import and utilize generated React hooks from Wagmi CLI within a project. This example shows fetching the balance of an ERC-20 token.
```typescript
import { useReadErc20, useReadErc20BalanceOf } from './generated'
// Use the generated ERC-20 read hook
const { data } = useReadErc20({
address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
functionName: 'balanceOf',
args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],
})
// Use the generated ERC-
```
--------------------------------
### Start Ponder Development Server using pnpm
Source: https://ponder.sh/docs/0.10/get-started
Starts the Ponder local development server, which includes connecting to the database, launching the HTTP server, and initiating the data indexing process. It provides real-time logs for build status, database connections, table creation, server status, and indexing progress.
```shell
pnpm dev
```
--------------------------------
### Initialize Ponder Project using npm, pnpm, or yarn
Source: https://github.com/ponder-sh/ponder
This snippet shows how to initiate a new Ponder project using the create-ponder CLI. It guides users to create a project directory, install dependencies, and initialize a Git repository. The command is available for npm, pnpm, and yarn package managers.
```shell
npm init ponder@latest
# or
pnpm create ponder
# or
yarn create ponder
```
--------------------------------
### Predev Script for Generation (package.json)
Source: https://wagmi.sh/cli/getting-started
This configuration snippet shows how to set up a 'predev' script in a package.json file to automatically run a 'generate' command before starting the development server. This ensures that generated files are up-to-date before development begins, preventing potential issues caused by stale generated code.
```json
"scripts": {
"predev": "generate",
"dev": "next dev"
}
```
--------------------------------
### Start Ponder Development Server using npm, pnpm, or yarn
Source: https://github.com/ponder-sh/ponder
This code demonstrates how to start the Ponder development server, which provides features like hot reloading and logging of console statements and errors. It's executed after navigating into the project directory and is available for npm, pnpm, and yarn.
```shell
npm run dev
# or
pnpm dev
# or
yarn dev
```
--------------------------------
### Project Setup and Dependency Installation
Source: https://github.com/marktoda/v4-ponder
Instructions for cloning the repository and installing project dependencies using npm, yarn, or pnpm. Assumes Node.js and a package manager are installed.
```shell
git clone cd v4-ponder
npm install
# or yarn install
# or pnpm install
```
--------------------------------
### Basic Wagmi CLI Configuration (TypeScript)
Source: https://wagmi.sh/cli/getting-started
A minimal Wagmi CLI configuration file in TypeScript. It specifies the output file for generated code and initializes empty arrays for contracts and plugins.
```typescript
import { defineConfig } from '@wagmi/cli'
export default defineConfig({
out: 'src/generated.ts',
contracts: [],
plugins: [],
})
```
--------------------------------
### Interactive GraphQL Query Example
Source: https://graphql.org/learn
Provides an example of an interactive GraphQL query for learning purposes, suggesting adding fields to an object to observe updated results. This is part of an interactive guide.
```graphql
Operation {
hero {
name # add additional fields here!
}
}
```
--------------------------------
### Run Wagmi CLI Code Generation
Source: https://wagmi.sh/cli/getting-started
Executes the Wagmi CLI's code generation process based on the configuration file. This command is supported by pnpm, npm, yarn, and bun.
```bash
pnpm wagmi generate
```
```bash
npx wagmi generate
```
```bash
yarn wagmi generate
```
```bash
bun wagmi generate
```
--------------------------------
### Initialize Wagmi CLI Configuration
Source: https://wagmi.sh/cli/getting-started
Initializes a Wagmi CLI configuration file. It automatically creates `wagmi.config.ts` if TypeScript is detected, otherwise `wagmi.config.js`. This command is available for pnpm, npm, yarn, and bun.
```bash
pnpm wagmi init
```
```bash
npx wagmi init
```
```bash
yarn wagmi init
```
```bash
bun wagmi init
```
--------------------------------
### GraphQL API Setup
Source: https://ponder.sh/docs/query/graphql
This section details how to enable the GraphQL API by registering the `graphql` Hono middleware and provides an example of the `src/api/index.ts` file.
```APIDOC
## POST /graphql
### Description
Enables the GraphQL API for querying the Ponder database.
### Method
POST
### Endpoint
/graphql
### Parameters
#### Request Body
- **query** (String) - Required - The GraphQL query string.
- **variables** (Object) - Optional - Variables for the GraphQL query.
### Request Example
```json
{
"query": "{ persons { id name } }",
"variables": {}
}
```
### Response
#### Success Response (200)
- **data** (Object) - The result of the GraphQL query.
- **errors** (Array) - An array of errors, if any occurred.
#### Response Example
```json
{
"data": {
"persons": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
]
}
}
```
```
--------------------------------
### Start Ponder Development Server
Source: https://github.com/ponder-sh/ponder/tree/main/examples/with-foundry
Starts the Ponder development server using pnpm. Ponder is a framework for building reliable data services from blockchains. This command initiates the development environment for indexing and processing blockchain data. No specific inputs are required, and it outputs server status and logs.
```bash
pnpm ponder dev
```
--------------------------------
### Monorepo Ponder Start Command (npm)
Source: https://ponder.sh/docs/0.10/production/railway
For monorepo setups, this command navigates to the Ponder project root (e.g., 'packages/ponder') and then starts the Ponder application with the --schema option. It assumes an npm workspace.
```shell
cd packages/ponder && npm start
```
--------------------------------
### Ponder Configuration Example
Source: https://ponder.sh/docs/0.10/guides/foundry
This snippet shows a basic Ponder configuration, including importing contract ABI, address, and start block. It is a foundational part of setting up Ponder for indexing.
```typescript
import { createConfig } from "ponder";
import { http } from "viem";
const config = createConfig({
contracts: {
Counter: {
abi: counterABI,
address: "0x123",
startBlock: 1,
},
},
});
```
--------------------------------
### Running Anvil Local Node
Source: https://github.com/ponder-sh/ponder/tree/main/examples/with-foundry
This command starts a local Anvil node, a hardhat-compatible local Ethereum node. It's essential for local blockchain development and testing.
```bash
anvil --block-time 1
```
--------------------------------
### Start Ponder with Automated View Creation (CLI)
Source: https://ponder.sh/docs/production/self-hosting
Shows how to start a Ponder deployment using 'ponder start' with the '--views-schema' flag. This automatically runs the 'ponder db create-views' command upon deployment readiness, ensuring views always point to the latest tables.
```bash
pnpm start --schema=deployment-123 --views-schema=project-name
```
--------------------------------
### Monorepo Ponder Start Command (pnpm)
Source: https://ponder.sh/docs/0.10/production/railway
For monorepo setups, this command navigates to the Ponder project root (e.g., 'packages/ponder') and then starts the Ponder application with the --schema option. It assumes a pnpm workspace.
```shell
cd packages/ponder && pnpm start
```
--------------------------------
### Create HTTP Server in Node.js
Source: https://nodejs.org/en
This example demonstrates how to create a basic HTTP server using Node.js. It listens on port 3000 and responds with 'Hello World!'. Ensure Node.js is installed to run this code. The output is a running server that can be accessed via a web browser.
```javascript
import { createServer } from 'node:http';
const server = createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World!\n');
});
// starts a simple http server locally on port 3000
server.listen(3000, '127.0.0.1', () => {
console.log('Listening on 127.0.0.1:3000');
});
// run with `node server.mjs`
```
--------------------------------
### Basic React Query Setup
Source: https://tanstack.com/query/latest/docs/framework/react/guides/infinite-queries
Demonstrates the fundamental setup for using TanStack Query in a React application. It involves wrapping the application with QueryClientProvider and initializing a QueryClient instance. This setup is essential for managing server state across the application.
```jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import App from './App';
const queryClient = new QueryClient();
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
);
```
--------------------------------
### Install GraphiQL and Dependencies
Source: https://github.com/graphql/graphiql/tree/main/packages/graphiql
Installs the 'graphiql' package along with its peer dependencies 'react', 'react-dom', and 'graphql' using npm. This is the foundational step for using GraphiQL.
```bash
npm install graphiql react react-dom graphql
```
--------------------------------
### Windows specific global TypeScript path example
Source: https://stackoverflow.com/questions/39668731/what-typescript-version-is-visual-studio-code-using-how-to-update-it
An example of how to specify the TypeScript SDK path in VS Code settings on Windows, when TypeScript is installed globally via npm. It uses the full path obtained from `npm root -g`.
```json
"typescript.tsdk": "C:\\Users\\myname\\AppData\\Roaming\\npm\\node_modules\\typescript\\lib"
```
--------------------------------
### Starting Anvil Local Testnet
Source: https://book.getfoundry.sh/guides/scripting-with-solidity
This snippet represents the command to start the Anvil local blockchain development environment. Anvil provides default accounts and private keys for local testing.
```bash
anvil
```
--------------------------------
### `@ponder/client` Installation
Source: https://ponder.sh/docs/0.10/api-reference/ponder-client
Installs the `@ponder/client` package using pnpm, yarn, or npm.
```APIDOC
## Installation
### Method
`pnpm` `yarn` `npm`
### Endpoint
N/A
### Request Body
N/A
### Response
N/A
### Request Example
```bash
pnpm add @ponder/client
```
```
--------------------------------
### Install @ponder/client with pnpm
Source: https://ponder.sh/docs/0.10/api-reference/ponder-client
Installs the @ponder/client package using the pnpm package manager. This is the first step to using the Ponder SQL client in your project.
```bash
pnpm add @ponder/client
```
--------------------------------
### Log Hot Reload and Indexing Progress
Source: https://ponder.sh/docs/0.10/get-started
This snippet represents log entries from a development server, showing the status of hot reloading a TypeScript file and the progress of indexing events. It provides timing and completion percentages.
```log
12:27:26 PM INFO build Hot reload 'src/index.ts'
12:27:29 PM INFO app Indexed 4999 events with 54.2% complete and 471ms remaining
12:27:29 PM INFO app Indexed 4999 events with 75.5% complete and 276ms remaining
12:27:29 PM INFO app Indexed 4998 events with 99.4% complete and 6ms remaining
12:27:29 PM INFO app Indexed 108 events with 100% complete and 0ms remaining
12:27:29 PM INFO indexing Completed historical indexing
```
--------------------------------
### Extract ABI Function Names with ABIType
Source: https://abitype.dev/guide/getting-started
Imports and utilizes `ExtractAbiFunctionNames` from ABIType to extract all function names from a given ABI. It also shows how to import a predefined ABI like `erc20Abi` from `abitype/abis`.
```typescript
import { type ExtractAbiFunctionNames } from 'abitype'
import { erc20Abi } from 'abitype/abis'
type Result = ExtractAbiFunctionNames
// Result will be "symbol" | "name" | "allowance" | "balanceOf" | "decimals" | "totalSupply"
```
--------------------------------
### Example .env file for Ponder
Source: https://github.com/ponder-sh/ponder/tree/main/examples/feature-multichain
An example environment file for a Ponder project. It demonstrates how to set up environment variables, such as RPC URLs for different networks. This file helps in configuring the Ponder instance for local development or deployment.
```env
# Replace with your actual RPC endpoints
ETHEREUM_RPC_URL=https://rpc.ankr.com/eth
GOERLI_RPC_URL=https://rpc.ankr.com/eth/goerli
```
--------------------------------
### Minimal Ponder API Server Setup (TypeScript)
Source: https://ponder.sh/docs/query/api-endpoints
This snippet shows the basic setup for a Ponder API server using Hono. It exports a minimal Hono instance, which serves as the foundation for custom API endpoints. No external dependencies beyond Hono are required for this minimal setup.
```typescript
import { Hono } from "hono";
const app = new Hono();
export default app;
```
--------------------------------
### Narrow ABIs using `narrow` function in JavaScript
Source: https://abitype.dev/guide/getting-started
Shows how to use the `narrow` function from ABIType in JavaScript to achieve specific typing for ABIs, similar to `const` assertions in TypeScript. This is useful for environments where `const` assertions might not be preferred.
```javascript
import { narrow } from 'abitype'
const erc20Abi = narrow([
// ... ABI definition ...
])
```
--------------------------------
### Logfmt Example
Source: https://brandur.org/logfmt
An example of a log line formatted using logfmt, showcasing its key/value pair structure.
```logfmt
at=info method=GET path=/ host=mutelight.org fwd="124.133.52.161" dyno=web.2 connect=4ms service=8ms status=200 bytes=1653
```
--------------------------------
### Multi-chain Example Configuration
Source: https://github.com/ponder-sh/ponder/tree/main/examples/feature-multichain
Configuration file for a multi-chain example in Ponder. It defines the network settings and contract events to index. This file is typically used to set up Ponder for indexing data from multiple blockchains simultaneously.
```typescript
import { ponder } from "./ponder.js";
ponder.configure({
networks: {
ethereum: {
name: "mainnet",
chainId: 1,
transport: http("https://rpc.ankr.com/eth"),
},
goerli: {
name: "goerli",
chainId: 5,
transport: http("https://rpc.ankr.com/eth/goerli"),
},
},
contracts: {
// ... other contracts
},
});
```
--------------------------------
### Install @ponder/react and dependencies
Source: https://ponder.sh/docs/0.10/query/sql-client
Installs the @ponder/react package along with its peer dependencies, @ponder/client and @tanstack/react-query, for use in a React application.
```bash
pnpm add @ponder/react @ponder/client @tanstack/react-query
```
--------------------------------
### Gitignore 'out' Directory (Configuration)
Source: https://wagmi.sh/cli/getting-started
This configuration snippet illustrates how to prevent generated 'out' files from being committed to version control. By adding 'out' to the .gitignore file, developers ensure that only source files are tracked, promoting a cleaner repository. The 'out' directory is typically populated by build or generation scripts.
```git
out
```
--------------------------------
### Install @ponder/client (pnpm)
Source: https://ponder.sh/docs/query/sql-over-http
Command to install the @ponder/client package, which is necessary for interacting with Ponder's SQL over HTTP API from your client project.
```bash
pnpm add @ponder/client
```
--------------------------------
### Install @ponder/react and Dependencies (pnpm)
Source: https://ponder.sh/docs/query/sql-over-http
Command to install the @ponder/react package along with its peer dependencies, @ponder/client and @tanstack/react-query, required for using Ponder's React hooks.
```bash
pnpm add @ponder/react @ponder/client @tanstack/react-query
```
--------------------------------
### Install env-paths using npm
Source: https://github.com/sindresorhus/env-paths
This snippet shows how to install the env-paths package using npm. It's a prerequisite for using the package in your project.
```shell
$ npm install env-paths
```
--------------------------------
### Read ERC20 BalanceOf Hook (JavaScript)
Source: https://wagmi.sh/cli/getting-started
This snippet demonstrates how to use the `useReadErc20BalanceOf` hook to read the balance of a specific ERC20 token for a given address. It requires the Ethers.js library and assumes the necessary contract ABIs are available. The hook takes the token's address and the owner's address as arguments and returns the balance data.
```javascript
const { data } = useReadErc20BalanceOf({
address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],
})
```
--------------------------------
### Starting the Indexer Service
Source: https://github.com/marktoda/v4-ponder
Commands to start the Ponder indexer service in development mode using npm, yarn, or pnpm. This initiates the data indexing process.
```shell
npm run dev
# or yarn dev
# or pnpm dev
```
--------------------------------
### Project Initialization with Hono CLI (npm, yarn, pnpm, bun, deno)
Source: https://hono.dev/docs
These commands illustrate how to initialize a new Hono project using the official Hono CLI. The commands vary slightly depending on the package manager (npm, yarn, pnpm, bun, deno) being used. This is the recommended way to start a new Hono project, setting up the basic structure and configuration.
```shell
npm create hono@latest
```
```shell
yarn create hono
```
```shell
pnpm create hono@latest
```
```shell
bun create hono@latest
```
```shell
deno init --npm hono@latest
```
--------------------------------
### Get Transaction Count at Block Number (TypeScript)
Source: https://viem.sh/docs/actions/public/getTransactionCount
This example shows how to get the transaction count for an address at a specific block number using the `getTransactionCount` function. This is useful for historical analysis or state verification at a particular point in the blockchain.
```typescript
const transactionCount = await publicClient.getTransactionCount({
address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
blockNumber: 69420n
})
```
--------------------------------
### Deploy Smart Account with SimpleAccountFactory
Source: https://viem.sh/docs/contract/readContract
This snippet demonstrates how to deploy a smart account using the `SimpleAccountFactory`. It involves encoding the `createAccount` function data and then calling the `entryPoint` function on the smart account.
```typescript
factory: '0xE8Df82fA4E10e6A12a9Dab552bceA2acd26De9bb', // Function to execute on the factory to deploy the Smart Account.
factoryData: encodeFunctionData({
abi: parseAbi([
'function createAccount(address owner, uint256 salt)'
]),
functionName: 'createAccount',
args: [account, 0n],
}), // Function to call on the Smart Account.
abi: account.abi,
address: account.address,
functionName: 'entryPoint',
}
```
--------------------------------
### Register GET Route Handler with Hono
Source: https://ponder.sh/docs/0.10/query/api-endpoints
This example demonstrates how to register a simple GET route handler for '/hello' on a Hono instance. It returns a plain text response. This is a foundational step for creating interactive API endpoints within Ponder.
```typescript
import { Hono } from "hono";
const app = new Hono();
app.get("/hello", (c) => {
return c.text("Hello, world!");
});
export default app;
```
--------------------------------
### Initialize Foundry Project
Source: https://book.getfoundry.sh/guides/scripting-with-solidity
Initializes a new Foundry project in a specified directory. This command sets up the basic file structure and configuration for a new smart contract project.
```bash
forge init Counter
```
--------------------------------
### Execute Contract Call with Factory and Factory Data (JavaScript)
Source: https://viem.sh/docs/actions/public/call
This example shows how to deploy and interact with a contract using a factory pattern. It requires the factory address and the data to execute on the factory. This is common for contract creation via Create2 or smart account factories. Requires `publicClient`.
```javascript
const data = await publicClient.call({
account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',
factory: '0x0000000000ffe8b47b3e2130213b802212439497',
factoryData: '0xdeadbeef',
to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
})
```
--------------------------------
### Example of Setting TypeScript SDK Path (Windows)
Source: https://stackoverflow.com/questions/39668731/what-typescript-version-is-visual-studio-code-using-how-to-update-it
This example shows how to configure the 'typescript.tsdk' setting in Visual Studio Code for a user on Windows. It specifies a path pointing to a globally installed TypeScript version managed by npm. Note the use of double backslashes for proper escaping of the Windows file path.
```json
{
"typescript.tsdk": "C:\\Users\\username\\AppData\\Roaming\\npm\\node_modules\\typescript\\lib"
}
```
--------------------------------
### Ponder Environment Variables Example (.env.example)
Source: https://github.com/ponder-sh/ponder/tree/main/examples/reference-erc20
An example environment file for Ponder projects. It lists the necessary environment variables required to run Ponder, such as RPC URLs for different blockchain networks. This file serves as a template for developers to create their own `.env` file.
```dotenv
# .env.example
MAINNET_RPC_URL=https://mainnet.infura.io/v3/YOUR_INFURA_KEY
POLYGON_RPC_URL=https://polygon-rpc.com/
ARBITRUM_ONE_RPC_URL=https://arb1.arbitrum.io/rpc/
```
--------------------------------
### Ponder CLI Usage and Options
Source: https://ponder.sh/docs/0.10/api-reference/ponder/cli
This snippet shows the general usage of the `ponder` CLI and lists common options and commands. It provides a high-level overview of how to interact with the CLI, including options for specifying the project root, configuration file, logging levels, and debugging. Key commands like `dev`, `start`, `serve`, `db`, and `codegen` are introduced.
```bash
Usage: ponder [OPTIONS]
Options:
--root Path to the project root directory (default: working directory)
--config Path to the project config file (default: "ponder.config.ts")
-v, --debug Enable debug logs, e.g. realtime blocks, internal events
-vv, --trace Enable trace logs, e.g. db queries, indexing checkpoints
--log-level Minimum log level ("error", "warn", "info", "debug", or "trace", default: "info")
--log-format The log format ("pretty" or "json") (default: "pretty")
-V, --version Show the version number
-h, --help Show this help message
Commands:
dev [options] Start the development server with hot reloading
start [options] Start the production server
serve [options] Start the production HTTP server without the indexer
db Database management commands
codegen Generate the ponder-env.d.ts file, then exit
```
--------------------------------
### React Query Setup and Usage
Source: https://tanstack.com/query/latest/docs/framework/react/quick-start
Demonstrates how to set up and use React Query in a React application. It covers initializing the QueryClient and providing it to the application context. This is essential for enabling data fetching and state management with React Query.
```javascript
import { useQuery, useMutation, useQueryClient, QueryClient, QueryClientProvider, } from '@tanstack/react-query'
import { getTodos, postTodo } from '../my-api'
// Create a client
const queryClient = new QueryClient()
function App() {
return (
// Provide the client to your App
)
}
function Todos() {
// Access the client
const queryClient = useQueryClient()
// Queries
const query = useQuery({
queryKey: ['todos'],
queryFn: getTodos
})
// Mutations
const mutation = useMutation({
mutationFn: postTodo,
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries({ queryKey: ['todos'] })
},
})
return (
{query.data?.map((todo) => (
{todo.title}
))}
)
}
```
--------------------------------
### Get Account Balance at Specific Block Number (TypeScript)
Source: https://viem.sh/docs/actions/public/getBalance
This example shows how to query the balance of an Ethereum address at a specific block number using `publicClient.getBalance`. It takes the address and a `blockNumber` (as a bigint) as parameters.
```typescript
const balance = await publicClient.getBalance({
address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
blockNumber: 69420n
})
```
--------------------------------
### Check global TypeScript version with Yarn
Source: https://stackoverflow.com/questions/39668731/what-typescript-version-is-visual-studio-code-using-how-to-update-it
This command allows you to check the globally installed version of the TypeScript compiler using Yarn. It's a quick way to verify your setup before making changes.
```bash
yarn tsc --version
```
--------------------------------
### Create Basic Public Client - viem
Source: https://viem.sh/docs/clients/public
Shows how to initialize a basic Public Client using 'createPublicClient'. It requires specifying a 'chain' (e.g., 'mainnet') and a 'transport' (e.g., 'http'). This client can then be used to call public blockchain actions.
```typescript
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const publicClient = createPublicClient({
chain: mainnet,
transport: http()
})
```
--------------------------------
### Drizzle Kit Configuration for Multi-Project Schemas
Source: https://orm.drizzle.team/docs/goodies
Example Drizzle Kit configuration for a multi-project setup, specifying schema paths, output directory, dialect, database credentials, and filtering tables for 'project1'.
```typescript
import { defineConfig } from "drizzle-kit";
export default defineConfig({
schema: "./src/schema/*",
out: "./drizzle",
dialect: "mysql",
dbCredentials: {
url: process.env.DATABASE_URL,
},
tablesFilter: ["project1_*"]
});
```
--------------------------------
### Specify Block Interval Name in ponder.config.ts
Source: https://ponder.sh/docs/0.10/config/block-intervals
This example demonstrates defining a block interval named 'ChainlinkOracleUpdate' within the `ponder.config.ts` file. It specifies the network, interval, and a starting block number for the indexing task.
```typescript
import { createConfig } from "ponder";
export default createConfig({
networks: {
/* ... */
},
blocks: {
ChainlinkOracleUpdate: {
network: "mainnet",
interval: 10,
startBlock: 19783636,
},
},
});
```
--------------------------------
### Assert ABIs to Constants with `as const` in TypeScript
Source: https://abitype.dev/guide/getting-started
Demonstrates how to use `const` assertions in TypeScript to ensure ABIs are typed with their most specific types, preventing type widening. This is crucial for ABIs with deeply nested arrays and objects.
```typescript
const erc20Abi = [
// ... ABI definition ...
] as const
```
--------------------------------
### Get global npm root path
Source: https://stackoverflow.com/questions/39668731/what-typescript-version-is-visual-studio-code-using-how-to-update-it
This command helps you find the root directory of your globally installed npm packages. This path is often needed when manually configuring the `typescript.tsdk` setting in VS Code.
```bash
npm root -g
```
--------------------------------
### Handle Event Data and Database Updates
Source: https://ponder.sh/docs/0.10/get-started
This snippet demonstrates how to process event data, including address and balance, and handle potential conflicts during database updates. It utilizes an 'onConflictDoUpdate' pattern for efficient data management.
```typescript
{
address: event.args.from,
balance: 0n,
isOwner: event.args.from === OWNER_ADDRESS,
})
.onConflictDoUpdate((row) => ({ // ...
```
--------------------------------
### Configure Public Client Transport - viem
Source: https://viem.sh/docs/clients/public
Provides an example of configuring the 'transport' parameter when creating a Public Client. Here, it demonstrates using the 'http' transport.
```typescript
const publicClient = createPublicClient({
chain: mainnet,
transport: http(),
})
```
--------------------------------
### Solidity Script for Counter Contract Deployment
Source: https://book.getfoundry.sh/guides/scripting-with-solidity
A basic Solidity script using Foundry's Script contract to deploy a Counter contract. It demonstrates the use of `vm.startBroadcast()` and `vm.stopBroadcast()` to manage transaction signing and broadcasting. This script is intended for local or testnet deployments.
```solidity
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import {Script, console} from "forge-std/Script.sol";
import {Counter} from "../src/Counter.sol";
contract CounterScript is Script {
Counter public counter;
function setUp() public {}
function run() public {
vm.startBroadcast();
counter = new Counter();
vm.stopBroadcast();
}
}
```
--------------------------------
### Ponder Configuration for Block Intervals (TypeScript)
Source: https://ponder.sh/docs/config/block-intervals
This snippet demonstrates how to configure block intervals in `ponder.config.ts`. It defines a block interval named 'ChainlinkOracleUpdate' that triggers every 10 blocks, starting from block 1000, on the 'mainnet' chain.
```typescript
import { createConfig } from "ponder";
export default createConfig({
chains: {
mainnet: {
id: 1,
rpc: process.env.PONDER_RPC_URL_1
}
},
blocks: {
ChainlinkOracleUpdate: {
chain: "mainnet",
interval: 10, // Every 10 blocks
startBlock: 1000
}
}
});
```
--------------------------------
### React Query Quick Start: Queries, Mutations, and Invalidation
Source: https://tanstack.com/query/latest/docs/framework/react/quick-start
This snippet demonstrates the three core concepts of React Query: queries for fetching data, mutations for updating data, and query invalidation for cache management. It shows how to set up the QueryClient, use the useQuery hook for data fetching, the useMutation hook for data updates, and invalidate queries upon successful mutation.
```tsx
import { useQuery, useMutation, useQueryClient, QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { getTodos, postTodo } from '../my-api'
// Create a client
const queryClient = new QueryClient()
function App() {
return (
)
}
function Todos() {
// Access the client
const queryClient = useQueryClient()
// Queries
const query = useQuery({
queryKey: ['todos'],
queryFn: getTodos,
})
// Mutations
const mutation = useMutation({
mutationFn: postTodo,
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries({ queryKey: ['todos'] })
},
})
return (
{query.data?.map((todo) => (
{todo.title}
))}
)
}
```
--------------------------------
### Configure Block Settings in Ponder
Source: https://ponder.sh/docs/api-reference/ponder/config
Shows how to configure specific block settings using the `BlockConfig` type. This example configures the `ChainlinkPriceOracle` block with its associated chain, starting block, and indexing interval, allowing for targeted data synchronization.
```typescript
import { createConfig, type BlockConfig } from "ponder";
const ChainlinkPriceOracle = {
chain: "mainnet",
startBlock: 19_750_000,
interval: 5,
} as const satisfies BlockConfig;
export default createConfig({
blocks: {
ChainlinkPriceOracle,
},
// ...
});
```
--------------------------------
### QueryClient Configuration
Source: https://tanstack.com/query/latest/docs/framework/react/reference/useQuery
Documentation on how to configure and use the QueryClient instance.
```APIDOC
## QueryClientProvider
**Description**: A React component that provides the `QueryClient` instance to your application.
**Usage**: Wrap your application or a part of it with `QueryClientProvider` to make the `QueryClient` available to all descendant components.
### Parameters
* **client** (QueryClient) - Required - The `QueryClient` instance to provide.
* **children** - Required - The child elements to be rendered.
### Request Example
```javascript
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
function App() {
return (
{/* Your application components */}
);
}
```
```
--------------------------------
### Define Account Name in Ponder Configuration (TypeScript)
Source: https://ponder.sh/docs/config/accounts
This example demonstrates how to uniquely name an account ('BeaverBuild') within the Ponder configuration. Account names must be unique across all defined accounts, contracts, and block intervals in the project.
```typescript
import { createConfig } from "ponder";
export default createConfig({
chains: {
/* ... */
},
accounts: {
BeaverBuild: {
chain: "mainnet",
address: "0x95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5",
startBlock: 12439123,
},
},
});
```
--------------------------------
### Ponder `start` Command for Production
Source: https://ponder.sh/docs/0.10/api-reference/ponder/cli
Initiates the Ponder application in production mode. Unlike development mode, project files are built only once on startup, and file changes are ignored. The terminal UI is also disabled by default. Options allow configuration of the schema, port, and hostname.
```bash
Usage: ponder start [options]
Start the production server
Options:
--schema Database schema
-p, --port Port for the web server (default: 42069)
-H, --hostname Hostname for the web server (default: "0.0.0.0" or "::")
-h, --help display help for command
```
--------------------------------
### Configure Ponder Account Indexing (TypeScript)
Source: https://ponder.sh/docs/config/accounts
This configuration sets up Ponder to index transactions and native transfers for a specified account ('BeaverBuild') on the 'mainnet' chain, starting from block 20,000,000. It requires an RPC URL to be set in the environment variables.
```typescript
import { createConfig } from "ponder";
export default createConfig({
chains: {
mainnet: {
id: 1,
rpc: process.env.PONDER_RPC_URL_1,
},
},
accounts: {
BeaverBuild: {
chain: "mainnet",
address: "0x95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5",
startBlock: 20000000,
},
},
});
```
--------------------------------
### Ponder Indexing Function for Block Intervals (TypeScript)
Source: https://ponder.sh/docs/config/block-intervals
This example shows an indexing function registered for the 'ChainlinkOracleUpdate:block' event. It fetches the latest price from a Chainlink oracle contract at specified block heights and inserts the data into a 'priceTimeline' table.
```typescript
import { ponder } from "ponder:registry";
import { priceTimeline } from "ponder:schema";
import { ChainlinkOracleAbi } from "../abis/ChainlinkOracle.ts";
ponder.on("ChainlinkOracleUpdate:block", async ({ event, context }) => {
// Fetch the price at the current block height (1000, 1010, 1020, etc.)
const latestPrice = await context.client.readContract({
abi: ChainlinkOracleAbi,
address: "0xD10aBbC76679a20055E167BB80A24ac851b37056",
functionName: "latestAnswer"
});
// Insert a row into the price timeline table
await context.db.insert(priceTimeline).values({
id: event.id,
timestamp: event.block.timestamp,
price: latestPrice
});
});
```
--------------------------------
### Execute Raw SQL Query in SQLite with Drizzle ORM
Source: https://orm.drizzle.team/docs/goodies
Provides examples of executing raw SQL queries in SQLite using Drizzle ORM. It showcases different methods like `all`, `get`, `values`, and `run` for retrieving or executing data.
```typescript
import { sql } from 'drizzle-orm';
const statement = sql`select * from ${users} where ${users.id} = ${userId}`;
// Example usages:
const res: unknown[][] = db.all(statement); // Returns all rows as arrays
const res: unknown = db.get(statement); // Returns the first row
const res: unknown[][] = db.values(statement); // Returns only values from all rows
const res: Database.RunResult = db.run(statement); // Executes the statement, returns info about changes
```
--------------------------------
### Deploy Contracts with Forge
Source: https://github.com/ponder-sh/ponder/tree/main/examples/with-foundry
Deploys smart contracts and generates logs using Forge. Requires a local Ethereum node and a private key. Outputs contract deployment information and logs.
```bash
forge script script/Deploy.s.sol --broadcast --fork-url http://localhost:8545 --private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80
```
--------------------------------
### Solidity Contract Example
Source: https://docs.soliditylang.org/en/v0.8.17/abi-spec.html
A sample Solidity contract 'Foo' demonstrating functions with different parameter and return types. This contract is used to illustrate function encoding.
```solidity
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 <0.9.0;
contract Foo {
function bar(bytes3[2] memory) public pure {}
function baz(uint32 x, bool y) public pure returns (bool r) {
r = x > 32 || y;
}
function sam(bytes memory, bool, uint[] memory) public pure {}
}
```
--------------------------------
### Get Environment Paths with envPaths (JavaScript)
Source: https://github.com/sindresorhus/env-paths
Demonstrates how to use the envPaths function to retrieve standardized directory paths for an application. It shows examples of accessing data and config paths. Note that this package only generates path strings and does not create directories; you might need a package like 'make-dir' for that.
```javascript
import envPaths from 'env-paths';
const paths = envPaths('MyApp');
console.log(paths.data);
//=> '/home/sindresorhus/.local/share/MyApp-nodejs' (example Linux path)
console.log(paths.config);
//=> '/home/sindresorhus/.config/MyApp-nodejs' (example Linux path)
```
--------------------------------
### Ponder Configuration Files
Source: https://github.com/ponder-sh/ponder/tree/main/examples/reference-erc721
This snippet includes configuration files for the Ponder project, such as .env.example, .eslintrc.json, .gitignore, package.json, tsconfig.json, and ponder.config.ts. These files define project settings, dependencies, and build configurations.
```dotenv
# .env.example
# Example environment variables for Ponder
DATABASE_URL="postgres://user:password@host:port/database"
```
```json
# .eslintrc.json
{
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module"
},
"env": {
"browser": true,
"es2017": true,
"node": true
}
}
```
```ignore
# .gitignore
node_modules/
dist/
.env
*.log
```
```json
# package.json
{
"name": "ponder",
"version": "0.1.0",
"description": "A framework for building data services.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"react": "^18.2.0"
}
}
```
```json
# tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"src/**/*.ts",
"test/**/*.ts"
],
"exclude": [
"node_modules"
]
}
```
```typescript
// ponder.config.ts
import { createConfig } from '@ponder/core';
export const config = createConfig({
networks: [
{
name: 'mainnet',
chainId: 1,
transport: process.env.MAINNET_RPC_URL
}
],
contracts: [
// Add contract definitions here
]
});
```
--------------------------------
### Get ENS Name with Strict Error Propagation (TypeScript)
Source: https://viem.sh/docs/ens/actions/getEnsName
This example explains how to enable strict error propagation for ENS Universal Resolver Contract errors by setting the `strict` parameter to `true`. When enabled, any errors encountered during the resolution process will be strictly propagated, aiding in debugging.
```typescript
const ensName = await publicClient.getEnsName({
address: '0xd2135CfB216b74109775236E36d4b433F1DF507B',
strict: true,
})
```
--------------------------------
### Public Client Creation and Usage
Source: https://viem.sh/docs/clients/public
Demonstrates how to import, create, and use a viem Public Client with HTTP transport and a specified chain.
```APIDOC
## Public Client
A Public Client is an interface to "public" JSON-RPC API methods such as retrieving block numbers, transactions, reading from smart contracts, etc through Public Actions.
### Import
```typescript
import { createPublicClient } from 'viem'
```
### Usage
Initialize a Client with your desired Chain (e.g. `mainnet`) and Transport (e.g. `http`).
```typescript
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const publicClient = createPublicClient({
chain: mainnet,
transport: http()
})
// Then you can consume Public Actions:
const blockNumber = await publicClient.getBlockNumber()
```
### Parameters
#### transport
* **Type:** `Transport`
The Transport of the Public Client.
```typescript
const publicClient = createPublicClient({
chain: mainnet,
transport: http()
})
```
#### chain (optional)
* **Type:** `Chain`
The Chain of the Public Client.
```typescript
const publicClient = createPublicClient({
chain: mainnet,
transport: http()
})
```
```
--------------------------------
### Simulate Mint Function Call in TypeScript
Source: https://viem.sh/docs/contract/simulateContract
Demonstrates a basic simulation of a `mint` function call on a contract using `simulateContract`. This example shows the essential parameters: address, ABI, function name, and account.
```typescript
const { result } = await publicClient.simulateContract({
address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
abi: wagmiAbi,
functionName: 'mint',
account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266'
})
```
--------------------------------
### Get ENS Name with Block Tag (TypeScript)
Source: https://viem.sh/docs/ens/actions/getEnsName
This example demonstrates fetching an ENS name using a block tag, such as 'latest', 'safe', or 'finalized'. Using `blockTag` allows you to specify the state of the blockchain for the ENS resolution, ensuring consistency or targeting specific chain states.
```typescript
const ensName = await publicClient.getEnsName({
address: '0xd2135CfB216b74109775236E36d4b433F1DF507B',
blockTag: 'safe',
})
```