From 5c53056ba501f9a7587118465ec4cc90387addc2 Mon Sep 17 00:00:00 2001 From: pravijndeca Date: Fri, 2 Oct 2026 09:09:37 -0700 Subject: [PATCH 1/3] Generate AI documentation indexes and Markdown pages --- README.md | 13 + app/[[...mdxPath]]/page.tsx | 24 +- app/layout.tsx | 2 +- next.config.ts | 13 + package.json | 6 +- public/.ai-docs-manifest.json | 34 + public/building-on-shape/ai.md | 119 + public/building-on-shape/alchemy-api.md | 10 + public/building-on-shape/builder-kit.md | 100 + .../differences-ethereum-shape.md | 36 + .../onchain-compatible/assembly.md | 335 +++ .../onchain-compatible/index.md | 9 + .../onchain-compatible/otom.md | 238 ++ .../superchain-incentives.md | 13 + public/building-on-shape/transaction-fees.md | 94 + public/gasback.md | 24 + public/index.md | 36 + public/llms-full.txt | 2613 +++++++++++++++++ public/llms.txt | 96 +- public/quick-start/connect-to-shape.md | 76 + public/quick-start/deploy-a-contract.md | 66 + public/quick-start/index.md | 16 + .../technical-details/contract-addresses.md | 111 + .../technical-details/network-information.md | 22 + public/technical-details/run-a-node.md | 354 +++ public/the-stack.md | 52 + public/tools/account-abstraction.md | 25 + public/tools/bridges.md | 17 + public/tools/data-indexers.md | 35 + public/tools/explorers.md | 18 + public/tools/faucets.md | 14 + public/tools/node-providers.md | 14 + public/tools/oracles/gelato-vrf.md | 100 + public/tools/safes-asset-security.md | 10 + public/tools/sybil-resistance.md | 13 + public/tutorials/mint-nft-collection.md | 196 ++ .../registering-contract-gasback/dashboard.md | 65 + .../registering-contract-gasback/index.md | 7 + .../programmatically.md | 168 ++ public/wallet-setup.md | 25 + scripts/generate-ai-docs.mjs | 295 ++ scripts/generate-ai-docs.test.mjs | 69 + 42 files changed, 5525 insertions(+), 58 deletions(-) create mode 100644 public/.ai-docs-manifest.json create mode 100644 public/building-on-shape/ai.md create mode 100644 public/building-on-shape/alchemy-api.md create mode 100644 public/building-on-shape/builder-kit.md create mode 100644 public/building-on-shape/differences-ethereum-shape.md create mode 100644 public/building-on-shape/onchain-compatible/assembly.md create mode 100644 public/building-on-shape/onchain-compatible/index.md create mode 100644 public/building-on-shape/onchain-compatible/otom.md create mode 100644 public/building-on-shape/superchain-incentives.md create mode 100644 public/building-on-shape/transaction-fees.md create mode 100644 public/gasback.md create mode 100644 public/index.md create mode 100644 public/llms-full.txt create mode 100644 public/quick-start/connect-to-shape.md create mode 100644 public/quick-start/deploy-a-contract.md create mode 100644 public/quick-start/index.md create mode 100644 public/technical-details/contract-addresses.md create mode 100644 public/technical-details/network-information.md create mode 100644 public/technical-details/run-a-node.md create mode 100644 public/the-stack.md create mode 100644 public/tools/account-abstraction.md create mode 100644 public/tools/bridges.md create mode 100644 public/tools/data-indexers.md create mode 100644 public/tools/explorers.md create mode 100644 public/tools/faucets.md create mode 100644 public/tools/node-providers.md create mode 100644 public/tools/oracles/gelato-vrf.md create mode 100644 public/tools/safes-asset-security.md create mode 100644 public/tools/sybil-resistance.md create mode 100644 public/tutorials/mint-nft-collection.md create mode 100644 public/tutorials/registering-contract-gasback/dashboard.md create mode 100644 public/tutorials/registering-contract-gasback/index.md create mode 100644 public/tutorials/registering-contract-gasback/programmatically.md create mode 100644 public/wallet-setup.md create mode 100644 scripts/generate-ai-docs.mjs create mode 100644 scripts/generate-ai-docs.test.mjs diff --git a/README.md b/README.md index dd7c466..65fad71 100644 --- a/README.md +++ b/README.md @@ -40,3 +40,16 @@ If you have feedback, please open an issue or reach out to [@williamhzo](https:/ ## License All content is © Shape Factory. + +## Documentation for AI tools + +The production build generates `/llms.txt`, `/llms-full.txt`, and Markdown versions of all documentation pages from `content/` and the shared cards and callouts. Each HTML page links to its Markdown alternative. `/llms.txt` groups entry points by task, while `/llms-full.txt` contains the technical documentation corpus. + +```bash +bun run generate:ai-docs +bun run test:ai-docs +``` + +Edit the MDX source or shared components, then regenerate the assets. Do not edit generated Markdown directly. The converter handles the current static MDX patterns and stops on unknown components, unclosed code fences, or unmapped documentation links. Add conversion support and a test when introducing a new MDX component. Fenced code blocks are preserved verbatim. + +Generated files under `public/` are committed so previews and local development can read them before a production build. Regenerate them with source changes. `.ai-docs-manifest.json` records the generated page paths so deleted pages are removed on regeneration and HTML alternatives use the same route map. diff --git a/app/[[...mdxPath]]/page.tsx b/app/[[...mdxPath]]/page.tsx index 0df8644..28119ea 100644 --- a/app/[[...mdxPath]]/page.tsx +++ b/app/[[...mdxPath]]/page.tsx @@ -1,3 +1,4 @@ +import markdownPages from '../../public/.ai-docs-manifest.json'; import { generateStaticParamsFor, importPage } from 'nextra/pages'; import { useMDXComponents as getMDXComponents } from '../../mdx-components'; @@ -6,7 +7,28 @@ export const generateStaticParams = generateStaticParamsFor('mdxPath'); export async function generateMetadata(props) { const params = await props.params; const { metadata } = await importPage(params.mdxPath); - return metadata; + const segments = params.mdxPath || []; + const route = '/' + segments.join('/'); + const indexes = new Set( + markdownPages + .filter((file) => file.endsWith('/index.md') || file === 'index.md') + .map((file) => '/' + file.replace(/(^|\/)index\.md$/, '').replace(/\/$/, '')) + ); + const markdown = indexes.has(route) + ? route === '/' + ? '/index.md' + : route + '/index.md' + : route + '.md'; + return { + ...metadata, + alternates: { + ...metadata.alternates, + types: { + ...metadata.alternates?.types, + 'text/markdown': 'https://docs.shape.network' + markdown, + }, + }, + }; } const Wrapper = getMDXComponents({}).wrapper; diff --git a/app/layout.tsx b/app/layout.tsx index 77903c8..4fd3507 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -57,7 +57,7 @@ export default async function RootLayout({ children }) { light: '#fff', }} > - {/* Your additional tags should be passed as `children` of `` element */} + diff --git a/next.config.ts b/next.config.ts index aa2f155..c2d57af 100644 --- a/next.config.ts +++ b/next.config.ts @@ -4,6 +4,19 @@ import type { NextConfig } from 'next'; const withNextra = nextra({}); export default withNextra({ + headers: async () => [ + ...['/llms.txt', '/llms-full.txt'].map((source) => ({ + source, + headers: [{ key: 'Content-Type', value: 'text/plain; charset=utf-8' }], + })), + { + source: '/:path*.md', + headers: [ + { key: 'Content-Type', value: 'text/markdown; charset=utf-8' }, + { key: 'Link', value: '; rel="describedby"' }, + ], + }, + ], redirects: () => [ { source: '/building-on-shape/gasback', diff --git a/package.json b/package.json index 5b86e59..3ced691 100644 --- a/package.json +++ b/package.json @@ -1,9 +1,11 @@ { "scripts": { "dev": "next dev", - "build": "next build", + "build": "node scripts/generate-ai-docs.mjs && next build", "start": "next start", - "postbuild": "pagefind --site .next/server/app --output-path public/_pagefind" + "postbuild": "pagefind --site .next/server/app --output-path public/_pagefind", + "generate:ai-docs": "node scripts/generate-ai-docs.mjs", + "test:ai-docs": "SHAPE_DOCS_TEST_ROOT=. node --test scripts/generate-ai-docs.test.mjs" }, "dependencies": { "@tailwindcss/postcss": "^4.1.18", diff --git a/public/.ai-docs-manifest.json b/public/.ai-docs-manifest.json new file mode 100644 index 0000000..54c46e2 --- /dev/null +++ b/public/.ai-docs-manifest.json @@ -0,0 +1,34 @@ +[ + "building-on-shape/ai.md", + "building-on-shape/alchemy-api.md", + "building-on-shape/builder-kit.md", + "building-on-shape/differences-ethereum-shape.md", + "building-on-shape/onchain-compatible/assembly.md", + "building-on-shape/onchain-compatible/index.md", + "building-on-shape/onchain-compatible/otom.md", + "building-on-shape/superchain-incentives.md", + "building-on-shape/transaction-fees.md", + "gasback.md", + "index.md", + "quick-start/connect-to-shape.md", + "quick-start/deploy-a-contract.md", + "quick-start/index.md", + "technical-details/contract-addresses.md", + "technical-details/network-information.md", + "technical-details/run-a-node.md", + "the-stack.md", + "tools/account-abstraction.md", + "tools/bridges.md", + "tools/data-indexers.md", + "tools/explorers.md", + "tools/faucets.md", + "tools/node-providers.md", + "tools/oracles/gelato-vrf.md", + "tools/safes-asset-security.md", + "tools/sybil-resistance.md", + "tutorials/mint-nft-collection.md", + "tutorials/registering-contract-gasback/dashboard.md", + "tutorials/registering-contract-gasback/index.md", + "tutorials/registering-contract-gasback/programmatically.md", + "wallet-setup.md" +] diff --git a/public/building-on-shape/ai.md b/public/building-on-shape/ai.md new file mode 100644 index 0000000..1a3f566 --- /dev/null +++ b/public/building-on-shape/ai.md @@ -0,0 +1,119 @@ +# AI Agents on Shape + +This guide gets you started with the Model Context Protocol (MCP) and our Shape MCP server, tools to make your AI agents smarter onchain. We'll cover the basics, show how to plug in Vercel AI, and spark some NFT agent ideas. + +## What is MCP? + +MCP (Model Context Protocol) is a standard for letting AI models like ChatGPT, Grok, or Claude safely access and interact with external data. Think blockchains, APIs, or tools. It's like giving your agent a direct communication channel to Shape, with features for tool calls, resources, and permissions. MCP keeps things structured and extensible, while keeping granular control over access or authorization for example. + +For a deep dive, check the [official MCP intro](https://modelcontextprotocol.io/introduction). In short: MCP turns your AI into an Shape-connoisseur, chaining queries like "fetch Shape NFTs" to "analyze collections trends" without leaving the chat. + +## Shape MCP Server: Your On-Chain Data Bridge + +We've built a dedicated MCP server for Shape, wrapping key data like Gasback distributions, NFT analytics, and Stack medals. It's open-source, forkable, and ready for your agents. Built with [xmcp](https://xmcp.dev/), it's TypeScript-first so no need to learn Python, and it deploys in minutes. + +- **Repository**: [github.com/shape-network/mcp-server](https://github.com/shape-network/mcp-server) +- **Why Use It?** Agents can query Shape without raw RPC calls. E.g., simulate Gasback rewards or track Stack achievements. It's modular, so you can extend it for any project. + +### Quick Setup + +Fork the repo and deploy your own instance, keeping things non-hosted and under your control. + +1. Fork and clone: `git clone https://github.com/shape-network/mcp-server` +2. Install: `yarn install` +3. Env vars in `.env`: `ALCHEMY_API_KEY=your-key`, `CHAIN_ID=360` (mainnet), optional `REDIS_URL` for caching. +4. Run locally: `yarn dev` (at http://localhost:3002/mcp) +5. Deploy to Vercel: Import the fork, set env vars in the UI, and hit deploy. + +For full tools and examples, see the [README](https://github.com/shape-network/mcp-server/blob/main/README.md). + +## Building AI Agents with Vercel AI SDK + +[Vercel AI SDK](https://ai-sdk.dev/docs/introduction) makes agent development a breeze. It's TypeScript-first, works with models like ChatGPT, Grok, or Claude, and handles streaming, tool calls, and chaining. Pair it with our MCP server for Shape-specific capabilities. + +### First Steps + +1. **Setup a Next.js App**: `npx create-next-app my-shape-agent`. (Pro tip: If you want a head start, run `bun create shape-app my-shape-agent` to scaffold a full Shape project with wallet connect, RPC setup, smart contracts, and UI components. See the [Builder Kit](https://docs.shape.network/building-on-shape/builder-kit.md) docs for details.) +2. **Install SDK**: `npm i ai @ai-sdk/openai @modelcontextprotocol/sdk viem wagmi` (for onchain integration) — [more info](https://ai-sdk.dev/docs/introduction). +3. **Connect MCP**: In an API route (e.g., /api/agent.ts): + + ```ts + import { openai } from '@ai-sdk/openai'; + import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; + import { experimental_createMCPClient, streamText } from 'ai'; + + export const maxDuration = 30; + + export async function POST(req: Request) { + const { messages } = await req.json(); + + // Connect to your deployed MCP server + const url = new URL('https://shape-mcp-server.vercel.app/mcp'); // or http://localhost:3002/mcp for local + const mcpClient = await experimental_createMCPClient({ + transport: new StreamableHTTPClientTransport(url), + }); + + // Get all available tools exposed + const tools = await mcpClient.tools(); + + const result = await streamText({ + model: openai('gpt-4o'), + tools, + messages, + maxSteps: 10, // Allow up to 10 sequential tool calls + system: 'You are a helpful assistant that [...]', // add your custom system prompt + onFinish: async () => { + await mcpClient.close(); + }, + }); + + return result.toDataStreamResponse(); + } + ``` + +4. **Add UI**: Use `useChat` hook in a page: + + ```ts + import { useChat } from 'ai/react'; + + export default function AgentChat() { + const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({ + api: '/api/agent', + maxSteps: 10, // Enable multi-step tool usage + }); + + return ( +
+
+ {messages.map(m => ( +
+ {m.role}: {m.content} +
+ ))} + {isLoading &&
Thinking...
} +
+
+ + +
+
+ ); + } + ``` + +5. **Deploy**: Push to GitHub, import to Vercel, set env vars, and go live. + +For full docs, see [Vercel AI SDK](https://vercel.com/docs/ai-sdk). + +## AI Agent Ideas for NFTs on Shape + +Shape's low fees and Gasback make it ideal for NFT agents. Here are fun starters—build these for the upcoming hackathon! + +- **NFT Curator Bot**: Queries `getCollectionAnalytics` to spot trending collections, then uses `getShapeNft` to suggest buys. Agent prompt: "Curate 5 underrated NFTs under 0.1 ETH—why buy?" +- **Gasback Optimizer**: Simulates rewards with `simulateGasbackRewards` for creators. Chains with `getTopShapeCreators` for comparisons. Prompt: "Optimize my contract for max Gasback—tx volume tips?" +- **Stack Achievement Coach**: Tracks progress via `getStackAchievements`, suggests actions (e.g., "Mint 3 more for gold medal"). Prompt: "What's my Stack level? Steps to next tier?" +- **Collection Analyzer**: Combines `getCollectionAnalytics` and `getChainStatus` to time mints. Prompt: "Is now good to mint on collection X? Gas low?" + +These leverage MCP for on-chain data, Vercel AI for reasoning—start simple, add wallet integration (wagmi) for actions. + +Questions? Hit up [@williamhzo](https://x.com/williamhzo) or [Shape Discord](https://discord.com/invite/shape-l2). Let's build!! diff --git a/public/building-on-shape/alchemy-api.md b/public/building-on-shape/alchemy-api.md new file mode 100644 index 0000000..e90f7ba --- /dev/null +++ b/public/building-on-shape/alchemy-api.md @@ -0,0 +1,10 @@ +# Alchemy API + +Find out what Alchemy tools are available to use on Shape. + +Checkout [Alchemy's Quickstart guide](https://docs.alchemy.com/reference/shape-api-quickstart) for Shape API. The [full suite](https://www.alchemy.com/) of Alchemy tools are available for builders on Shape. + +Visit your [Alchemy dashboard](https://dashboard.alchemy.com/) and start building now! + +> Visit your [Alchemy dashboard](https://www.alchemy.com/dashboard) and start building +> now! diff --git a/public/building-on-shape/builder-kit.md b/public/building-on-shape/builder-kit.md new file mode 100644 index 0000000..e22866c --- /dev/null +++ b/public/building-on-shape/builder-kit.md @@ -0,0 +1,100 @@ +# Shape Builder Kit for Developers + +The Shape Builder Kit is your go-to starter for crafting dApps on the Shape ecosystem. It's a monorepo with a Next.js frontend (wagmi, viem) and a Hardhat smart contract package, all pre-wired with sensible defaults. + +- **Batteries Included**: Wallet connection, Shape RPC integration, and NFT fetching out of the box. No reinventing the wheel. +- **AI-Ready**: Pairs seamlessly with the [Shape MCP server](https://docs.shape.network/building-on-shape/ai.md) and Vercel AI SDK for agentic apps. +- **Fast Track to Deploy**: Built for Vercel, so you can deploy to prod in minutes and focus on getting your first users! + +It's completely open and composable: use it to kickstart, then tweak to your style & needs. Check it out: [github.com/shape-network/builder-kit](https://github.com/shape-network/builder-kit). + +## Quickstart with `create-shape-app` + +The fastest way to get started is [`create-shape-app`](https://github.com/shape-network/create-shape-app), a CLI that scaffolds a new project from the latest Builder Kit release. One command and you're in: + +```bash +npx create-shape-app my-app +# or +bun create shape-app my-app +``` + +Also works with pnpm and yarn: + +```bash +pnpm dlx create-shape-app my-app +yarn create shape-app my-app +``` + +The CLI will download the latest Builder Kit release, install dependencies, and initialize a git repository. + +### CLI Options + +| Option | Description | +| --- | --- | +| `-y, --yes` | Skip interactive confirmation prompts | +| `--pm ` | Select package manager (auto-detected if omitted) | +| `--skip-install` | Skip dependency installation | +| `--skip-git` | Skip git init and initial commit | +| `--template-ref ` | Pin a specific Builder Kit release tag (e.g. `v1.0.0`) | + +## Project Structure + +The scaffolded project is a monorepo with two packages: + +``` +my-app/ +├── apps/web/ # Next.js + wagmi frontend +└── packages/contract/ # Hardhat smart contracts +``` + +## Configuration + +Copy `.env.example` to `.env` and fill in your values: + +```env +NEXT_PUBLIC_ALCHEMY_KEY=your-alchemy-key +NEXT_PUBLIC_CHAIN_ID=11011 # 11011 for Shape Sepolia, 360 for Shape Mainnet +NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID= # Optional +DEPLOYER_PRIVATE_KEY= # For contract deployment, must be funded on target network +``` + +Get an Alchemy API key from the [Alchemy Dashboard](https://www.alchemy.com/dashboard). + +## Development + +```bash +bun dev # Run the web app locally +bun build # Build for production +bun lint # Lint +bun type-check # Type-check +``` + +### Smart Contracts + +```bash +bun contracts:compile # Compile contracts and regenerate artifacts +bun contracts:test # Run contract tests +bun contracts:deploy:shape-sepolia # Deploy to Shape Sepolia +bun contracts:artifact # Regenerate deployment artifacts for the web app +bun wagmi:generate # Regenerate wagmi typed ABI hooks +``` + +## What's Included? + +- **Wallet Connection**: wagmi for MetaMask (or other wallet providers) integration. Connect with one click. +- **Shape RPC**: Pre-configured with Shape's RPC via Alchemy. Swap to your own node in `.env`. +- **Smart Contracts**: Hardhat setup with a sample `HelloShape` contract, deployment scripts, and typed wagmi hooks generated from your ABIs. +- **UI Components**: Based on [shadcn/ui](https://ui.shadcn.com/) & Tailwind CSS, customize to your heart's content. +- **AI-Ready**: Pairs with the [Shape MCP server](https://docs.shape.network/building-on-shape/ai.md) and Vercel AI SDK for agentic apps. + +## Deploy to Vercel + +Push to GitHub, import to [Vercel](https://vercel.com/new), set env vars in the UI, and deploy. Instant live app! + +## Resources + +- [Builder Kit repository](https://github.com/shape-network/builder-kit) +- [create-shape-app on npm](https://www.npmjs.com/package/create-shape-app) +- [Live demo](https://builder-kit.vercel.app/) + +Questions? Hit up [@williamhzo](https://x.com/williamhzo) or [Shape Discord](https://discord.com/invite/shape-l2). Let's build! diff --git a/public/building-on-shape/differences-ethereum-shape.md b/public/building-on-shape/differences-ethereum-shape.md new file mode 100644 index 0000000..b095e99 --- /dev/null +++ b/public/building-on-shape/differences-ethereum-shape.md @@ -0,0 +1,36 @@ +# Differences between Ethereum and Shape + +Shape is EVM equivalent, but has some minor differences. + +Shape is built on Optimism's [OP Stack](https://docs.optimism.io/stack/getting-started), an open-source public good designed to be EVM equivalent and introduce as few changes as possible to the Ethereum protocol. This makes it easy to build on Shape. + +There are some minor differences developers should be aware of: + +## Key Differences + +### Opcodes + +Shape maintains EVM equivalence but has some modified opcodes to support its Layer 2 architecture. For detailed information about specific opcode changes, refer to the [Optimism documentation](https://docs.optimism.io/chain/differences#opcodes). + +### Transaction Fees + +Shape's transaction fee structure differs from Ethereum's: + +- Shape uses a dual-fee system with L1 and L2 fees +- L2 fees are significantly lower than Ethereum's gas fees +- Shape has [Gasback](https://docs.shape.network/gasback.md), returning 80% of L2 fees to contract owners + +More information [here](https://docs.shape.network/building-on-shape/transaction-fees.md). + +### Block Time + +- Shape produces blocks every 2 seconds (vs Ethereum's ~12 seconds) +- This enables quicker transaction confirmations + +### Network Architecture + +- Shape is a Layer 2 solution built on top of Ethereum +- It inherits Ethereum's security while providing scalability benefits +- Transactions are batched and submitted to Ethereum for final settlement + +For more detailed technical information about these differences, please refer to the [Optimism documentation](https://docs.optimism.io/chain/differences/). diff --git a/public/building-on-shape/onchain-compatible/assembly.md b/public/building-on-shape/onchain-compatible/assembly.md new file mode 100644 index 0000000..c48b1b2 --- /dev/null +++ b/public/building-on-shape/onchain-compatible/assembly.md @@ -0,0 +1,335 @@ +# Assembly + +## Overview + +The Assembly system, built on top of Otoms, is a flexible ERC1155 implementation enabling the creation, crafting, and management of both fungible and non-fungible items on the blockchain. Built with upgradeability in mind, the system allows for component-based crafting where items can be created using blueprints that define required components with specific properties. + +It's a community-driven and open source project, source code is available [here on GitHub](https://github.com/shape-network/assembly), where you'll find both code for the web dApp implementation and the contracts. + +We greatly welcome contributions to the project! Please reach out on [Discord](https://discord.com/invite/shape-L2) or [Twitter/X](https://x.com/shape) if you'd like to get involved. + +### Key Components + +- **OtomItems**: Main ERC1155 token contract that implements the token standard and handles token operations +- **OtomItemsCore**: Manages item definitions, crafting logic, and item usage behaviors +- **OtomItemsTracking**: Tracks ownership and supplies of items without requiring an offchain indexer + +## Item Types + +The system supports two primary item types: + +1. **Fungible Items**: Standard fungible tokens that stack in inventory, useful for resources or consumables that all have identical properties at all times e.g. bricks, oak logs, gold ore +2. **Non-Fungible Items**: Unique items that can have tiers (1-7) and dynamic properties, suitable for equipment or collectibles where each instance of an item could have different properties at any given time e.g. a car with differing amounts of fuel in the tank + +## Item and Token ID System + +The Otom Items system uses two ID types to track items and their instances: + +- **Item IDs**: Sequential identifiers that represent item definitions or blueprints. Each distinct item type (like "Steel Sword" or "Health Potion") has a unique item ID assigned when it's created. Item IDs define what an item is, including its blueprint requirements, traits, and behaviors. +- **Token IDs**: ERC1155 token identifiers that represent specific instances or quantities of items owned by users. For fungible items, the token ID == item ID, as all instances are identical. For non-fungible items, each crafted instance receives a unique token ID that maps back to its parent item ID. The system maintains this mapping through `getItemIdForToken()`. Non-fungible tokens also store tier information and the actual components used in crafting, enabling dynamic properties based on crafting input. Practically, token IDs are derived by concatenating the item id and the mint count of that item + +The system uses a specific function `getNonFungibleTokenId(itemId, mintIndex)` to generate token IDs for non-fungible items: + +``` +function getNonFungibleTokenId(uint256 itemId, uint256 mintIndex) { + return (uint256(keccak256(abi.encodePacked(itemId, mintIndex))) % 2 ** 128) + 2 ** 128; +} + +``` + +This function creates a unique token ID by hashing the item ID and mint index together, then ensuring the result is above 2^128. This approach guarantees that: + +1. Each non-fungible token has a unique ID +2. The token ID range is distinct from fungible tokens (all non-fungible token IDs are greater than 2^128), and all fungible token ids are less than 2^128 +3. ID collisions are prevented by the cryptographic properties of keccak256 hashing, which creates a unique output for each unique (itemId, mintIndex) pair + +## Blueprint System + +Items are defined by blueprints that specify: + +- Required components (Otoms, variable Otoms, or other items) +- Property criteria that components must meet +- Quantities of each component needed + +### Component Types + +``` +OTOM - Specific Otom token required +VARIABLE_OTOM - Any Otom meeting property criteria +FUNGIBLE_ITEM - Fungible item component +NON_FUNGIBLE_ITEM - Non-fungible item component + +``` + +### Property Criteria + +Components can be required to have specific properties within defined ranges: + +``` +PropertyCriterion: +- PropertyType (e.g., ATOM_RADIUS, MASS, ELECTRONEGATIVITY) +- Min/Max values for numerical properties +- Boolean values for flag properties +- String values for categorical properties e.g. the decay type must match some string +- Bytes32 values for the universe hash property + +``` + +## Item Creation and Crafting + +### Creation Flow + +1. User creates item definitions with `createFungibleItem` or `createNonFungibleItem` +2. Each item receives a unique ID and blueprint definition +3. Base traits can be defined at creation time, and for non fungible tokens, get updated as the item is used, or at craft time if the blueprint is variable. Fungible token base traits never change. + +### Crafting Flow + +1. User calls `craftItem` with item ID, amount, and any variable components + 1. When crafting variable blueprints, two arrays are provided, 1 for otom token ids used in the variable slots, and 1 for the item token ids used in the variable slots. The ordering of ids within those arrays matter - the first VARIABLE_OTOM blueprint component will be filled by the first element in the first array, and so on. + 2. Arrays are not needed for OTOM and FUNGIBLE ITEM blueprint components because the token ids are predefined in the blueprint. +2. System verifies user has required components meeting criteria +3. System burns the components as part of crafting +4. For non-fungible items, tier is calculated via mutator contract +5. New item tokens are minted to the user with appropriate traits + +Items can be "frozen", meaning their core properties (name, description, mutator address, initial traits) can no longer be updated, and the behaviour of mutation is set in stone. Freezing is a one way operation. + +## Tier System + +Non-fungible items have optional tiers (1-7) that are calculated by mutator contracts based on components used and price paid in crafting. + +The intent is for users to seek out the most powerful otoms to use in blueprints, so that they can get the top tier version of the item. + +Tiers are not named, they should just be referred to as T1 through T7. This is so that at a glance every user knows the relative power the item is considered to have. + +If all instances of a non fungible item are equal, the developer can set the tier to 0 and no tier will be set. + +## Item Usage + +Items can be: + +- **Crafted**: Trigger custom logic in mutator contracts through `onCraft` + - This hook allows custom checks to be made when crafting an item e.g. a limited edition craft only available for a set time period. +- **Used**: Trigger custom logic in mutator contracts through `useItem` + - ONLY non fungible items can be used in this way + - The intent is that "using" an item then causes the traits to be altered in some way. Differing traits for the same item is only possible if the item is non fungible + - Using an item may destroy it, if the mutator contract called in the use function says so +- **Consumed**: Burned via `consumeItem` + - ONLY fungible items can be consumed + - Fungible items have no reason to be "used" because the tokens are all identical. But they can still be "consumed", e.g., using 10 bricks to build a house, the 10 bricks will be consumed. + +The `useItem` and `consumeItem` functions are expected to be called by contracts, not by users directly. In order for the calls to succeed, the user must have granted approval to the caller to be allowed to use their OtomItems nfts. There are 3 ways to grant approval: + +1. Call the ERC1155 `setApprovalForAll` function on the nft contract itself - unsafe because it means the operator will have access to all of the user's items even if they aren't relevant +2. Call `setApprovalForItemIds` on the core contract, which approves an operator to consume that item or use any instance of a non fungible item +3. Call `setApprovalForTokenIds` on the core contract, which approves an operator to use/consume that specific token id + +## Trait System + +Items have dynamic traits that: + +``` +Trait: +- typeName: The name of the trait +- valueString: String representation (for STRING type traits) +- valueNumber: Numeric representation (for NUMBER type traits) +- traitType: Either NUMBER or STRING + +``` + +- Can be updated through item usage via mutator contracts +- Affect item functionality and appearance +- Store custom metadata relevant to the item + +## Rendering + +The rendering is handled by a hot swappable renderer contract. All token metadata is onchain. The image rendered is simply the name of the item (and tier), plus the blueprint used to create it. + +When creating items, users can provide a "default image uri" for the fungible token and for all tiers of non fungible tokens. This image is not what will appear in wallets and marketplaces, but front ends for the items system (e.g. Assembly), can use these images instead of the onchain svg. + +## Creating items + +### Step-by-step guides for creating different items for Assembly + +We'll be using Hardhat in the examples below. Here's the [Otoms repo](https://github.com/shape-network/assembly/tree/main/packages/contracts/contracts/items) if you'd prefer to take a look beforehand. + +#### Creating fungible items + +1. Fill in the following data (use this example data to get started) + +```jsx +const item = { + // name, description, & imageUri: used to generate the NFT metadata. + name: 'Jusonic Ore', + description: 'A ductile metal, known for its strength and lightweight', + imageUri: 'https://arweave.net/cBCEZ6bqtmdkS6Vj8dIAgXhl4O8oDSyAWuqCMlCDToU', + // blueprint: list of Otoms used to craft your Item + // (in our example we chose the Otom Ju2 with the an amount of 2). + blueprint: [ + { + componentType: 0, // ComponentType.OTOM + itemIdOrOtomTokenId: + '35159569680903626501449329353512578019171730918789714169601127546706358467814', // Ju2 + amount: 3, + criteria: [], + }, + ], + // traits: these are optional + traits: [ + { + typeName: 'Strength', + valueString: '70', + valueNumber: 70, + traitType: 0, // TraitType.NUMBER + }, + { + typeName: 'Weight', + valueString: '10', + valueNumber: 10, + traitType: 0, // TraitType.NUMBER + }, + { + typeName: 'Build Materials', + valueString: 'Three Ju2', + valueNumber: 0, + traitType: 1, // TraitType.STRING + }, + ], + // costInWei: what you want to charge for the item + costInWei: 0, + // feeRecipient: who should get the fees generated from by item + feeRecipient: '0x0000000000000000000000000000000000000000', +}; +``` + +1. Call the `createFungibleItem` function on the `OtomItemsCore` contract + +```jsx +const core = await ethers.getContractAt( + 'OtomItemsCore', + '0xe8af571878D33CfecA4eA11caEf124E5ef105a30' // Shape Mainnet +); + +await core.createFungibleItem( + item.name, + item.description, + item.imageUri, + item.blueprint, + item.traits, + item.costInWei, + item.feeRecipient +); +``` + +And that's all you need to create your first fungible Assembly item. + +#### Creating non-fungible items + +1. Fill in the following data + 1. **Note: this example data is different than the previous example data** + +```jsx +const testPick = { + // name, description, & imageUri: used to generate the NFT metadata. + name: 'Invisibility Cloak', + description: 'A mythical cloak that grants invisibility', + imageUri: 'https://arweave.net/D3uuvnLDY48wmJ_Qic5l3AUrQ1pfOaUYn79t9PJYG18', + // tieredImageUris: used for tiered items; optionally leave empty. + tieredImageUris: ['', '', '', '', '', '', ''], + // blueprint: list of Otoms used to craft your Item + // (in our example we chose the Otom Ju3 with the an amount of 1). + blueprint: [ + { + componentType: 0, // ComponentType.OTOM + itemIdOrOtomTokenId: + '59556967404187678662646267921069430003902119556859655597906602022599940926148', // T15 + amount: 1, + criteria: [], + }, + { + componentType: 0, // ComponentType.OTOM + itemIdOrOtomTokenId: + '103207475906385737307003328874764609497044818069100475897999853498353983732479', // Sr2 + amount: 2, + criteria: [], + }, + ], + // traits: these are optional, + // but become useful when paired with a mutator contract (more on that later). + traits: [ + { + typeName: 'Ability', + valueString: 'Invisibility', + valueNumber: 0, + traitType: 1, // TraitType.STRING + }, + { + typeName: 'Build Materials', + valueString: 'T15 and two Sr2', + valueNumber: 0, + traitType: 1, // TraitType.STRING + }, + ], + // costInWei: what you want to charge for the item + costInWei: 0, + // feeRecipient: who should get the fee + feeRecipient: '0x0000000000000000000000000000000000000000', +}; +``` + +1. Call the `createNonFungibleItem` function on the `OtomItemsCore` contract + +```jsx +const core = await ethers.getContractAt( + 'OtomItemsCore', + '0xe8af571878D33CfecA4eA11caEf124E5ef105a30' // Shape Mainnet +); + +await core.createNonFungibleItem( + item.name, + item.description, + item.imageUri, + item.tieredImageUris, + item.blueprint, + item.traits, + '0x0000000000000000000000000000000000000000', + // ^this is where you mutator address would go + item.costInWei, + item.feeRecipient +); +``` + +Now you can create non-fungible items for Assembly. + +#### Creating non-fungible items (with a mutator) + +1. Create your mutator contract and implement the `IOtomItemMutator` hooks for custom item logic (`calculateTier`, `onCraft`, `onItemUse`, `onTransfer`) + 1. **Here is the [interface](https://github.com/shape-network/assembly/blob/main/packages/contracts/contracts/interfaces/IOtomItemMutator.sol) you will need, and here is an example of a [generic mutator](https://github.com/shape-network/assembly/blob/main/packages/contracts/contracts/items/mutators/GenericMutator.sol)** +2. Once you've deployed your mutator contract, follow step #1 of the previous tutorial + 1. **Note: If you handle tiers inside your mutator contract, try adding `tieredImageUris`** +3. Now we will call the `createNonFungibleItem` function on the `OtomItemsCore` contract, this time we pass in our mutator address + +```jsx +const core = await ethers.getContractAt( + 'OtomItemsCore', + '0xe8af571878D33CfecA4eA11caEf124E5ef105a30' // Shape Mainnet +); + +const mutatorAddress = '0xYourContractAddressHere'; + +await core.createNonFungibleItem( + item.name, + item.description, + item.imageUri, + item.tieredImageUris, + item.blueprint, + item.traits, + mutatorAddress, + // ^this is the only difference + item.costInWei, + item.feeRecipient +); +``` + +Now you've created an Assembly item with a custom mutator contract. diff --git a/public/building-on-shape/onchain-compatible/index.md b/public/building-on-shape/onchain-compatible/index.md new file mode 100644 index 0000000..44ba861 --- /dev/null +++ b/public/building-on-shape/onchain-compatible/index.md @@ -0,0 +1,9 @@ +# Onchain Compatible Projects + +A collection of projects made with interoperability in mind + +- [Assembly](https://docs.shape.network/building-on-shape/onchain-compatible/assembly.md): A flexible ERC1155 system for creating and crafting composable items + +- [OTOM by Kjetil Golid](https://docs.shape.network/building-on-shape/onchain-compatible/otom.md): Create and experiment with particles called otoms + +- [Moveable Type by DEAFBEEF](https://moveabletype.deafbeef.com/) diff --git a/public/building-on-shape/onchain-compatible/otom.md b/public/building-on-shape/onchain-compatible/otom.md new file mode 100644 index 0000000..7c26d69 --- /dev/null +++ b/public/building-on-shape/onchain-compatible/otom.md @@ -0,0 +1,238 @@ +# OTOM by Kjetil Golid + +Create and experiment with particles called otoms + +**Website**: [otom.xyz](https://otom.xyz/) + +**Repo:** [github.com/shape-network/otom-contracts](https://github.com/shape-network/otom-contracts) + +There are four main actions a chemist can take within the otoms universe. + +1. **Mine for Otoms** +2. **Annihilate said Otoms and receive Energy (ERC20)** +3. **Use Energy along with multiple Otoms to initiate a reaction** +4. **Analyze reactions and receive molecules (Chemists can analyze multiple unanalyzed reactions in a single transaction)** + +## Contracts + +### Shape Mainnet + +| Link | Description | Address | +| ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | +| [**Otoms**](https://shapescan.xyz/address/0x2f9810789aebBB6cdC6c0332948fF3B6D11121E3?tab=contract) | Main NFT contract for minting otoms | `0x2f9810789aebBB6cdC6c0332948fF3B6D11121E3` | +| [**OtomsDatabase**](https://shapescan.xyz/address/0x953761a771d6Ad9F888e41b3E7c9338a32b1A346?tab=contract) | DB used for storing information related to things like; tokenURI, Molecules, Who first discovered a Molecule, Universes | `0x953761a771d6Ad9F888e41b3E7c9338a32b1A346` | +| [**OtomsReactionOutputs**](https://shapescan.xyz/address/0x7d5A370F277e1847E4f768a88758237c6E3456eD?tab=contract) | Secondary NFT contract of unextracted Molecules | `0x7d5A370F277e1847E4f768a88758237c6E3456eD` | +| [**Energy**](https://shapescan.xyz/address/0x42276dF82BAb34c3CCcA9e5c058b6ff7EA4d07e3?tab=contract) | Fungible token used in reactions | `0x42276dF82BAb34c3CCcA9e5c058b6ff7EA4d07e3` | +| [**Reactor**](https://shapescan.xyz/address/0xB8874fCE9b702B191C306A21c7A4a101FB14a0fc?tab=contract) | Main reactor contract, used to initialize and analyze reactions | `0xB8874fCE9b702B191C306A21c7A4a101FB14a0fc` | +| [**Annihilator**](https://shapescan.xyz/address/0xca3088aedaAB138cAB3F0c135ceD77aF1a8b9063?tab=contract) | Used to convert NFT Otoms into fungible Energy | `0xca3088aedaAB138cAB3F0c135ceD77aF1a8b9063` | + +### Shape Sepolia + +| Link | Description | Address | +| ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | +| [**Otoms**](https://sepolia.shapescan.xyz/address/0xc709F59f1356230025d4fdFDCeD92341A14FF2F8?tab=contract) | Main NFT contract for minting otoms | `0xc709F59f1356230025d4fdFDCeD92341A14FF2F8` | +| [**OtomsDatabase**](https://sepolia.shapescan.xyz/address/0xC6E01938846D3d62EafD7FF485afeE416f6D8A40?tab=contract) | DB used for storing information related to things like; tokenURI, Molecules, Who first discovered a Molecule, Universes | `0xC6E01938846D3d62EafD7FF485afeE416f6D8A40` | +| [**OtomsReactionOutputs**](https://sepolia.shapescan.xyz/address/0x042125947523dD14dc64e3093a53DfCcdF07d979?tab=contract) | Secondary NFT contract of unextracted Molecules | `0x042125947523dD14dc64e3093a53DfCcdF07d979` | +| [**Energy**](https://sepolia.shapescan.xyz/address/0xe59D1719d3F8c149B009cB05a7679ce1dC074787?tab=contract) | Fungible token used in reactions | `0xe59D1719d3F8c149B009cB05a7679ce1dC074787` | +| [**Reactor**](https://sepolia.shapescan.xyz/address/0x62C87dd718E60c31993cf1a5EB32EE472C7eD144?tab=contract) | Main reactor contract, used to initialize and analyze reactions | `0x62C87dd718E60c31993cf1a5EB32EE472C7eD144` | +| [**Annihilator**](https://sepolia.shapescan.xyz/address/0xC998b6604aA50F71dd1b52884544c9107cf267E9?tab=contract) | Used to convert NFT Otoms into fungible Energy | `0xC998b6604aA50F71dd1b52884544c9107cf267E9` | + +## Functionality + +### Mining Otoms + +```solidity filename="Otoms.sol" +/** + * @dev Mines atoms based on the provided payloads. + * @param _payloads The payloads to mine atoms from. + * @return The token IDs of the mined atoms. + */ +function mine( + MiningPayload[] calldata payloads +) external returns (uint256[] memory); +``` + +### Mining Payload + +```solidity filename="IOtoms.sol" +struct MiningPayload { + Molecule minedMolecule; + bytes32 miningHash; + string tokenUri; + bytes32 universeHash; + uint256 expiry; + bytes signature; +} +``` + +### Reacting with Otoms + +```solidity filename="Reactor.sol" +/** + * @dev Initiates a reaction with the provided atom IDs and energy amount. + * @param atomIds The token IDs of the atoms to be used in the reaction. + * @param energyAmount The amount of energy to be used in the reaction. + * @return The token ID of the output of the reaction. + */ +function initiateReaction( + uint256[] memory atomIds, + uint256 energyAmount +) external returns (uint256); + +/** + * @dev Analyses the provided reaction results and returns + * the output of the reaction. + * @param reactionResults The results of the reaction. + * @param expiry The expiry time of the reaction. + * @param signature The signature of the reaction. + * @return The output of the reaction. + */ +function analyseReactions( + ReactionResult[] memory reactionResults, + uint256 expiry, + bytes memory signature +) external; +``` + +### Annihilating Otoms + +```solidity filename="Annihilator.sol" +/** + * @dev Annihilates the provided atom IDs. + * @param atomIds The token IDs of the atoms to be annihilated. + * @return The amount of energy produced by the annihilations. + */ +function annihilate( + uint256[] memory atomIds +) external nonReentrant returns (uint256) +``` + +## Structs + +```solidity filename="IOtomsDatabase.sol" +struct Molecule { + string id; + string name; + bytes32 universeHash; + uint256 activationEnergy; + uint256 radius; + Bond bond; + Atom[] givingAtoms; + Atom[] receivingAtoms; + uint256 electricalConductivity; + uint256 thermalConductivity; + uint256 toughness; + uint256 hardness; + uint256 ductility; +} + +struct Atom { + uint256 radius; + uint256 volume; + uint256 mass; + uint256 density; + uint256 electronegativity; + bool metallic; + string name; + string series; + uint256 periodicTableX; + uint256 periodicTableY; + AtomStructure structure; + Nucleus nucleus; +} +``` + +> We've included the three main structs used for mining otoms. Check out `IOtoms.sol` and +> `IOtomsDatabase.sol` for more info. + +## Data + +```solidity filename="OtomsDatabase.sol" +function getMoleculeByTokenId( + uint256 tokenId +) external view returns (Molecule memory); + +function getUniverseInformation( + bytes32 universeHash +) external view returns (UniverseInformation memory); + +function getMoleculesDiscovered( + bytes32 universeHash +) external view returns (Molecule[] memory); + +function getMoleculesDiscoveredPaginated( + bytes32 universeHash, + uint256 offset, + uint256 limit +) external view returns (Molecule[] memory molecules, uint256 total); + +function activeUniverses() external view returns (bytes32[] memory); +``` + +### Otoms + +```solidity filename="Otoms.sol" +function moleculeIsAtom( + Molecule memory _molecule +) external pure returns (bool); +``` + +### ReactionOutputs + +```solidity filename="OtomsReactionOutputs.sol" +function getReactionOutputData( + uint256 tokenId +) external view returns (ReactionOutputData memory); +``` + +## Encoding Utilities + +```solidity filename="IOtomsEncoder.sol" +function encodeMolecule( + Molecule memory _newMolecule +) external pure returns (bytes32); + +function encodeAtom( + Atom memory _newAtom +) external pure returns (bytes32); + +function encodeStructure( + AtomStructure memory _newStructure +) external pure returns (bytes32); + +function encodeNucleus( + Nucleus memory _newNucleus +) external pure returns (bytes32); + +function encodeUniverseInformation( + UniverseInformation memory _universeInformation +) external pure returns (bytes32); + +function getSeedUniverseMessageHash( + UniverseInformation memory _universeInformation, + uint256 expiry, + address sender +) external view returns (bytes32); + +function getMiningMessageHash( + Molecule memory _newAtom, + bytes32 _miningHash, + string memory _tokenUri, + bytes32 _universeHash, + uint256 expiry, + address sender +) external view returns (bytes32); + +function getMiningHash( + address _chemist, + bytes32 _universeHash, + uint256 _nonce +) external pure returns (bytes32); + +function getMultipleMiningHashes( + address _chemist, + bytes32 _universeHash, + uint256 _startingNonce, + uint256 _count +) external pure returns (bytes32[] memory); +``` diff --git a/public/building-on-shape/superchain-incentives.md b/public/building-on-shape/superchain-incentives.md new file mode 100644 index 0000000..89819d3 --- /dev/null +++ b/public/building-on-shape/superchain-incentives.md @@ -0,0 +1,13 @@ +# Superchain incentives + +Learn about the Superchain incentives available to you as a Shape builder. + +Shape is a part of the [Superchain](https://app.optimism.io/superchain/). This means when you build on Shape, you become eligible for additional incentives, including: + +- [RetroPGF](https://app.optimism.io/retropgf): Rewarding your onchain impact + +- [Free contract deployment](https://docs.optimism.io/builders/app-developers/tutorials/deploy-for-free): Claim deployment rebates + +- [Gas sponsorship](https://console.optimism.io/): For your early users + +- [Launch support](https://console.optimism.io/): Amplified marketing through Superchain channels diff --git a/public/building-on-shape/transaction-fees.md b/public/building-on-shape/transaction-fees.md new file mode 100644 index 0000000..1266506 --- /dev/null +++ b/public/building-on-shape/transaction-fees.md @@ -0,0 +1,94 @@ +# Transaction Fees + +Learn how network fees work on Shape, what changes them, where they go, and how to estimate them. + +## How do network fees on Shape work? + +Shape transaction fees are paid in **Ether** ("ETH"). + +Every Shape transaction involves two separate costs: + +- **L1 Fee**: the security fee for publishing transaction data to Ethereum. +- **L2 Fee**: the execution fee for running the transaction on Shape. + +Fees on Shape are much cheaper than what you'd pay for an equivalent transaction on Ethereum. The total cost can still vary based on Ethereum network activity, Shape network activity, transaction size, and any priority fee you choose to include. + +## L1 Fee + +The L1 Fee is paid to ensure your transaction's data is published to Ethereum, guaranteeing its availability for nodes to download and execute. This is crucial for maintaining the security properties of Shape. + +This fee varies depending on the current base fee on Ethereum and the amount of transaction data that needs to be published. If the timing of your transaction is flexible, submitting during periods of lower Ethereum gas can reduce the L1 Fee. + +L1 Fees are used to cover costs paid to Ethereum validators. + +## L2 Fee + +The L2 Fee is paid to execute your transaction on Shape. It has two components: a base fee and a priority fee. + +The **base fee** is the minimum required for your transaction to be included in a block. + +The **priority fee** is _optional_, and you decide how much to pay if you choose to include it. + +> Shape executes transactions in descending priority order - with higher priority fees taking +> precedence over lower priority fees - so the priority fee allows you to efficiently express +> the urgency of your transaction. + +The L2 Fee is also known as the **Sequencer Fee**. You can find more information about transaction fee calculation in the [OP Stack transaction fee documentation](https://docs.optimism.io/op-stack/transactions/fees). + +## Where do fees go? + +L1 Fees are used to cover the cost of publishing transaction data to Ethereum. + +**Shape directs 80% of ETH collected from L2 Fees back to the contracts that generated the activity**, ensuring the creators and platforms that thrive on the network share in its success. + +> Learn more about how this works in [Gasback](https://docs.shape.network/gasback.md). + +For the remaining 20%: + +- 15% goes to the Optimism Collective to fund public goods +- 5% goes to infrastructure and the Shape Foundation during the early stages of the network + +## Minimum Base Fee + +Shape uses a minimum L2 base fee to keep execution fees from falling to near-zero during quiet periods. This floor keeps blockspace predictably priced while preserving low transaction costs for apps, creators, and users. + +The minimum L2 base fee on Shape Mainnet is 10,000,000 wei (0.01 gwei). Shape may adjust this value as network usage evolves. At 0.01 gwei, a transaction using 200,000 L2 gas costs about $0.004 in L2 base fee when ETH is $2,000, before priority fees and the separate L1 data fee. + +### Why it matters + +- **Gasback alignment**: The minimum applies to L2 execution fees, which are the fees Shape shares with registered contracts through Gasback. +- **More reliable inclusion**: A nonzero floor helps the fee market respond when demand increases after quiet periods, reducing the chance that transactions wait while fees catch up. +- **Predictable app costs**: During normal demand, the L2 base fee should remain close to the floor. During congestion, it can rise with network usage. +- **Healthier blockspace pricing**: The floor discourages low-value spam while keeping normal Shape transactions inexpensive. + +## EIP-1559 fee behavior + +Shape uses the OP Stack's implementation of EIP-1559 for L2 execution fees. The L2 base fee adjusts in response to network demand, while the priority fee lets users express transaction urgency. + +When Shape is less busy, the L2 base fee can decrease. When blocks are more heavily used, the L2 base fee can increase. This is separate from the L1 Fee, which varies with Ethereum gas costs and the size of the transaction data being posted. + +OP Stack chains can tune fee behavior with parameters such as EIP-1559 elasticity, EIP-1559 denominator, gas limit, and minimum base fee. Shape-specific values are not listed here unless published or verified from the live network configuration. For the underlying OP Stack parameter model, see the [OP Stack fee parameter documentation](https://docs.optimism.io/chain-operators/guides/management/transaction-fees-101). + +## Querying the L1 fee + +The **GasPriceOracle** predeploy at `0x420000000000000000000000000000000000000F` lets you programmatically estimate the L1 Fee component before signing and submitting a transaction. + +| Method | Returns | +| ------------------------------------ | -------------------------------------------------------------------- | +| `getL1Fee(bytes)` | Exact L1 fee for a fully serialized transaction | +| `getL1FeeUpperBound(uint256 txSize)` | Upper-bound L1 fee estimate from approximate transaction byte length | +| `l1BaseFee()` | Current Ethereum L1 base fee as seen by Shape | +| `blobBaseFee()` | Current EIP-4844 blob base fee | +| `baseFeeScalar()` | Scalar applied to the L1 base fee component | +| `blobBaseFeeScalar()` | Scalar applied to the blob base fee component | + +Use `getL1FeeUpperBound` when you need a quick estimate before the transaction is fully constructed. Use `getL1Fee` with the complete serialized transaction for an exact estimate before signing. + +The GasPriceOracle address is also listed in [Contract Addresses](https://docs.shape.network/technical-details/contract-addresses.md). + +## Related resources + +- [Gasback](https://docs.shape.network/gasback.md) +- [Network Information](https://docs.shape.network/technical-details/network-information.md) +- [Contract Addresses](https://docs.shape.network/technical-details/contract-addresses.md) +- [OP Stack transaction fees](https://docs.optimism.io/op-stack/transactions/fees) diff --git a/public/gasback.md b/public/gasback.md new file mode 100644 index 0000000..2d6f5d2 --- /dev/null +++ b/public/gasback.md @@ -0,0 +1,24 @@ +# Gasback + +Claim back 80% of the sequencer fees that users spend interacting with your contracts on Shape. + +## What is Gasback? + +Shape redistributes the **majority of sequencer fees spent by users to execute transactions** back to the contracts they interacted with, ensuring the creators and platforms that thrive on the network share in its success. This concept is called **Gasback**. + +### I own a contract on Shape. How much gas do I get back? + +All contract owners can claim back **80%** of the [L2 Fees](https://docs.shape.network/building-on-shape/transaction-fees.md) generated from users interacting with their contracts on Shape. + +### How do I take part in Gasback? + +**Gasback** is open to all smart contract owners on Shape. There are two ways to register your contracts: + +1. [Register via the Dashboard](https://docs.shape.network/tutorials/registering-contract-gasback/dashboard.md) +2. [Register programmatically](https://docs.shape.network/tutorials/registering-contract-gasback/programmatically.md) + +Once registered, you'll be able to claim your share of the sequencer fees generated by your contracts' activity. + +> Learn how to +> [register your contracts for Gasback here](https://docs.shape.network/tutorials/registering-contract-gasback/index.md) +> . diff --git a/public/index.md b/public/index.md new file mode 100644 index 0000000..7f9ec85 --- /dev/null +++ b/public/index.md @@ -0,0 +1,36 @@ +# Welcome + +Shape is the culture-first L2 built on top of Ethereum to power the new NFT economy. + +The network is an open space where everyone is free to create whatever they want - from fine art, to weird experiments, to whole new ideas - making it the place for culture to take root. + +## Why create on Shape? + +### Shape Culture. Get Gasback. + +As a creator on Shape, you can claim back 80% of sequencer fees users spend interacting with your contracts. This includes contracts you build yourself, contracts you acquire ownership of, and contracts that you deploy through other platforms. + +> Learn more about how this works in [Gasback](https://docs.shape.network/gasback.md). + +### The best of Ethereum. + +Shape is [EVM equivalent](https://docs.shape.network/building-on-shape/differences-ethereum-shape.md). This means your creator experience is the same as on Ethereum, just at a fraction of the cost. + +### Secure, stable & scalable. + +Shape inherits its security directly from Ethereum, keeping the networks intrinsically linked forever. + +Shape also prioritizes stability and scalability, utilizing [Alchemy](https://docs.shape.network/building-on-shape/alchemy-api.md) and [Optimism](https://www.optimism.io/) as key infrastructure partners to help achieve and maintain these states. + +### Shape the Superchain. + +Shape is a member of the [Superchain](https://docs.optimism.io/stack/explainer), which unlocks a range of further benefits for the entire ecosystem - including ongoing network-level cooperation, funding of public goods, and additional builder incentives on Shape. + +### Home for unique NFT experiments + +Shape is the proof that NFTs aren't just static images that people can buy and sell. + +- Deep dive into the rabbit hole of onchain chemistry with [OTOM](https://docs.shape.network/building-on-shape/onchain-compatible/otom.md) by Kjetil Golid. +- Wander in Leander Herzog's [Infinite Garden](https://infinite-garden.xyz/) +- Create & craft your own [Assembly Items](https://docs.shape.network/building-on-shape/onchain-compatible/assembly.md) +- And [many more...](https://shape.network/) diff --git a/public/llms-full.txt b/public/llms-full.txt new file mode 100644 index 0000000..38b0578 --- /dev/null +++ b/public/llms-full.txt @@ -0,0 +1,2613 @@ +# Shape Technical Documentation + +Generated from the official documentation source. This is the technical corpus; token and governance information is maintained at https://shape.network/token. + +--- + +Canonical page: https://docs.shape.network/building-on-shape/ai +Markdown page: https://docs.shape.network/building-on-shape/ai.md + +# AI Agents on Shape + +This guide gets you started with the Model Context Protocol (MCP) and our Shape MCP server, tools to make your AI agents smarter onchain. We'll cover the basics, show how to plug in Vercel AI, and spark some NFT agent ideas. + +## What is MCP? + +MCP (Model Context Protocol) is a standard for letting AI models like ChatGPT, Grok, or Claude safely access and interact with external data. Think blockchains, APIs, or tools. It's like giving your agent a direct communication channel to Shape, with features for tool calls, resources, and permissions. MCP keeps things structured and extensible, while keeping granular control over access or authorization for example. + +For a deep dive, check the [official MCP intro](https://modelcontextprotocol.io/introduction). In short: MCP turns your AI into an Shape-connoisseur, chaining queries like "fetch Shape NFTs" to "analyze collections trends" without leaving the chat. + +## Shape MCP Server: Your On-Chain Data Bridge + +We've built a dedicated MCP server for Shape, wrapping key data like Gasback distributions, NFT analytics, and Stack medals. It's open-source, forkable, and ready for your agents. Built with [xmcp](https://xmcp.dev/), it's TypeScript-first so no need to learn Python, and it deploys in minutes. + +- **Repository**: [github.com/shape-network/mcp-server](https://github.com/shape-network/mcp-server) +- **Why Use It?** Agents can query Shape without raw RPC calls. E.g., simulate Gasback rewards or track Stack achievements. It's modular, so you can extend it for any project. + +### Quick Setup + +Fork the repo and deploy your own instance, keeping things non-hosted and under your control. + +1. Fork and clone: `git clone https://github.com/shape-network/mcp-server` +2. Install: `yarn install` +3. Env vars in `.env`: `ALCHEMY_API_KEY=your-key`, `CHAIN_ID=360` (mainnet), optional `REDIS_URL` for caching. +4. Run locally: `yarn dev` (at http://localhost:3002/mcp) +5. Deploy to Vercel: Import the fork, set env vars in the UI, and hit deploy. + +For full tools and examples, see the [README](https://github.com/shape-network/mcp-server/blob/main/README.md). + +## Building AI Agents with Vercel AI SDK + +[Vercel AI SDK](https://ai-sdk.dev/docs/introduction) makes agent development a breeze. It's TypeScript-first, works with models like ChatGPT, Grok, or Claude, and handles streaming, tool calls, and chaining. Pair it with our MCP server for Shape-specific capabilities. + +### First Steps + +1. **Setup a Next.js App**: `npx create-next-app my-shape-agent`. (Pro tip: If you want a head start, run `bun create shape-app my-shape-agent` to scaffold a full Shape project with wallet connect, RPC setup, smart contracts, and UI components. See the [Builder Kit](https://docs.shape.network/building-on-shape/builder-kit.md) docs for details.) +2. **Install SDK**: `npm i ai @ai-sdk/openai @modelcontextprotocol/sdk viem wagmi` (for onchain integration) — [more info](https://ai-sdk.dev/docs/introduction). +3. **Connect MCP**: In an API route (e.g., /api/agent.ts): + + ```ts + import { openai } from '@ai-sdk/openai'; + import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; + import { experimental_createMCPClient, streamText } from 'ai'; + + export const maxDuration = 30; + + export async function POST(req: Request) { + const { messages } = await req.json(); + + // Connect to your deployed MCP server + const url = new URL('https://shape-mcp-server.vercel.app/mcp'); // or http://localhost:3002/mcp for local + const mcpClient = await experimental_createMCPClient({ + transport: new StreamableHTTPClientTransport(url), + }); + + // Get all available tools exposed + const tools = await mcpClient.tools(); + + const result = await streamText({ + model: openai('gpt-4o'), + tools, + messages, + maxSteps: 10, // Allow up to 10 sequential tool calls + system: 'You are a helpful assistant that [...]', // add your custom system prompt + onFinish: async () => { + await mcpClient.close(); + }, + }); + + return result.toDataStreamResponse(); + } + ``` + +4. **Add UI**: Use `useChat` hook in a page: + + ```ts + import { useChat } from 'ai/react'; + + export default function AgentChat() { + const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({ + api: '/api/agent', + maxSteps: 10, // Enable multi-step tool usage + }); + + return ( +
+
+ {messages.map(m => ( +
+ {m.role}: {m.content} +
+ ))} + {isLoading &&
Thinking...
} +
+
+ + +
+
+ ); + } + ``` + +5. **Deploy**: Push to GitHub, import to Vercel, set env vars, and go live. + +For full docs, see [Vercel AI SDK](https://vercel.com/docs/ai-sdk). + +## AI Agent Ideas for NFTs on Shape + +Shape's low fees and Gasback make it ideal for NFT agents. Here are fun starters—build these for the upcoming hackathon! + +- **NFT Curator Bot**: Queries `getCollectionAnalytics` to spot trending collections, then uses `getShapeNft` to suggest buys. Agent prompt: "Curate 5 underrated NFTs under 0.1 ETH—why buy?" +- **Gasback Optimizer**: Simulates rewards with `simulateGasbackRewards` for creators. Chains with `getTopShapeCreators` for comparisons. Prompt: "Optimize my contract for max Gasback—tx volume tips?" +- **Stack Achievement Coach**: Tracks progress via `getStackAchievements`, suggests actions (e.g., "Mint 3 more for gold medal"). Prompt: "What's my Stack level? Steps to next tier?" +- **Collection Analyzer**: Combines `getCollectionAnalytics` and `getChainStatus` to time mints. Prompt: "Is now good to mint on collection X? Gas low?" + +These leverage MCP for on-chain data, Vercel AI for reasoning—start simple, add wallet integration (wagmi) for actions. + +Questions? Hit up [@williamhzo](https://x.com/williamhzo) or [Shape Discord](https://discord.com/invite/shape-l2). Let's build!! + +--- + +Canonical page: https://docs.shape.network/building-on-shape/alchemy-api +Markdown page: https://docs.shape.network/building-on-shape/alchemy-api.md + +# Alchemy API + +Find out what Alchemy tools are available to use on Shape. + +Checkout [Alchemy's Quickstart guide](https://docs.alchemy.com/reference/shape-api-quickstart) for Shape API. The [full suite](https://www.alchemy.com/) of Alchemy tools are available for builders on Shape. + +Visit your [Alchemy dashboard](https://dashboard.alchemy.com/) and start building now! + +> Visit your [Alchemy dashboard](https://www.alchemy.com/dashboard) and start building +> now! + +--- + +Canonical page: https://docs.shape.network/building-on-shape/builder-kit +Markdown page: https://docs.shape.network/building-on-shape/builder-kit.md + +# Shape Builder Kit for Developers + +The Shape Builder Kit is your go-to starter for crafting dApps on the Shape ecosystem. It's a monorepo with a Next.js frontend (wagmi, viem) and a Hardhat smart contract package, all pre-wired with sensible defaults. + +- **Batteries Included**: Wallet connection, Shape RPC integration, and NFT fetching out of the box. No reinventing the wheel. +- **AI-Ready**: Pairs seamlessly with the [Shape MCP server](https://docs.shape.network/building-on-shape/ai.md) and Vercel AI SDK for agentic apps. +- **Fast Track to Deploy**: Built for Vercel, so you can deploy to prod in minutes and focus on getting your first users! + +It's completely open and composable: use it to kickstart, then tweak to your style & needs. Check it out: [github.com/shape-network/builder-kit](https://github.com/shape-network/builder-kit). + +## Quickstart with `create-shape-app` + +The fastest way to get started is [`create-shape-app`](https://github.com/shape-network/create-shape-app), a CLI that scaffolds a new project from the latest Builder Kit release. One command and you're in: + +```bash +npx create-shape-app my-app +# or +bun create shape-app my-app +``` + +Also works with pnpm and yarn: + +```bash +pnpm dlx create-shape-app my-app +yarn create shape-app my-app +``` + +The CLI will download the latest Builder Kit release, install dependencies, and initialize a git repository. + +### CLI Options + +| Option | Description | +| --- | --- | +| `-y, --yes` | Skip interactive confirmation prompts | +| `--pm ` | Select package manager (auto-detected if omitted) | +| `--skip-install` | Skip dependency installation | +| `--skip-git` | Skip git init and initial commit | +| `--template-ref ` | Pin a specific Builder Kit release tag (e.g. `v1.0.0`) | + +## Project Structure + +The scaffolded project is a monorepo with two packages: + +``` +my-app/ +├── apps/web/ # Next.js + wagmi frontend +└── packages/contract/ # Hardhat smart contracts +``` + +## Configuration + +Copy `.env.example` to `.env` and fill in your values: + +```env +NEXT_PUBLIC_ALCHEMY_KEY=your-alchemy-key +NEXT_PUBLIC_CHAIN_ID=11011 # 11011 for Shape Sepolia, 360 for Shape Mainnet +NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID= # Optional +DEPLOYER_PRIVATE_KEY= # For contract deployment, must be funded on target network +``` + +Get an Alchemy API key from the [Alchemy Dashboard](https://www.alchemy.com/dashboard). + +## Development + +```bash +bun dev # Run the web app locally +bun build # Build for production +bun lint # Lint +bun type-check # Type-check +``` + +### Smart Contracts + +```bash +bun contracts:compile # Compile contracts and regenerate artifacts +bun contracts:test # Run contract tests +bun contracts:deploy:shape-sepolia # Deploy to Shape Sepolia +bun contracts:artifact # Regenerate deployment artifacts for the web app +bun wagmi:generate # Regenerate wagmi typed ABI hooks +``` + +## What's Included? + +- **Wallet Connection**: wagmi for MetaMask (or other wallet providers) integration. Connect with one click. +- **Shape RPC**: Pre-configured with Shape's RPC via Alchemy. Swap to your own node in `.env`. +- **Smart Contracts**: Hardhat setup with a sample `HelloShape` contract, deployment scripts, and typed wagmi hooks generated from your ABIs. +- **UI Components**: Based on [shadcn/ui](https://ui.shadcn.com/) & Tailwind CSS, customize to your heart's content. +- **AI-Ready**: Pairs with the [Shape MCP server](https://docs.shape.network/building-on-shape/ai.md) and Vercel AI SDK for agentic apps. + +## Deploy to Vercel + +Push to GitHub, import to [Vercel](https://vercel.com/new), set env vars in the UI, and deploy. Instant live app! + +## Resources + +- [Builder Kit repository](https://github.com/shape-network/builder-kit) +- [create-shape-app on npm](https://www.npmjs.com/package/create-shape-app) +- [Live demo](https://builder-kit.vercel.app/) + +Questions? Hit up [@williamhzo](https://x.com/williamhzo) or [Shape Discord](https://discord.com/invite/shape-l2). Let's build! + +--- + +Canonical page: https://docs.shape.network/building-on-shape/differences-ethereum-shape +Markdown page: https://docs.shape.network/building-on-shape/differences-ethereum-shape.md + +# Differences between Ethereum and Shape + +Shape is EVM equivalent, but has some minor differences. + +Shape is built on Optimism's [OP Stack](https://docs.optimism.io/stack/getting-started), an open-source public good designed to be EVM equivalent and introduce as few changes as possible to the Ethereum protocol. This makes it easy to build on Shape. + +There are some minor differences developers should be aware of: + +## Key Differences + +### Opcodes + +Shape maintains EVM equivalence but has some modified opcodes to support its Layer 2 architecture. For detailed information about specific opcode changes, refer to the [Optimism documentation](https://docs.optimism.io/chain/differences#opcodes). + +### Transaction Fees + +Shape's transaction fee structure differs from Ethereum's: + +- Shape uses a dual-fee system with L1 and L2 fees +- L2 fees are significantly lower than Ethereum's gas fees +- Shape has [Gasback](https://docs.shape.network/gasback.md), returning 80% of L2 fees to contract owners + +More information [here](https://docs.shape.network/building-on-shape/transaction-fees.md). + +### Block Time + +- Shape produces blocks every 2 seconds (vs Ethereum's ~12 seconds) +- This enables quicker transaction confirmations + +### Network Architecture + +- Shape is a Layer 2 solution built on top of Ethereum +- It inherits Ethereum's security while providing scalability benefits +- Transactions are batched and submitted to Ethereum for final settlement + +For more detailed technical information about these differences, please refer to the [Optimism documentation](https://docs.optimism.io/chain/differences/). + +--- + +Canonical page: https://docs.shape.network/building-on-shape/onchain-compatible/assembly +Markdown page: https://docs.shape.network/building-on-shape/onchain-compatible/assembly.md + +# Assembly + +## Overview + +The Assembly system, built on top of Otoms, is a flexible ERC1155 implementation enabling the creation, crafting, and management of both fungible and non-fungible items on the blockchain. Built with upgradeability in mind, the system allows for component-based crafting where items can be created using blueprints that define required components with specific properties. + +It's a community-driven and open source project, source code is available [here on GitHub](https://github.com/shape-network/assembly), where you'll find both code for the web dApp implementation and the contracts. + +We greatly welcome contributions to the project! Please reach out on [Discord](https://discord.com/invite/shape-L2) or [Twitter/X](https://x.com/shape) if you'd like to get involved. + +### Key Components + +- **OtomItems**: Main ERC1155 token contract that implements the token standard and handles token operations +- **OtomItemsCore**: Manages item definitions, crafting logic, and item usage behaviors +- **OtomItemsTracking**: Tracks ownership and supplies of items without requiring an offchain indexer + +## Item Types + +The system supports two primary item types: + +1. **Fungible Items**: Standard fungible tokens that stack in inventory, useful for resources or consumables that all have identical properties at all times e.g. bricks, oak logs, gold ore +2. **Non-Fungible Items**: Unique items that can have tiers (1-7) and dynamic properties, suitable for equipment or collectibles where each instance of an item could have different properties at any given time e.g. a car with differing amounts of fuel in the tank + +## Item and Token ID System + +The Otom Items system uses two ID types to track items and their instances: + +- **Item IDs**: Sequential identifiers that represent item definitions or blueprints. Each distinct item type (like "Steel Sword" or "Health Potion") has a unique item ID assigned when it's created. Item IDs define what an item is, including its blueprint requirements, traits, and behaviors. +- **Token IDs**: ERC1155 token identifiers that represent specific instances or quantities of items owned by users. For fungible items, the token ID == item ID, as all instances are identical. For non-fungible items, each crafted instance receives a unique token ID that maps back to its parent item ID. The system maintains this mapping through `getItemIdForToken()`. Non-fungible tokens also store tier information and the actual components used in crafting, enabling dynamic properties based on crafting input. Practically, token IDs are derived by concatenating the item id and the mint count of that item + +The system uses a specific function `getNonFungibleTokenId(itemId, mintIndex)` to generate token IDs for non-fungible items: + +``` +function getNonFungibleTokenId(uint256 itemId, uint256 mintIndex) { + return (uint256(keccak256(abi.encodePacked(itemId, mintIndex))) % 2 ** 128) + 2 ** 128; +} + +``` + +This function creates a unique token ID by hashing the item ID and mint index together, then ensuring the result is above 2^128. This approach guarantees that: + +1. Each non-fungible token has a unique ID +2. The token ID range is distinct from fungible tokens (all non-fungible token IDs are greater than 2^128), and all fungible token ids are less than 2^128 +3. ID collisions are prevented by the cryptographic properties of keccak256 hashing, which creates a unique output for each unique (itemId, mintIndex) pair + +## Blueprint System + +Items are defined by blueprints that specify: + +- Required components (Otoms, variable Otoms, or other items) +- Property criteria that components must meet +- Quantities of each component needed + +### Component Types + +``` +OTOM - Specific Otom token required +VARIABLE_OTOM - Any Otom meeting property criteria +FUNGIBLE_ITEM - Fungible item component +NON_FUNGIBLE_ITEM - Non-fungible item component + +``` + +### Property Criteria + +Components can be required to have specific properties within defined ranges: + +``` +PropertyCriterion: +- PropertyType (e.g., ATOM_RADIUS, MASS, ELECTRONEGATIVITY) +- Min/Max values for numerical properties +- Boolean values for flag properties +- String values for categorical properties e.g. the decay type must match some string +- Bytes32 values for the universe hash property + +``` + +## Item Creation and Crafting + +### Creation Flow + +1. User creates item definitions with `createFungibleItem` or `createNonFungibleItem` +2. Each item receives a unique ID and blueprint definition +3. Base traits can be defined at creation time, and for non fungible tokens, get updated as the item is used, or at craft time if the blueprint is variable. Fungible token base traits never change. + +### Crafting Flow + +1. User calls `craftItem` with item ID, amount, and any variable components + 1. When crafting variable blueprints, two arrays are provided, 1 for otom token ids used in the variable slots, and 1 for the item token ids used in the variable slots. The ordering of ids within those arrays matter - the first VARIABLE_OTOM blueprint component will be filled by the first element in the first array, and so on. + 2. Arrays are not needed for OTOM and FUNGIBLE ITEM blueprint components because the token ids are predefined in the blueprint. +2. System verifies user has required components meeting criteria +3. System burns the components as part of crafting +4. For non-fungible items, tier is calculated via mutator contract +5. New item tokens are minted to the user with appropriate traits + +Items can be "frozen", meaning their core properties (name, description, mutator address, initial traits) can no longer be updated, and the behaviour of mutation is set in stone. Freezing is a one way operation. + +## Tier System + +Non-fungible items have optional tiers (1-7) that are calculated by mutator contracts based on components used and price paid in crafting. + +The intent is for users to seek out the most powerful otoms to use in blueprints, so that they can get the top tier version of the item. + +Tiers are not named, they should just be referred to as T1 through T7. This is so that at a glance every user knows the relative power the item is considered to have. + +If all instances of a non fungible item are equal, the developer can set the tier to 0 and no tier will be set. + +## Item Usage + +Items can be: + +- **Crafted**: Trigger custom logic in mutator contracts through `onCraft` + - This hook allows custom checks to be made when crafting an item e.g. a limited edition craft only available for a set time period. +- **Used**: Trigger custom logic in mutator contracts through `useItem` + - ONLY non fungible items can be used in this way + - The intent is that "using" an item then causes the traits to be altered in some way. Differing traits for the same item is only possible if the item is non fungible + - Using an item may destroy it, if the mutator contract called in the use function says so +- **Consumed**: Burned via `consumeItem` + - ONLY fungible items can be consumed + - Fungible items have no reason to be "used" because the tokens are all identical. But they can still be "consumed", e.g., using 10 bricks to build a house, the 10 bricks will be consumed. + +The `useItem` and `consumeItem` functions are expected to be called by contracts, not by users directly. In order for the calls to succeed, the user must have granted approval to the caller to be allowed to use their OtomItems nfts. There are 3 ways to grant approval: + +1. Call the ERC1155 `setApprovalForAll` function on the nft contract itself - unsafe because it means the operator will have access to all of the user's items even if they aren't relevant +2. Call `setApprovalForItemIds` on the core contract, which approves an operator to consume that item or use any instance of a non fungible item +3. Call `setApprovalForTokenIds` on the core contract, which approves an operator to use/consume that specific token id + +## Trait System + +Items have dynamic traits that: + +``` +Trait: +- typeName: The name of the trait +- valueString: String representation (for STRING type traits) +- valueNumber: Numeric representation (for NUMBER type traits) +- traitType: Either NUMBER or STRING + +``` + +- Can be updated through item usage via mutator contracts +- Affect item functionality and appearance +- Store custom metadata relevant to the item + +## Rendering + +The rendering is handled by a hot swappable renderer contract. All token metadata is onchain. The image rendered is simply the name of the item (and tier), plus the blueprint used to create it. + +When creating items, users can provide a "default image uri" for the fungible token and for all tiers of non fungible tokens. This image is not what will appear in wallets and marketplaces, but front ends for the items system (e.g. Assembly), can use these images instead of the onchain svg. + +## Creating items + +### Step-by-step guides for creating different items for Assembly + +We'll be using Hardhat in the examples below. Here's the [Otoms repo](https://github.com/shape-network/assembly/tree/main/packages/contracts/contracts/items) if you'd prefer to take a look beforehand. + +#### Creating fungible items + +1. Fill in the following data (use this example data to get started) + +```jsx +const item = { + // name, description, & imageUri: used to generate the NFT metadata. + name: 'Jusonic Ore', + description: 'A ductile metal, known for its strength and lightweight', + imageUri: 'https://arweave.net/cBCEZ6bqtmdkS6Vj8dIAgXhl4O8oDSyAWuqCMlCDToU', + // blueprint: list of Otoms used to craft your Item + // (in our example we chose the Otom Ju2 with the an amount of 2). + blueprint: [ + { + componentType: 0, // ComponentType.OTOM + itemIdOrOtomTokenId: + '35159569680903626501449329353512578019171730918789714169601127546706358467814', // Ju2 + amount: 3, + criteria: [], + }, + ], + // traits: these are optional + traits: [ + { + typeName: 'Strength', + valueString: '70', + valueNumber: 70, + traitType: 0, // TraitType.NUMBER + }, + { + typeName: 'Weight', + valueString: '10', + valueNumber: 10, + traitType: 0, // TraitType.NUMBER + }, + { + typeName: 'Build Materials', + valueString: 'Three Ju2', + valueNumber: 0, + traitType: 1, // TraitType.STRING + }, + ], + // costInWei: what you want to charge for the item + costInWei: 0, + // feeRecipient: who should get the fees generated from by item + feeRecipient: '0x0000000000000000000000000000000000000000', +}; +``` + +1. Call the `createFungibleItem` function on the `OtomItemsCore` contract + +```jsx +const core = await ethers.getContractAt( + 'OtomItemsCore', + '0xe8af571878D33CfecA4eA11caEf124E5ef105a30' // Shape Mainnet +); + +await core.createFungibleItem( + item.name, + item.description, + item.imageUri, + item.blueprint, + item.traits, + item.costInWei, + item.feeRecipient +); +``` + +And that's all you need to create your first fungible Assembly item. + +#### Creating non-fungible items + +1. Fill in the following data + 1. **Note: this example data is different than the previous example data** + +```jsx +const testPick = { + // name, description, & imageUri: used to generate the NFT metadata. + name: 'Invisibility Cloak', + description: 'A mythical cloak that grants invisibility', + imageUri: 'https://arweave.net/D3uuvnLDY48wmJ_Qic5l3AUrQ1pfOaUYn79t9PJYG18', + // tieredImageUris: used for tiered items; optionally leave empty. + tieredImageUris: ['', '', '', '', '', '', ''], + // blueprint: list of Otoms used to craft your Item + // (in our example we chose the Otom Ju3 with the an amount of 1). + blueprint: [ + { + componentType: 0, // ComponentType.OTOM + itemIdOrOtomTokenId: + '59556967404187678662646267921069430003902119556859655597906602022599940926148', // T15 + amount: 1, + criteria: [], + }, + { + componentType: 0, // ComponentType.OTOM + itemIdOrOtomTokenId: + '103207475906385737307003328874764609497044818069100475897999853498353983732479', // Sr2 + amount: 2, + criteria: [], + }, + ], + // traits: these are optional, + // but become useful when paired with a mutator contract (more on that later). + traits: [ + { + typeName: 'Ability', + valueString: 'Invisibility', + valueNumber: 0, + traitType: 1, // TraitType.STRING + }, + { + typeName: 'Build Materials', + valueString: 'T15 and two Sr2', + valueNumber: 0, + traitType: 1, // TraitType.STRING + }, + ], + // costInWei: what you want to charge for the item + costInWei: 0, + // feeRecipient: who should get the fee + feeRecipient: '0x0000000000000000000000000000000000000000', +}; +``` + +1. Call the `createNonFungibleItem` function on the `OtomItemsCore` contract + +```jsx +const core = await ethers.getContractAt( + 'OtomItemsCore', + '0xe8af571878D33CfecA4eA11caEf124E5ef105a30' // Shape Mainnet +); + +await core.createNonFungibleItem( + item.name, + item.description, + item.imageUri, + item.tieredImageUris, + item.blueprint, + item.traits, + '0x0000000000000000000000000000000000000000', + // ^this is where you mutator address would go + item.costInWei, + item.feeRecipient +); +``` + +Now you can create non-fungible items for Assembly. + +#### Creating non-fungible items (with a mutator) + +1. Create your mutator contract and implement the `IOtomItemMutator` hooks for custom item logic (`calculateTier`, `onCraft`, `onItemUse`, `onTransfer`) + 1. **Here is the [interface](https://github.com/shape-network/assembly/blob/main/packages/contracts/contracts/interfaces/IOtomItemMutator.sol) you will need, and here is an example of a [generic mutator](https://github.com/shape-network/assembly/blob/main/packages/contracts/contracts/items/mutators/GenericMutator.sol)** +2. Once you've deployed your mutator contract, follow step #1 of the previous tutorial + 1. **Note: If you handle tiers inside your mutator contract, try adding `tieredImageUris`** +3. Now we will call the `createNonFungibleItem` function on the `OtomItemsCore` contract, this time we pass in our mutator address + +```jsx +const core = await ethers.getContractAt( + 'OtomItemsCore', + '0xe8af571878D33CfecA4eA11caEf124E5ef105a30' // Shape Mainnet +); + +const mutatorAddress = '0xYourContractAddressHere'; + +await core.createNonFungibleItem( + item.name, + item.description, + item.imageUri, + item.tieredImageUris, + item.blueprint, + item.traits, + mutatorAddress, + // ^this is the only difference + item.costInWei, + item.feeRecipient +); +``` + +Now you've created an Assembly item with a custom mutator contract. + +--- + +Canonical page: https://docs.shape.network/building-on-shape/onchain-compatible +Markdown page: https://docs.shape.network/building-on-shape/onchain-compatible/index.md + +# Onchain Compatible Projects + +A collection of projects made with interoperability in mind + +- [Assembly](https://docs.shape.network/building-on-shape/onchain-compatible/assembly.md): A flexible ERC1155 system for creating and crafting composable items + +- [OTOM by Kjetil Golid](https://docs.shape.network/building-on-shape/onchain-compatible/otom.md): Create and experiment with particles called otoms + +- [Moveable Type by DEAFBEEF](https://moveabletype.deafbeef.com/) + +--- + +Canonical page: https://docs.shape.network/building-on-shape/onchain-compatible/otom +Markdown page: https://docs.shape.network/building-on-shape/onchain-compatible/otom.md + +# OTOM by Kjetil Golid + +Create and experiment with particles called otoms + +**Website**: [otom.xyz](https://otom.xyz/) + +**Repo:** [github.com/shape-network/otom-contracts](https://github.com/shape-network/otom-contracts) + +There are four main actions a chemist can take within the otoms universe. + +1. **Mine for Otoms** +2. **Annihilate said Otoms and receive Energy (ERC20)** +3. **Use Energy along with multiple Otoms to initiate a reaction** +4. **Analyze reactions and receive molecules (Chemists can analyze multiple unanalyzed reactions in a single transaction)** + +## Contracts + +### Shape Mainnet + +| Link | Description | Address | +| ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | +| [**Otoms**](https://shapescan.xyz/address/0x2f9810789aebBB6cdC6c0332948fF3B6D11121E3?tab=contract) | Main NFT contract for minting otoms | `0x2f9810789aebBB6cdC6c0332948fF3B6D11121E3` | +| [**OtomsDatabase**](https://shapescan.xyz/address/0x953761a771d6Ad9F888e41b3E7c9338a32b1A346?tab=contract) | DB used for storing information related to things like; tokenURI, Molecules, Who first discovered a Molecule, Universes | `0x953761a771d6Ad9F888e41b3E7c9338a32b1A346` | +| [**OtomsReactionOutputs**](https://shapescan.xyz/address/0x7d5A370F277e1847E4f768a88758237c6E3456eD?tab=contract) | Secondary NFT contract of unextracted Molecules | `0x7d5A370F277e1847E4f768a88758237c6E3456eD` | +| [**Energy**](https://shapescan.xyz/address/0x42276dF82BAb34c3CCcA9e5c058b6ff7EA4d07e3?tab=contract) | Fungible token used in reactions | `0x42276dF82BAb34c3CCcA9e5c058b6ff7EA4d07e3` | +| [**Reactor**](https://shapescan.xyz/address/0xB8874fCE9b702B191C306A21c7A4a101FB14a0fc?tab=contract) | Main reactor contract, used to initialize and analyze reactions | `0xB8874fCE9b702B191C306A21c7A4a101FB14a0fc` | +| [**Annihilator**](https://shapescan.xyz/address/0xca3088aedaAB138cAB3F0c135ceD77aF1a8b9063?tab=contract) | Used to convert NFT Otoms into fungible Energy | `0xca3088aedaAB138cAB3F0c135ceD77aF1a8b9063` | + +### Shape Sepolia + +| Link | Description | Address | +| ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | +| [**Otoms**](https://sepolia.shapescan.xyz/address/0xc709F59f1356230025d4fdFDCeD92341A14FF2F8?tab=contract) | Main NFT contract for minting otoms | `0xc709F59f1356230025d4fdFDCeD92341A14FF2F8` | +| [**OtomsDatabase**](https://sepolia.shapescan.xyz/address/0xC6E01938846D3d62EafD7FF485afeE416f6D8A40?tab=contract) | DB used for storing information related to things like; tokenURI, Molecules, Who first discovered a Molecule, Universes | `0xC6E01938846D3d62EafD7FF485afeE416f6D8A40` | +| [**OtomsReactionOutputs**](https://sepolia.shapescan.xyz/address/0x042125947523dD14dc64e3093a53DfCcdF07d979?tab=contract) | Secondary NFT contract of unextracted Molecules | `0x042125947523dD14dc64e3093a53DfCcdF07d979` | +| [**Energy**](https://sepolia.shapescan.xyz/address/0xe59D1719d3F8c149B009cB05a7679ce1dC074787?tab=contract) | Fungible token used in reactions | `0xe59D1719d3F8c149B009cB05a7679ce1dC074787` | +| [**Reactor**](https://sepolia.shapescan.xyz/address/0x62C87dd718E60c31993cf1a5EB32EE472C7eD144?tab=contract) | Main reactor contract, used to initialize and analyze reactions | `0x62C87dd718E60c31993cf1a5EB32EE472C7eD144` | +| [**Annihilator**](https://sepolia.shapescan.xyz/address/0xC998b6604aA50F71dd1b52884544c9107cf267E9?tab=contract) | Used to convert NFT Otoms into fungible Energy | `0xC998b6604aA50F71dd1b52884544c9107cf267E9` | + +## Functionality + +### Mining Otoms + +```solidity filename="Otoms.sol" +/** + * @dev Mines atoms based on the provided payloads. + * @param _payloads The payloads to mine atoms from. + * @return The token IDs of the mined atoms. + */ +function mine( + MiningPayload[] calldata payloads +) external returns (uint256[] memory); +``` + +### Mining Payload + +```solidity filename="IOtoms.sol" +struct MiningPayload { + Molecule minedMolecule; + bytes32 miningHash; + string tokenUri; + bytes32 universeHash; + uint256 expiry; + bytes signature; +} +``` + +### Reacting with Otoms + +```solidity filename="Reactor.sol" +/** + * @dev Initiates a reaction with the provided atom IDs and energy amount. + * @param atomIds The token IDs of the atoms to be used in the reaction. + * @param energyAmount The amount of energy to be used in the reaction. + * @return The token ID of the output of the reaction. + */ +function initiateReaction( + uint256[] memory atomIds, + uint256 energyAmount +) external returns (uint256); + +/** + * @dev Analyses the provided reaction results and returns + * the output of the reaction. + * @param reactionResults The results of the reaction. + * @param expiry The expiry time of the reaction. + * @param signature The signature of the reaction. + * @return The output of the reaction. + */ +function analyseReactions( + ReactionResult[] memory reactionResults, + uint256 expiry, + bytes memory signature +) external; +``` + +### Annihilating Otoms + +```solidity filename="Annihilator.sol" +/** + * @dev Annihilates the provided atom IDs. + * @param atomIds The token IDs of the atoms to be annihilated. + * @return The amount of energy produced by the annihilations. + */ +function annihilate( + uint256[] memory atomIds +) external nonReentrant returns (uint256) +``` + +## Structs + +```solidity filename="IOtomsDatabase.sol" +struct Molecule { + string id; + string name; + bytes32 universeHash; + uint256 activationEnergy; + uint256 radius; + Bond bond; + Atom[] givingAtoms; + Atom[] receivingAtoms; + uint256 electricalConductivity; + uint256 thermalConductivity; + uint256 toughness; + uint256 hardness; + uint256 ductility; +} + +struct Atom { + uint256 radius; + uint256 volume; + uint256 mass; + uint256 density; + uint256 electronegativity; + bool metallic; + string name; + string series; + uint256 periodicTableX; + uint256 periodicTableY; + AtomStructure structure; + Nucleus nucleus; +} +``` + +> We've included the three main structs used for mining otoms. Check out `IOtoms.sol` and +> `IOtomsDatabase.sol` for more info. + +## Data + +```solidity filename="OtomsDatabase.sol" +function getMoleculeByTokenId( + uint256 tokenId +) external view returns (Molecule memory); + +function getUniverseInformation( + bytes32 universeHash +) external view returns (UniverseInformation memory); + +function getMoleculesDiscovered( + bytes32 universeHash +) external view returns (Molecule[] memory); + +function getMoleculesDiscoveredPaginated( + bytes32 universeHash, + uint256 offset, + uint256 limit +) external view returns (Molecule[] memory molecules, uint256 total); + +function activeUniverses() external view returns (bytes32[] memory); +``` + +### Otoms + +```solidity filename="Otoms.sol" +function moleculeIsAtom( + Molecule memory _molecule +) external pure returns (bool); +``` + +### ReactionOutputs + +```solidity filename="OtomsReactionOutputs.sol" +function getReactionOutputData( + uint256 tokenId +) external view returns (ReactionOutputData memory); +``` + +## Encoding Utilities + +```solidity filename="IOtomsEncoder.sol" +function encodeMolecule( + Molecule memory _newMolecule +) external pure returns (bytes32); + +function encodeAtom( + Atom memory _newAtom +) external pure returns (bytes32); + +function encodeStructure( + AtomStructure memory _newStructure +) external pure returns (bytes32); + +function encodeNucleus( + Nucleus memory _newNucleus +) external pure returns (bytes32); + +function encodeUniverseInformation( + UniverseInformation memory _universeInformation +) external pure returns (bytes32); + +function getSeedUniverseMessageHash( + UniverseInformation memory _universeInformation, + uint256 expiry, + address sender +) external view returns (bytes32); + +function getMiningMessageHash( + Molecule memory _newAtom, + bytes32 _miningHash, + string memory _tokenUri, + bytes32 _universeHash, + uint256 expiry, + address sender +) external view returns (bytes32); + +function getMiningHash( + address _chemist, + bytes32 _universeHash, + uint256 _nonce +) external pure returns (bytes32); + +function getMultipleMiningHashes( + address _chemist, + bytes32 _universeHash, + uint256 _startingNonce, + uint256 _count +) external pure returns (bytes32[] memory); +``` + +--- + +Canonical page: https://docs.shape.network/building-on-shape/superchain-incentives +Markdown page: https://docs.shape.network/building-on-shape/superchain-incentives.md + +# Superchain incentives + +Learn about the Superchain incentives available to you as a Shape builder. + +Shape is a part of the [Superchain](https://app.optimism.io/superchain/). This means when you build on Shape, you become eligible for additional incentives, including: + +- [RetroPGF](https://app.optimism.io/retropgf): Rewarding your onchain impact + +- [Free contract deployment](https://docs.optimism.io/builders/app-developers/tutorials/deploy-for-free): Claim deployment rebates + +- [Gas sponsorship](https://console.optimism.io/): For your early users + +- [Launch support](https://console.optimism.io/): Amplified marketing through Superchain channels + +--- + +Canonical page: https://docs.shape.network/building-on-shape/transaction-fees +Markdown page: https://docs.shape.network/building-on-shape/transaction-fees.md + +# Transaction Fees + +Learn how network fees work on Shape, what changes them, where they go, and how to estimate them. + +## How do network fees on Shape work? + +Shape transaction fees are paid in **Ether** ("ETH"). + +Every Shape transaction involves two separate costs: + +- **L1 Fee**: the security fee for publishing transaction data to Ethereum. +- **L2 Fee**: the execution fee for running the transaction on Shape. + +Fees on Shape are much cheaper than what you'd pay for an equivalent transaction on Ethereum. The total cost can still vary based on Ethereum network activity, Shape network activity, transaction size, and any priority fee you choose to include. + +## L1 Fee + +The L1 Fee is paid to ensure your transaction's data is published to Ethereum, guaranteeing its availability for nodes to download and execute. This is crucial for maintaining the security properties of Shape. + +This fee varies depending on the current base fee on Ethereum and the amount of transaction data that needs to be published. If the timing of your transaction is flexible, submitting during periods of lower Ethereum gas can reduce the L1 Fee. + +L1 Fees are used to cover costs paid to Ethereum validators. + +## L2 Fee + +The L2 Fee is paid to execute your transaction on Shape. It has two components: a base fee and a priority fee. + +The **base fee** is the minimum required for your transaction to be included in a block. + +The **priority fee** is _optional_, and you decide how much to pay if you choose to include it. + +> Shape executes transactions in descending priority order - with higher priority fees taking +> precedence over lower priority fees - so the priority fee allows you to efficiently express +> the urgency of your transaction. + +The L2 Fee is also known as the **Sequencer Fee**. You can find more information about transaction fee calculation in the [OP Stack transaction fee documentation](https://docs.optimism.io/op-stack/transactions/fees). + +## Where do fees go? + +L1 Fees are used to cover the cost of publishing transaction data to Ethereum. + +**Shape directs 80% of ETH collected from L2 Fees back to the contracts that generated the activity**, ensuring the creators and platforms that thrive on the network share in its success. + +> Learn more about how this works in [Gasback](https://docs.shape.network/gasback.md). + +For the remaining 20%: + +- 15% goes to the Optimism Collective to fund public goods +- 5% goes to infrastructure and the Shape Foundation during the early stages of the network + +## Minimum Base Fee + +Shape uses a minimum L2 base fee to keep execution fees from falling to near-zero during quiet periods. This floor keeps blockspace predictably priced while preserving low transaction costs for apps, creators, and users. + +The minimum L2 base fee on Shape Mainnet is 10,000,000 wei (0.01 gwei). Shape may adjust this value as network usage evolves. At 0.01 gwei, a transaction using 200,000 L2 gas costs about $0.004 in L2 base fee when ETH is $2,000, before priority fees and the separate L1 data fee. + +### Why it matters + +- **Gasback alignment**: The minimum applies to L2 execution fees, which are the fees Shape shares with registered contracts through Gasback. +- **More reliable inclusion**: A nonzero floor helps the fee market respond when demand increases after quiet periods, reducing the chance that transactions wait while fees catch up. +- **Predictable app costs**: During normal demand, the L2 base fee should remain close to the floor. During congestion, it can rise with network usage. +- **Healthier blockspace pricing**: The floor discourages low-value spam while keeping normal Shape transactions inexpensive. + +## EIP-1559 fee behavior + +Shape uses the OP Stack's implementation of EIP-1559 for L2 execution fees. The L2 base fee adjusts in response to network demand, while the priority fee lets users express transaction urgency. + +When Shape is less busy, the L2 base fee can decrease. When blocks are more heavily used, the L2 base fee can increase. This is separate from the L1 Fee, which varies with Ethereum gas costs and the size of the transaction data being posted. + +OP Stack chains can tune fee behavior with parameters such as EIP-1559 elasticity, EIP-1559 denominator, gas limit, and minimum base fee. Shape-specific values are not listed here unless published or verified from the live network configuration. For the underlying OP Stack parameter model, see the [OP Stack fee parameter documentation](https://docs.optimism.io/chain-operators/guides/management/transaction-fees-101). + +## Querying the L1 fee + +The **GasPriceOracle** predeploy at `0x420000000000000000000000000000000000000F` lets you programmatically estimate the L1 Fee component before signing and submitting a transaction. + +| Method | Returns | +| ------------------------------------ | -------------------------------------------------------------------- | +| `getL1Fee(bytes)` | Exact L1 fee for a fully serialized transaction | +| `getL1FeeUpperBound(uint256 txSize)` | Upper-bound L1 fee estimate from approximate transaction byte length | +| `l1BaseFee()` | Current Ethereum L1 base fee as seen by Shape | +| `blobBaseFee()` | Current EIP-4844 blob base fee | +| `baseFeeScalar()` | Scalar applied to the L1 base fee component | +| `blobBaseFeeScalar()` | Scalar applied to the blob base fee component | + +Use `getL1FeeUpperBound` when you need a quick estimate before the transaction is fully constructed. Use `getL1Fee` with the complete serialized transaction for an exact estimate before signing. + +The GasPriceOracle address is also listed in [Contract Addresses](https://docs.shape.network/technical-details/contract-addresses.md). + +## Related resources + +- [Gasback](https://docs.shape.network/gasback.md) +- [Network Information](https://docs.shape.network/technical-details/network-information.md) +- [Contract Addresses](https://docs.shape.network/technical-details/contract-addresses.md) +- [OP Stack transaction fees](https://docs.optimism.io/op-stack/transactions/fees) + +--- + +Canonical page: https://docs.shape.network/gasback +Markdown page: https://docs.shape.network/gasback.md + +# Gasback + +Claim back 80% of the sequencer fees that users spend interacting with your contracts on Shape. + +## What is Gasback? + +Shape redistributes the **majority of sequencer fees spent by users to execute transactions** back to the contracts they interacted with, ensuring the creators and platforms that thrive on the network share in its success. This concept is called **Gasback**. + +### I own a contract on Shape. How much gas do I get back? + +All contract owners can claim back **80%** of the [L2 Fees](https://docs.shape.network/building-on-shape/transaction-fees.md) generated from users interacting with their contracts on Shape. + +### How do I take part in Gasback? + +**Gasback** is open to all smart contract owners on Shape. There are two ways to register your contracts: + +1. [Register via the Dashboard](https://docs.shape.network/tutorials/registering-contract-gasback/dashboard.md) +2. [Register programmatically](https://docs.shape.network/tutorials/registering-contract-gasback/programmatically.md) + +Once registered, you'll be able to claim your share of the sequencer fees generated by your contracts' activity. + +> Learn how to +> [register your contracts for Gasback here](https://docs.shape.network/tutorials/registering-contract-gasback/index.md) +> . + +--- + +Canonical page: https://docs.shape.network/ +Markdown page: https://docs.shape.network/index.md + +# Welcome + +Shape is the culture-first L2 built on top of Ethereum to power the new NFT economy. + +The network is an open space where everyone is free to create whatever they want - from fine art, to weird experiments, to whole new ideas - making it the place for culture to take root. + +## Why create on Shape? + +### Shape Culture. Get Gasback. + +As a creator on Shape, you can claim back 80% of sequencer fees users spend interacting with your contracts. This includes contracts you build yourself, contracts you acquire ownership of, and contracts that you deploy through other platforms. + +> Learn more about how this works in [Gasback](https://docs.shape.network/gasback.md). + +### The best of Ethereum. + +Shape is [EVM equivalent](https://docs.shape.network/building-on-shape/differences-ethereum-shape.md). This means your creator experience is the same as on Ethereum, just at a fraction of the cost. + +### Secure, stable & scalable. + +Shape inherits its security directly from Ethereum, keeping the networks intrinsically linked forever. + +Shape also prioritizes stability and scalability, utilizing [Alchemy](https://docs.shape.network/building-on-shape/alchemy-api.md) and [Optimism](https://www.optimism.io/) as key infrastructure partners to help achieve and maintain these states. + +### Shape the Superchain. + +Shape is a member of the [Superchain](https://docs.optimism.io/stack/explainer), which unlocks a range of further benefits for the entire ecosystem - including ongoing network-level cooperation, funding of public goods, and additional builder incentives on Shape. + +### Home for unique NFT experiments + +Shape is the proof that NFTs aren't just static images that people can buy and sell. + +- Deep dive into the rabbit hole of onchain chemistry with [OTOM](https://docs.shape.network/building-on-shape/onchain-compatible/otom.md) by Kjetil Golid. +- Wander in Leander Herzog's [Infinite Garden](https://infinite-garden.xyz/) +- Create & craft your own [Assembly Items](https://docs.shape.network/building-on-shape/onchain-compatible/assembly.md) +- And [many more...](https://shape.network/) + +--- + +Canonical page: https://docs.shape.network/quick-start/connect-to-shape +Markdown page: https://docs.shape.network/quick-start/connect-to-shape.md + +# Connect to Shape + +Shape Mainnet runs on chain ID `360`. Shape Sepolia (testnet) runs on chain ID `11011`. + +> The public RPCs are rate-limited. For production apps, use [Alchemy](https://www.alchemy.com/rpc/shape) (`https://shape-mainnet.g.alchemy.com/v2/YOUR_KEY`). Free tier available. + +The examples below use viem v2+ and wagmi v2+. Both export `shape` and `shapeSepolia` chain definitions. + +## viem + +```ts +import { createPublicClient, http } from 'viem'; +import { shape } from 'viem/chains'; + +const client = createPublicClient({ + chain: shape, + transport: http('https://mainnet.shape.network'), +}); +``` + +For Shape Sepolia, use `shapeSepolia` and the testnet RPC: + +```ts +import { createPublicClient, http } from 'viem'; +import { shapeSepolia } from 'viem/chains'; + +const client = createPublicClient({ + chain: shapeSepolia, + transport: http('https://sepolia.shape.network'), +}); +``` + +## wagmi + +```ts +import { http, createConfig } from 'wagmi'; +import { shape, shapeSepolia } from 'wagmi/chains'; + +export const config = createConfig({ + chains: [shape, shapeSepolia], + transports: { + [shape.id]: http('https://mainnet.shape.network'), + [shapeSepolia.id]: http('https://sepolia.shape.network'), + }, +}); +``` + +## Foundry + +Add a profile to `foundry.toml`: + +```toml +# foundry.toml +[profile.shape-sepolia] +eth_rpc_url = "https://sepolia.shape.network" +chain_id = 11011 +``` + +## ethers.js v6 + +```ts +import { JsonRpcProvider } from 'ethers'; + +const provider = new JsonRpcProvider('https://mainnet.shape.network'); +``` + +## Network Reference + +| | Mainnet | Sepolia | +| --- | --- | --- | +| Chain ID | `360` | `11011` | +| RPC | `https://mainnet.shape.network` | `https://sepolia.shape.network` | +| Explorer | [shapescan.xyz](https://shapescan.xyz/) | [sepolia.shapescan.xyz](https://sepolia.shapescan.xyz/) | +| Currency | ETH | ETH | + +See [Network Information](https://docs.shape.network/technical-details/network-information.md) for the full reference. + +--- + +Canonical page: https://docs.shape.network/quick-start/deploy-a-contract +Markdown page: https://docs.shape.network/quick-start/deploy-a-contract.md + +# Deploy a Contract on Shape + +Deploy a smart contract to Shape Sepolia and verify it on the block explorer using Foundry. + +## Prerequisites + +- [Foundry](https://book.getfoundry.sh/getting-started/installation) installed +- Shape Sepolia ETH from the [Alchemy Faucet](https://www.alchemy.com/faucets/shape-sepolia) +- A wallet private key funded with testnet ETH + +## 1. Create a Project + +```bash +forge init my-shape-contract +cd my-shape-contract +``` + +This scaffolds a project with a `Counter.sol` contract in `src/`. + +## 2. Deploy + +```bash +forge create src/Counter.sol:Counter \ + --rpc-url https://sepolia.shape.network \ + --private-key $PRIVATE_KEY +``` + +Save the `Deployed to` address from the output. + +## 3. Verify on the Explorer + +```bash +forge verify-contract src/Counter.sol:Counter \ + --verifier blockscout \ + --verifier-url https://sepolia.shapescan.xyz/api/ +``` + +Replace `` with the address from step 2. + +## 4. Deploy to Mainnet + +When ready for mainnet, use the mainnet RPC and verify against the mainnet explorer: + +```bash +forge create src/Counter.sol:Counter \ + --rpc-url https://mainnet.shape.network \ + --private-key $PRIVATE_KEY +``` + +```bash +forge verify-contract src/Counter.sol:Counter \ + --verifier blockscout \ + --verifier-url https://shapescan.xyz/api/ +``` + +## 5. Register for Gasback + +Gasback returns 80% of sequencer fees to contract owners. Register your deployed contract to start earning. + +See [Registering Your Contract for Gasback](https://docs.shape.network/tutorials/registering-contract-gasback/index.md) for the full walkthrough. + +## Next Steps + +- [Build a dApp](https://docs.shape.network/building-on-shape/builder-kit.md) with the Shape Builder Kit +- [Connect to Shape](https://docs.shape.network/quick-start/connect-to-shape.md) from your frontend +- [Gasback](https://docs.shape.network/gasback.md) (how fee reclamation works) + +--- + +Canonical page: https://docs.shape.network/quick-start +Markdown page: https://docs.shape.network/quick-start/index.md + +# Start Building on Shape + +Shape is an EVM-compatible L2 on the [Optimism Superchain](https://www.optimism.io/superchain). Gasback returns 80% of sequencer fees to contract owners. + +- [Connect to Shape](https://docs.shape.network/quick-start/connect-to-shape.md): Configure viem, wagmi, Foundry, and ethers.js for Shape + +- [Deploy a Contract](https://docs.shape.network/quick-start/deploy-a-contract.md): Deploy and verify a smart contract with Foundry + +- [Build a dApp](https://docs.shape.network/building-on-shape/builder-kit.md): Scaffold a full-stack dApp with the Shape Builder Kit + +## Resources + +- [Shape Sepolia Faucet](https://www.alchemy.com/faucets/shape-sepolia) (testnet ETH) +- [Alchemy Dashboard](https://www.alchemy.com/dashboard) (API keys and enhanced RPCs) +- [Network Information](https://docs.shape.network/technical-details/network-information.md) (chain IDs, RPCs, explorers) +- [Shape Discord](https://discord.com/invite/shape-l2) (builder support) + +--- + +Canonical page: https://docs.shape.network/technical-details/contract-addresses +Markdown page: https://docs.shape.network/technical-details/contract-addresses.md + +# Contract Addresses + +## Mainnet + +### Ethereum (L1) + +| Name | Address | +| ----------------------------------- | -------------------------------------------- | +| `L2OutputOracleProxy` | `0x6Ef8c69CfE4635d866e3E02732068022c06e724D` | +| `OptimismPortalProxy` | `0xEB06fFa16011B5628BaB98E29776361c83741dd3` | +| `L1StandardBridgeProxy` | `0x62Edd5f4930Ea92dCa3fB81689bDD9b9d076b57B` | +| `AddressManager` | `0xcee78437aE9e15cee9c78E63757E0153c0FD7479` | +| `AnchorStateRegistryProxy` | `0x02987E7294379B9DDa99d593b0C94c68266222D1` | +| `DelayedWETHProxy` | `0xfEc7865DAc5139886585F03146Ff61D9b31c2d57` | +| `DisputeGameFactoryProxy` | `0x575Aecd84083f93877291901907698F7db0Bd8b0` | +| `L1CrossDomainMessengerProxy` | `0x2b18602877181C3cB72C687E2A771E123A3788E3` | +| `L1ERC721BridgeProxy` | `0xe9d3E49b0636016c5fE9eaA2347948D0bA9f15Af` | +| `Mips` | `0xD30c2Cd3cd6112E61FDfb03e4b232564d7e5C91f` | +| `OptimismMintableERC20FactoryProxy` | `0x319322906beAdf69dF5d4607169c63D692B1aDC1` | +| `PreimageOracle` | `0xDF6a16a71d0BC7a1Bbe8FffB33700eC3d9448A5B` | +| `ProtocolVersionsProxy` | `0xa77995E10b0A833CDD4fA414C26E869F7aa32DDd` | +| `ProxyAdmin` | `0x11B190Ae661c6d6884dFEE48E215691E0DdB842e` | +| `SuperchainConfigProxy` | `0x125664BEf08177ca43f6f301E63118b1e4cCDe09` | +| `SystemConfigProxy` | `0xfF11e41D5C4F522E423Ff6C064Ff8D55AF8f7355` | +| `SystemOwnerSafe` | `0xacAF178b5048CB56712dc59E95fBA72F7990A005` | + +### Shape Mainnet (L2) + +| Name | Address | +| ------------------------------- | -------------------------------------------- | +| `Gasback` | `0xf5e602c87d675E978F097503aedE4A766285a08B` | +| `RecipientValidator` | `0x12e50C2B9Dd2741bd07Df4E2E544f3412fd584cE` | +| `WETH9` | `0x4200000000000000000000000000000000000006` | +| `multicall3` | `0xca11bde05977b3631167028862be2a173976ca11` | +| `ImmutableCreate2Factory` | `0x0000000000ffe8b47b3e2130213b802212439497` | +| `Create2Deployer` | `0x13b0D85CcB8bf860b6b79AF3029fCA081AE9beF2` | +| `DeterministicDeploymentProxy` | `0x4e59b44847b379578588920ca78fbf26c0b4956c` | +| `Seaport 1.6` | `0x0000000000000068F116a894984e2DB1123eB395` | +| `ConduitController` | `0x00000000F9490004C11Cef243f5400493c00Ad63` | +| `GitcoinPassportDecoder` | `0x2443D22Db6d25D141A1138D80724e3Eee54FD4C2` | +| `GitcoinResolver` | `0x90E2C4472Df225e8D31f44725B75FFaA244d5D33` | +| `GitcoinVerifier` | `0x16db23c4b99bbC9A6Bf55dF7a787C9AEFD261185` | +| `GitcoinAttester` | `0xCc90105D4A2aa067ee768120AdA19886021dF422` | +| `L2CrossDomainMessenger` | `0x4200000000000000000000000000000000000007` | +| `L2StandardBridge` | `0x4200000000000000000000000000000000000010` | +| `SequencerFeeVault` | `0x4200000000000000000000000000000000000011` | +| `OptimismMintableERC20Factory` | `0x4200000000000000000000000000000000000012` | +| `GasPriceOracle` | `0x420000000000000000000000000000000000000F` | +| `GovernanceToken` | `0x4200000000000000000000000000000000000042` | +| `L1Block` | `0x4200000000000000000000000000000000000015` | +| `L2ToL1MessagePasser` | `0x4200000000000000000000000000000000000016` | +| `L2ERC721Bridge` | `0x4200000000000000000000000000000000000014` | +| `OptimismMintableERC721Factory` | `0x4200000000000000000000000000000000000017` | +| `ProxyAdmin` | `0x4200000000000000000000000000000000000018` | +| `BaseFeeVault` | `0x4200000000000000000000000000000000000019` | +| `L1FeeVault` | `0x420000000000000000000000000000000000001a` | +| `SchemaRegistry` | `0x4200000000000000000000000000000000000020` | +| `EAS` | `0x4200000000000000000000000000000000000021` | +| `BeaconBlockRoot` | `0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02` | +| `LegacyMessagePasser` | `0x4200000000000000000000000000000000000000` | +| `DeployerWhitelist` | `0x4200000000000000000000000000000000000002` | + +## Testnet (Sepolia) + +### Sepolia (L1) + +| Name | Address | +| ----------------------------------- | -------------------------------------------- | +| `AddressManager` | `0x42721d8512d62aA26B2Cfa1AE18bEEd5a9Ab1337` | +| `AnchorStateRegistryProxy` | `0x41ea3c370896632121Cdde1b94a4eCcf23DA4532` | +| `DelayedWETHProxy` | `0x7cc9cA91BA4f92F4C967E93a1AAd97beB18d3877` | +| `DisputeGameFactoryProxy` | `0x93eaa7A1E7d7af7eD9D612F9957988C8631c33e8` | +| `L1CrossDomainMessengerProxy` | `0xF9F730650e1AB4D23E2ac983934271ca7c5EF293` | +| `L1ERC721BridgeProxy` | `0x19f02c55254d2644eF94f30C74A932D64e1D4F86` | +| `L1StandardBridgeProxy` | `0x341ab1DAfdfB73b3D6D075ef10b29e3cACB2A653` | +| `L2OutputOracleProxy` | `0x532dDCed3440Eab81c529Ac8b0d7e429B5C05c52` | +| `Mips` | `0xaCf1Ed7357E41f652407ae6cFE1024705c758C38` | +| `OptimismMintableERC20FactoryProxy` | `0x46085E2e648488e49FBeaF6544b8e9Dc96df8BDd` | +| `OptimismPortalProxy` | `0xfF8Ca2B4d8122E41441F7ccDCf61b8692198Bd1E` | +| `PreimageOracle` | `0x8F3B1c59eD4439ebF564604aA4B93130DA4CD1D5` | +| `ProtocolVersionsProxy` | `0x8B901e6F6a49C950088d11C81166BCE2E3171C03` | +| `ProxyAdmin` | `0xd60a706Bf6108F090d055787B9B353FA7EEE1355` | +| `SuperchainConfigProxy` | `0xe5b3692266FF4Ab8A96A9C7Da6EeEe532CCc7916` | +| `SystemConfigProxy` | `0xa1aC91ED91EbE40E00d61E233c8026318b4da5fb` | +| `SystemOwnerSafe` | `0x4c4526C8C55c4e1a6F2aaf91e37f07c97786e0f5` | + +### Shape Sepolia (L2) + +| Name | Address | +| ------------------------------- | -------------------------------------------- | +| `Gasback` | `0xdF329d59bC797907703F7c198dDA2d770fC45034` | +| `WETH9` | `0x4200000000000000000000000000000000000006` | +| `L2CrossDomainMessenger` | `0x4200000000000000000000000000000000000007` | +| `L2StandardBridge` | `0x4200000000000000000000000000000000000010` | +| `SequencerFeeVault` | `0x4200000000000000000000000000000000000011` | +| `OptimismMintableERC20Factory` | `0x4200000000000000000000000000000000000012` | +| `GasPriceOracle` | `0x420000000000000000000000000000000000000F` | +| `GovernanceToken` | `0x4200000000000000000000000000000000000042` | +| `L1Block` | `0x4200000000000000000000000000000000000015` | +| `L2ToL1MessagePasser` | `0x4200000000000000000000000000000000000016` | +| `L2ERC721Bridge` | `0x4200000000000000000000000000000000000014` | +| `OptimismMintableERC721Factory` | `0x4200000000000000000000000000000000000017` | +| `ProxyAdmin` | `0x4200000000000000000000000000000000000018` | +| `BaseFeeVault` | `0x4200000000000000000000000000000000000019` | +| `L1FeeVault` | `0x420000000000000000000000000000000000001a` | +| `SchemaRegistry` | `0x4200000000000000000000000000000000000020` | +| `EAS` | `0x4200000000000000000000000000000000000021` | +| `BeaconBlockRoot` | `0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02` | +| `LegacyMessagePasser` | `0x4200000000000000000000000000000000000000` | +| `DeployerWhitelist` | `0x4200000000000000000000000000000000000002` | +| `LegacyERC20ETH` | `0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000` | + +--- + +Canonical page: https://docs.shape.network/technical-details/network-information +Markdown page: https://docs.shape.network/technical-details/network-information.md + +# Network Information + +## Mainnet + +| Network Name | Shape | +| --------------- | ----------------------------------------------- | +| Chain ID | `360` | +| Currency Symbol | `ETH` | +| RPC Endpoint | `https://mainnet.shape.network` | +| Block Explorer | [https://shapescan.xyz](https://shapescan.xyz/) | + +## Testnet + +| Network Name | Shape Sepolia | +| --------------- | --------------------------------------------------------------------------------- | +| Chain ID | `11011` | +| Currency Symbol | `ETH` | +| RPC Endpoint | `https://sepolia.shape.network` | +| Block Explorer | [https://sepolia.shapescan.xyz](https://sepolia.shapescan.xyz/) | + +> For production systems or high throughput testing, we recommend using a node from +> [Alchemy](https://www.alchemy.com/supernode), one of our node providers. + +--- + +Canonical page: https://docs.shape.network/technical-details/run-a-node +Markdown page: https://docs.shape.network/technical-details/run-a-node.md + +# Run a Node + +Shape is an [OP Stack](https://docs.optimism.io/stack/getting-started) rollup. Running a Shape node requires two clients that talk over the [Engine API](https://github.com/ethereum/execution-apis/blob/main/src/engine/common.md) and authenticate with a shared JWT secret: + +- **Execution client (op-geth)** runs the EVM and stores chain state. +- **Consensus client (op-node)** derives the L2 chain from L1 data and feeds blocks to the execution client. + +## Prerequisites + +### Hardware requirements + +| Component | Full node | Archive node | +| --------- | --------- | ------------ | +| CPU | Reasonably modern, multi-core | Same | +| RAM | 16 GB minimum | 16 GB minimum | +| Storage | 700 GB+ SSD (grows ~100 GB / 6 months) | 14 TB+ NVMe SSD (grows ~3.5 TB / 6 months) | + +Archive nodes should use NVMe SSDs. op-geth's `--datadir.ancient` flag can offload older data to a cheaper HDD. + +### Software dependencies + +- [Go](https://go.dev/dl/) 1.21+ +- [just](https://github.com/casey/just#installation) (op-node build tool) +- Make (op-geth build tool) +- Git +- An **L1 Ethereum RPC endpoint** (e.g., [Alchemy](https://www.alchemy.com/), Infura, or your own node) +- An **L1 Beacon (consensus) endpoint** (required since Ecotone for blob retrieval) + +### Network ports + +Expose the following ports for P2P sync: + +| Port | Protocol | Purpose | +| ----- | -------- | ------- | +| 30303 | TCP + UDP | op-geth peer discovery and block propagation | +| 9222 | TCP + UDP | op-node peer discovery | + +## Choose paths + +The commands below assume these shell variables: + +```bash +export OP_GETH_DIR=$HOME/op-geth +export OPTIMISM_DIR=$HOME/optimism +export OP_NODE_DIR=$OPTIMISM_DIR/op-node +export DATADIR=$HOME/.shape +export CONFIG_DIR=$HOME/.shape-config + +mkdir -p "$DATADIR/geth" "$CONFIG_DIR" +``` + +Adjust them if you want different locations. + +## Build the clients + +Build both binaries first. You need the same `op-geth` and `op-node` binaries whether you sync from a snapshot or from genesis. + +### 1. Build op-geth + +```bash +git clone https://github.com/ethereum-optimism/op-geth.git "$OP_GETH_DIR" +cd "$OP_GETH_DIR" +git checkout +make geth +``` + +Check [op-geth releases](https://github.com/ethereum-optimism/op-geth/releases) for the required release branch. + +### 2. Build op-node + +```bash +git clone https://github.com/ethereum-optimism/optimism.git "$OPTIMISM_DIR" +cd "$OPTIMISM_DIR" +git checkout +cd "$OP_NODE_DIR" +just +``` + +Check [optimism releases](https://github.com/ethereum-optimism/optimism/releases) for the required release branch. + +## Option A: Sync from snapshot (fastest) + +[Alchemy snapshots](https://www.alchemy.com/snapshots/shape) let you skip the full sync by downloading a compressed chaindata archive and starting near the chain tip. + +### 1. Download the snapshot + +Visit [alchemy.com/snapshots/shape](https://www.alchemy.com/snapshots/shape) and download the latest `.tar.lz4` snapshot for your network (mainnet or Sepolia). + +### 2. Install lz4 and decompress + +```bash +# macOS +brew install lz4 + +# Ubuntu/Debian +sudo apt-get install -y lz4 +``` + +If you have existing data, stop your node and clear the old chaindata first: + +```bash +rm -rf "$DATADIR/geth/chaindata" +rm -rf "$DATADIR/geth/lightchaindata" +``` + +Decompress the snapshot: + +```bash +lz4 -c -d .tar.lz4 | tar -x -C "$DATADIR/geth/" +``` + +### 3. Download the rollup config + +Save the `rollup.json` for your network to `$CONFIG_DIR/rollup.json`: + +**Shape Mainnet:** +- [rollup.json](https://arweave.net/Lh9vjNsHKHOKzGwWwlvVz2tsxcL_h5Wc-Ga0udO3Xm0) + +**Shape Sepolia:** +- [rollup.json](https://arweave.net/gSb3hOzLaBIBy-AyWA2O2_03sfXJ-IwPqmV6Mhstmj8) + +### 4. Continue to [Configure and run](#configure-and-run) + +Your node should be in sync within minutes of starting. + +## Option B: Sync from genesis + +### 1. Download genesis and rollup configs + +Save the files for your network to `$CONFIG_DIR/rollup.json` and `$CONFIG_DIR/genesis.json`: + +**Shape Mainnet:** +- [rollup.json](https://arweave.net/Lh9vjNsHKHOKzGwWwlvVz2tsxcL_h5Wc-Ga0udO3Xm0) +- [genesis.json](https://arweave.net/LrSrsEJsUtSWNAzkpKqkwE9RG3JZP1SmlOQNlTu8Nxk) + +**Shape Sepolia:** +- [rollup.json](https://arweave.net/gSb3hOzLaBIBy-AyWA2O2_03sfXJ-IwPqmV6Mhstmj8) +- [genesis.json](https://arweave.net/nw6opum2ALT9T39TSAAK_Wq0Z75aZJWd6J2RmiWHm_s) + +### 2. Initialize the datadir + +```bash +"$OP_GETH_DIR/build/bin/geth" init --datadir="$DATADIR" "$CONFIG_DIR/genesis.json" +``` + +### 3. Continue to [Configure and run](#configure-and-run) + +## Configure and run + +### 1. Generate a JWT secret + +op-geth and op-node authenticate over the Engine API with a shared secret. Save it to `$CONFIG_DIR/jwt.txt`: + +```bash +openssl rand -hex 32 > "$CONFIG_DIR/jwt.txt" +``` + +### 2. Start op-geth + +**Shape Mainnet:** + +```bash +"$OP_GETH_DIR/build/bin/geth" \ + --datadir="$DATADIR" \ + --http \ + --http.port=8545 \ + --http.addr=0.0.0.0 \ + --http.api=eth,net,web3 \ + --ws \ + --ws.port=8546 \ + --ws.addr=0.0.0.0 \ + --ws.api=eth,net,web3 \ + --authrpc.addr=localhost \ + --authrpc.port=8551 \ + --authrpc.jwtsecret="$CONFIG_DIR/jwt.txt" \ + --authrpc.vhosts=* \ + --verbosity=3 \ + --rollup.sequencerhttp=https://mainnet.shape.network \ + --rollup.disabletxpoolgossip=true \ + --syncmode=snap +``` + +**Shape Sepolia:** Replace `--rollup.sequencerhttp` with `https://sepolia.shape.network`. + +**For archive mode:** Add `--gcmode=archive` and change `--syncmode=full`. + +### 3. Start op-node + +Set your L1 endpoints: + +```bash +export L1_RPC_URL= # e.g., https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY +export L1_RPC_KIND= # alchemy, quicknode, infura, basic, etc. +export L1_BEACON_URL= # e.g., https://ethereum-beacon-api.publicnode.com +``` + +**Shape Mainnet:** + +```bash +"$OP_NODE_DIR/bin/op-node" \ + --l1=$L1_RPC_URL \ + --l1.rpckind=$L1_RPC_KIND \ + --l1.beacon=$L1_BEACON_URL \ + --l2=ws://localhost:8551 \ + --l2.jwt-secret="$CONFIG_DIR/jwt.txt" \ + --rollup.config="$CONFIG_DIR/rollup.json" \ + --l2.enginekind=geth \ + --syncmode=execution-layer \ + --override.granite=1727370000 \ + --override.holocene=1739880000 \ + --override.isthmus=1774530000 \ + --p2p.listen.tcp=9222 \ + --p2p.listen.udp=9222 \ + --rpc.addr=127.0.0.1 \ + --rpc.port=9545 \ + --metrics.enabled \ + --metrics.port=7300 +``` + +**Shape Sepolia:** + +```bash +"$OP_NODE_DIR/bin/op-node" \ + --l1=$L1_RPC_URL \ + --l1.rpckind=$L1_RPC_KIND \ + --l1.beacon=$L1_BEACON_URL \ + --l2=ws://localhost:8551 \ + --l2.jwt-secret="$CONFIG_DIR/jwt.txt" \ + --rollup.config="$CONFIG_DIR/rollup.json" \ + --l2.enginekind=geth \ + --syncmode=execution-layer \ + --override.ecotone=0 \ + --override.fjord=1721732400 \ + --override.granite=1727197200 \ + --override.holocene=1739880000 \ + --override.isthmus=1763650800 \ + --p2p.listen.tcp=9222 \ + --p2p.listen.udp=9222 \ + --rpc.addr=127.0.0.1 \ + --rpc.port=9545 \ + --metrics.enabled \ + --metrics.port=7300 +``` + +For Sepolia, use a Sepolia L1 RPC for `L1_RPC_URL`. + +> **Do not expose the op-node RPC publicly.** The `--rpc.addr` should be `127.0.0.1` (localhost) unless you have a specific reason and a firewall in place. + +### Sync modes + +| Mode | op-node flag | op-geth flag | Use case | +| ---- | ------------ | ------------ | -------- | +| Snap sync | `--syncmode=execution-layer` | `--syncmode=snap` (default) | Downloads state at chain tip via P2P. Fastest for full nodes. | +| Full sync | `--syncmode=execution-layer` | `--syncmode=full` | Executes every block. Required for archive nodes. | + +## Verifying your node + +After startup, look for: + +1. op-geth logs showing `Syncing beacon headers` as it downloads headers from peers. +2. op-geth logs showing state download progress (percentage and data volumes). +3. Once caught up, both clients log new blocks every 2 seconds. + +Check sync status via JSON-RPC: + +```bash +curl -s -X POST http://localhost:8545 \ + -H "Content-Type: application/json" \ + -d '{"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}' +``` + +Returns `false` when fully synced. + +## Monitoring + +op-node exposes Prometheus metrics at `http://localhost:7300/metrics` when started with `--metrics.enabled`. + +| Metric | What it tells you | +| ------ | ----------------- | +| `op_node_default_refs_number` | Current L1/L2 block heights. If these stall, sync has stopped. | +| `op_node_default_p2p_peer_count` | Connected peers. Zero means the node falls back to slow L1-only derivation. | +| `op_node_default_rpc_client_request_duration_seconds` | RPC call latency. Spikes usually point to your L1 provider. | + +## Blob archiver + +Since Ecotone, batch data is posted as [EIP-4844 blobs](https://eips.ethereum.org/EIPS/eip-4844). Standard beacon nodes prune blobs after ~18 days. + +You need a blob archiver if your node may go offline for 18+ days or you are syncing from genesis without a recent snapshot. + +Options: +1. Run an L1 beacon node with pruning disabled (e.g., Lighthouse with `--prune-blobs=false`) +2. Use a third-party beacon endpoint that retains blobs beyond the 18-day window + +Point op-node at a fallback endpoint that has the old blobs: + +```bash +--l1.beacon-fallbacks= +``` + +## Troubleshooting + +### Node stalling or can't find peers + +Pass the bootnode enodes directly to op-node with `--p2p.bootnodes`: + +**Shape Mainnet:** + +``` +--p2p.bootnodes=enode://ae31be7c6596f4bc3657f90b65a1569c7b0db10c976649f06fe5cfb26139064d78d22b41aede293aa7358fc336d086051ac7fce78f063dce89e1da19c7b88aee@34.228.226.23:0?discport=30301,enode://0bea78f02c9bee58326b3a612dae63dc5a0193fb3dfc9be687c9757d25606405ef9f87810157598fce35688bdb5b3834dc6283afab6dc5774abbd6c5a7b17cea@3.85.27.162:0?discport=30301 +``` + +**Shape Sepolia:** + +``` +--p2p.bootnodes=enode://34fc07c447b843f3915f72cae27daeda7f2f8c3ea4b9132aed188387d3208d1d5cd7eeea58d30d038c14f985a5b108ad6b2172815ed8b757c9de9f609741b2a6@34.228.9.78:0?discport=30301,enode://61841b7682f808f5ce8222f15d7de7f118a2c2c3e342fe42ea41e987ae22fb90e49ef2b5f394897e791c33c6fc59d7ad064851ee653badb2d6ece7a94040944b@54.91.75.177:0?discport=30301 +``` + +### 401 Unauthorized: signature invalid + +The JWT secret doesn't match between op-node and op-geth. Ensure both point to the same `jwt.txt` file. + +### 403 Forbidden: invalid host specified + +Add `--authrpc.vhosts=*` to op-geth, or set it to the specific hostname op-node uses to connect. + +### P2P directory permission denied + +op-node can't write to its P2P discovery directory. Either grant write access or redirect with: + +```bash +--p2p.discovery.path=/path/with/write/access +--p2p.peerstore.path=/path/with/write/access +``` + +### Wrong chain / mismatched genesis + +Verify that: +- `L1_RPC_URL` points to the correct L1 network (Ethereum mainnet for Shape, Sepolia for Shape Sepolia) +- `rollup.json` matches the network you intend to run +- op-geth was initialized with the correct `genesis.json` + +### Unclean shutdown detected + +op-geth prints this warning on startup after a crash or kill. It usually recovers on its own. If the database is unrecoverable, re-initialize from genesis or restore from a [snapshot](https://www.alchemy.com/snapshots/shape). + +## References + +- [Optimism node operator docs](https://docs.optimism.io/node-operators/overview) +- [Run a node from source (OP docs)](https://docs.optimism.io/node-operators/tutorials/run-node-from-source) +- [Build from source (OP docs)](https://docs.optimism.io/node-operators/tutorials/node-from-source) +- [Alchemy Shape snapshots](https://www.alchemy.com/snapshots/shape) +- [op-node configuration reference](https://docs.optimism.io/node-operators/reference/op-node-config) +- [op-geth configuration reference](https://docs.optimism.io/node-operators/reference/op-geth-config) +- [OP Stack troubleshooting](https://docs.optimism.io/node-operators/guides/troubleshooting) + +--- + +Canonical page: https://docs.shape.network/the-stack +Markdown page: https://docs.shape.network/the-stack.md + +# The Stack + +The **Stack** is a dynamic NFT that serves as a living record of your achievements and contributions across the Shape ecosystem. + +By engaging with projects on Shape, you earn medals that showcase your journey and build your reputation in the community. + +## Getting Started + +### 1. Mint Your Stack + +Start by minting your Stack at [stack.shape.network](https://stack.shape.network/) + +### 2. Engage with Projects + +Engage with different projects in various ways on Shape. Interactions include: + +- Collecting NFTs +- Minting new creations +- Bidding on artwork auctions +- Exploring apps, games, and experiments + +### 3. Earn Medals + +As you engage, you'll earn medals issued by the community projects you interact with. There are 4 types of medals: + +- **Bronze (🟤):** Awarded for initial interactions +- **Silver (⚪):** Awarded for deeper involvement +- **Gold (🟡):** Awarded for significant contributions +- **Special (⚫):** Awarded for exceptional achievements + +### 4. Claim Medals + +Once a medal has been earned, you can claim it via your Stack dashboard. + +Your Stack NFT will dynamically update as you claim medals. + +### 5. Climb Ranks + +As you earn medals, you climb ranks in the [Leaderboard](https://stack.shape.network/leaderboard). + +Higher ranks may grant access to exclusive opportunities, such as allowlist spots for future Stack projects. + +## The Stack Keeps Stacking + +New projects and medals are added regularly. + +Stay up to date by following [@shape](https://twitter.com/shape) for the latest news. + +> Do you have a project you'd like to make part of the Stack? +> +> Reach out on [Twitter/X](https://x.com/shape) or in +> [Discord](https://discord.com/invite/shape-l2) to let us know. + +--- + +Canonical page: https://docs.shape.network/tools/account-abstraction +Markdown page: https://docs.shape.network/tools/account-abstraction.md + +# Account Abstraction + +On Shape, combine AA with [Gasback](https://docs.shape.network/gasback.md) to subsidize your users and recoup 80% of sequencer fees. + +| Tool | Use case | +| --- | --- | +| Alchemy Bundler + Gas Manager | Full AA stack: bundled UserOps, gas sponsorship | +| Alchemy Embedded Accounts | Email/social login, no seed phrase | +| Alchemy Smart Accounts | Programmable accounts with custom validation | +| Crossmint NFT Checkout | Credit card NFT purchases, no wallet needed | +| Crossmint WaaS | Invisible wallets embedded in your app | + +See [Alchemy's AA overview](https://www.alchemy.com/learn/account-abstraction) for background. + +- [Alchemy Bundler](https://www.alchemy.com/account-abstraction-infrastructure): A highly reliable ERC-4337 bundler + +- [Alchemy Gas Manager](https://www.alchemy.com/gas-manager): Sponsor gas for your users + +- [Alchemy Embedded Accounts](https://www.alchemy.com/embedded-accounts): Bring users onchain in seconds. No seed phrase, no gas + +- [Alchemy Smart Accounts](https://www.alchemy.com/account-contracts): Fully abstract the user experience with secure & extensible smart accounts + +- [Crossmint NFT Checkout](https://www.crossmint.com/products/nft-checkout): Sell NFTs via credit cards and cross-chain payments + +- [Crossmint Wallet-as-a-Service](https://www.crossmint.com/): Invisible wallets, embedded in your app + +--- + +Canonical page: https://docs.shape.network/tools/bridges +Markdown page: https://docs.shape.network/tools/bridges.md + +# Bridges + +Bridge ETH and tokens between Ethereum and Shape. + +## Mainnet + +- [Relay](https://relay.link/shape): Instant bridging & cross-chain execution + +- [Superbridge](https://superbridge.app/shape-mainnet): Fast and secure native bridging + +- [Alchemy](https://shape-mainnet.bridge.alchemy.com/) + +## Sepolia + +- [Relay (Sepolia)](https://testnets.relay.link/bridge/shape-sepolia) + +- [Superbridge (Sepolia)](https://superbridge.app/shape-testnet) + +--- + +Canonical page: https://docs.shape.network/tools/data-indexers +Markdown page: https://docs.shape.network/tools/data-indexers.md + +# Data Indexers + +| Service | Best for | +| --- | --- | +| Alchemy NFT/Token/Transfers APIs | General-purpose queries, NFT metadata, token balances | +| Alchemy Subgraphs | Custom GraphQL queries on indexed contract events | +| Alchemy Webhooks | Real-time notifications (transfers, mints, contract events) | +| Goldsky | Streaming onchain data to your database (Postgres, Kafka) | +| Reservoir | NFT marketplace data (listings, sales, collection stats) | +| SimpleHash | Cross-chain NFT and token metadata aggregation | + +Fetch NFTs owned by an address using the Alchemy NFT API: + +```ts +const res = await fetch( + `https://shape-mainnet.g.alchemy.com/nft/v3/${ALCHEMY_KEY}/getNFTsForOwner?owner=${address}` +); +const { ownedNfts } = await res.json(); +``` + +- [Alchemy NFT API](https://www.alchemy.com/nft-api): An API to launch, verify, analyze, trade & display NFTs + +- [Alchemy Subgraphs](https://www.alchemy.com/subgraphs): A fast & reliable GraphQL API + +- [Alchemy Token API](https://www.alchemy.com/token-api): Complete token data, no token list required + +- [Alchemy Transfers API](https://www.alchemy.com/transfers-api): Retrieve all historical transaction activity, including internal transfers + +- [Alchemy Webhooks](https://www.alchemy.com/webhooks): Realtime notifications for your users + +- [Goldsky](https://goldsky.com/): Livestream onchain data to your database + +- [Reservoir](https://reservoir.tools/): From market data to metadata, Reservoir APIs provide all-in-one endpoints + +- [SimpleHash](https://simplehash.com/): Instant access to Token & NFT market prices, metadata and media + +--- + +Canonical page: https://docs.shape.network/tools/explorers +Markdown page: https://docs.shape.network/tools/explorers.md + +# Explorers + +| Explorer | Focus | +| --- | --- | +| Shapescan | Block explorer: transactions, contracts, verification | +| Shapescan Sepolia | Testnet block explorer | +| Deca | NFT explorer: collections, metadata, floor prices | +| Zapper | Portfolio and activity feed in a human-readable format | + +Verify your contracts on Shapescan to make them readable. See [Deploy a Contract](https://docs.shape.network/quick-start/deploy-a-contract.md) for verification steps. + +- [Shape Mainnet Explorer](https://shapescan.xyz/) + +- [Shape Sepolia Testnet Explorer](https://explorer-sepolia.shape.network/) + +- [Deca](https://deca.art/): See all NFTs on Shape in one place + +- [Zapper](https://zapper.xyz/): See what's happening onchain in a human readable way + +--- + +Canonical page: https://docs.shape.network/tools/faucets +Markdown page: https://docs.shape.network/tools/faucets.md + +# Faucets + +Get free testnet ETH on Shape Sepolia for development. + +1. Go to the Alchemy or Optimism faucet +2. Sign in with an account (free tier works) +3. Enter your wallet address +4. Receive testnet ETH (usually within seconds) + +- [Alchemy Faucet](https://www.alchemy.com/faucets/shape-sepolia) + +- [Optimism Faucet](https://console.optimism.io/faucet) + +> You can also [bridge Sepolia ETH](https://docs.shape.network/tools/bridges.md) to get started. + +--- + +Canonical page: https://docs.shape.network/tools/node-providers +Markdown page: https://docs.shape.network/tools/node-providers.md + +# Node Providers + +| Provider | Endpoint | Notes | +| --- | --- | --- | +| Public RPC | `https://mainnet.shape.network` | Rate-limited, not for production | +| Alchemy | `https://shape-mainnet.g.alchemy.com/v2/YOUR_KEY` | Higher limits, WebSocket, enhanced APIs | + +Sepolia: `https://sepolia.shape.network` (public) or `https://shape-sepolia.g.alchemy.com/v2/YOUR_KEY` (Alchemy). + +WebSocket: `wss://shape-mainnet.g.alchemy.com/v2/YOUR_KEY` + +The public RPC is rate-limited and not suitable for production. Use [Alchemy](https://www.alchemy.com/rpc/shape) (free tier available). + +- [Alchemy Supernode](https://www.alchemy.com/rpc/shape): A highly reliable RPC + +--- + +Canonical page: https://docs.shape.network/tools/oracles/gelato-vrf +Markdown page: https://docs.shape.network/tools/oracles/gelato-vrf.md + +# Gelato VRF + +- **Mechanism**: Uses [Drand](https://drand.love/), a decentralized source for random numbers. +- **Benefits**: Provides genuine, verifiable random values for blockchain applications. + +## Applications of Gelato VRF + +- **Gaming and Gambling**: For fair outcomes in online games and decentralized gambling. +- **Decentralized Finance (DeFi)**: Random selections for lotteries in DeFi protocols. +- **NFT Generation**: Random trait generation for unique digital assets. +- **Protocol Decision Making**: Randomized selections for validators or jurors. + +## Steps to Set Up Gelato VRF + +1. **Set Up Development Environment**: Install either Foundry or Hardhat. +2. **Install Gelato VRF Contracts**: Use specific commands for Hardhat or Foundry. +3. **Inherit** `GelatoVRFConsumerBase` **Contract**: Incorporate it into your contract. +4. **Request Randomness**: Call `_requestRandomness()` function. +5. **Implement Callback Function**: Define how your contract handles the randomness response. +6. **Include** `dedicated msg.sender`: Essential for contract security and function. + +## Quick Start + +### Step 1: Set Up Your Development Environment + +Make sure you have Hardhat or Foundry ready for use. + +### Step 2: Install Gelato VRF Contracts + +For Hardhat, clone the repository and set up the environment. For Foundry, use the `forge install` command. + +### Step 3: Inherit GelatoVRFConsumerBase Contract + +Create a contract that inherits from **GelatoVRFConsumerBase**. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity 0.8.18; + +import {GelatoVRFConsumerBase} from "./GelatoVRFConsumerBase.sol"; + +contract YourContract is GelatoVRFConsumerBase { + // Your contract's code +} +``` + +### Step 4: Request Randomness + +To request randomness, call the \_requestRandomness() function. You should protect the call since it will take from your 1Balance. The data argument will be passed back to you by the W3F. + +```solidity +function requestRandomness(bytes memory data) external { + require(msg.sender == ...); + uint64 requestId = _requestRandomness(data); +} +``` + +### Step 5: Implement Callback Function + +```solidity +function _fulfillRandomness( + bytes32 randomness, + uint64 requestId, + bytes memory data +) internal override { + // Your implementation here +} +``` + +### Step 6: Include Dedicated msg.sender + +When you're ready to deploy your Gelato VRF-compatible contract, an important step is to include the dedicated msg.sender as a constructor parameter. This ensures that your contract is set up to work with the correct operator for fulfilling the randomness requests. It's crucial for ensuring that only authorized requests are processed. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity 0.8.18; + +import {GelatoVRFConsumerBase} from "./GelatoVRFConsumerBase.sol"; + +contract YourContract is GelatoVRFConsumerBase { + constructor(address operator) + GelatoVRFConsumerBase(operator) { + // Additional initializations + } + + // The rest of your contract code +} +``` + +## Task Creation + +Upon deploying your contract, you will need to create a Gelato Task. This can be done via the [Gelato UI](https://app.gelato.network/). Next, you will be prompted to provide the address of the Request Contract to which the Gelato nodes should respond. Enter the address of your contract, and once all details have been correctly entered, proceed with launching your Gelato VRF instance. + +Now everytime you call the `_requestRandomness()` function, the Gelato nodes will respond with a random number that you can use in your contract. + +For more detailed information, refer to the [Gelato VRF documentation](https://docs.gelato.network/web3-services/vrf). + +![Gelato VRF 1](https://docs.shape.network/gelato-gui-1.webp) + +![Gelato VRF 2](https://docs.shape.network/gelato-gui-2.webp) + +--- + +Canonical page: https://docs.shape.network/tools/safes-asset-security +Markdown page: https://docs.shape.network/tools/safes-asset-security.md + +# Safes & Asset Security + +Manage high-value assets and team operations securely on Shape. + +- **Safe**: Multi-signature wallet for team treasuries, protocol governance, or any operation requiring multiple approvals. Shape's Safe is at [safe.shape.network](https://safe.shape.network/). +- **Delegate**: Prove NFT ownership or claim airdrops from a hot wallet without moving assets from cold storage. + +- [Safe](https://safe.shape.network/): A decentralized custody protocol and collective asset management platform + +- [Delegate](https://delegate.xyz/): Claim airdrops, mint NFTs, and prove ownership via your hot wallet + +--- + +Canonical page: https://docs.shape.network/tools/sybil-resistance +Markdown page: https://docs.shape.network/tools/sybil-resistance.md + +# Sybil Resistance + +Protect your app from bots and sybil attacks while preserving user privacy. + +- **Passport**: Privacy-preserving identity scoring. Good for gating access, weighting rewards, detecting bots. +- **Premint**: Allowlist management for mints. Good for curated drops, community-first launches. +- **Crossmint Verifiable Credentials**: Issue and verify credentials at scale. Good for KYC-lite, compliance, loyalty programs. + +- [Passport](https://app.passport.xyz/#/shape/): A tool for dApps to defend against sybils while preserving user privacy + +- [Premint](https://www.premint.xyz/): Create allowlists tailored to your requirements + +- [Crossmint Verifiable Credentials](https://www.crossmint.com/products/verifiable-credentials): Issue and verify credentials at scale + +--- + +Canonical page: https://docs.shape.network/tutorials/mint-nft-collection +Markdown page: https://docs.shape.network/tutorials/mint-nft-collection.md + +# Launch an NFT Collection on Shape + +Deploy an ERC-721 contract to Shape Sepolia, mint an NFT, and verify it on the block explorer. + +## Prerequisites + +- [Foundry](https://book.getfoundry.sh/getting-started/installation) installed +- Shape Sepolia ETH from the [Alchemy Faucet](https://www.alchemy.com/faucets/shape-sepolia) +- A wallet private key funded with testnet ETH + +## 1. Set Up the Project + +```bash +forge init my-nft && cd my-nft +rm src/Counter.sol test/Counter.t.sol script/Counter.s.sol +forge install OpenZeppelin/openzeppelin-contracts --no-commit +``` + +Add the `remappings` line to `foundry.toml`: + +```toml +[profile.default] +src = "src" +out = "out" +libs = ["lib"] +remappings = ["@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/"] +``` + +## 2. Write the Contract + +Create `src/MyNFT.sol`: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; + +contract MyNFT is ERC721, Ownable { + uint256 public totalSupply; + uint256 public constant MAX_SUPPLY = 1000; + string private _baseTokenURI; + + constructor() ERC721("MyNFT", "MNFT") Ownable(msg.sender) {} + + function mint(address to) external onlyOwner { + require(totalSupply < MAX_SUPPLY, "Max supply reached"); + _mint(to, totalSupply); + totalSupply++; + } + + function setBaseURI(string calldata baseURI) external onlyOwner { + _baseTokenURI = baseURI; + } + + function _baseURI() internal view override returns (string memory) { + return _baseTokenURI; + } +} +``` + +## 3. Test + +Create `test/MyNFT.t.sol`: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +import {Test} from "forge-std/Test.sol"; +import {MyNFT} from "../src/MyNFT.sol"; + +contract MyNFTTest is Test { + MyNFT nft; + + function setUp() public { + nft = new MyNFT(); + } + + function test_mint() public { + nft.mint(address(this)); + assertEq(nft.ownerOf(0), address(this)); + assertEq(nft.totalSupply(), 1); + } +} +``` + +```bash +forge test +``` + +## 4. Deploy to Shape Sepolia + +```bash +export PRIVATE_KEY= + +forge create src/MyNFT.sol:MyNFT \ + --rpc-url https://sepolia.shape.network \ + --private-key $PRIVATE_KEY +``` + +Save the `Deployed to` address from the output. + +## 5. Mint an NFT + +```bash +cast send "mint(address)" \ + --rpc-url https://sepolia.shape.network \ + --private-key $PRIVATE_KEY +``` + +Confirm the mint: + +```bash +cast call "ownerOf(uint256)" 0 \ + --rpc-url https://sepolia.shape.network +``` + +This returns your address (ABI-encoded, zero-padded to 32 bytes). + +## 6. Optional: Let Users Mint From Another Chain + +If your mint UI should let users start from Ethereum, Base, Arbitrum, or another supported chain, use Relay cross-chain call execution. The UI can let the user pay from an origin-chain balance while Relay executes the NFT mint call on Shape. + +The most important contract detail is to mint to an explicit recipient, like `mint(address to)`, instead of relying only on `msg.sender`. Relay's Shape-side address executes the destination call, so your UI should encode the buyer's address into the mint calldata and your contract should allow the Relay address to call that mint path. Treat this as a narrow exception: most arbitrary addresses should still be blocked from minting this way, but the Relay executor or relayer address you configure for Shape needs permission to call the function and mint the NFT to the recipient. + +```ts +import { getClient } from '@relayprotocol/relay-sdk'; +import { encodeFunctionData, parseEther, zeroAddress } from 'viem'; + +const relayClient = getClient(); +const shapeSepoliaChainId = 11011; // Use 360 for Shape mainnet. +const mintPrice = parseEther('0.01'); + +const callData = encodeFunctionData({ + abi: nftAbi, + functionName: 'mint', + args: [userAddress], +}); + +const quote = await relayClient.actions.getQuote({ + wallet, + chainId: originChainId, + toChainId: shapeSepoliaChainId, + currency: zeroAddress, + toCurrency: zeroAddress, + user: userAddress, + recipient: userAddress, + amount: mintPrice.toString(), + tradeType: 'EXACT_OUTPUT', + txs: [ + { + to: nftContractAddress, + value: mintPrice.toString(), + data: callData, + }, + ], +}); + +await relayClient.actions.execute({ + quote, + wallet, + onProgress: (progress) => { + // Use this to show states like: + // confirm in wallet -> origin transaction submitted -> relaying -> minted + }, +}); +``` + +For a free mint, set the mint transaction `value` and quote `amount` to `"0"`. For a paid mint, use `EXACT_OUTPUT` with the exact ETH value your mint call requires on Shape. Keep quotes fresh, check the user's origin-chain balance before enabling the mint button, and show a clear error if Relay has insufficient liquidity or the user lacks enough ETH for the amount, Relay fees, and origin-chain gas. + +The Stack mint UI uses the same pattern, with one extra convenience: users can optionally send additional ETH to themselves on Shape in the same Relay execution. That is just a second transaction in `txs` and is useful for onboarding, but most mint UIs only need the Shape contract call. + +See Relay's [Call Execution Integration Guide](https://docs.relay.link/references/api/api_guides/calling-integration-guide#common-use-cases) for the full quote, execution, and status flow. + +## 7. Verify on Shapescan + +```bash +forge verify-contract src/MyNFT.sol:MyNFT \ + --verifier blockscout \ + --verifier-url https://sepolia.shapescan.xyz/api/ +``` + +Once verified, view your contract at `https://sepolia.shapescan.xyz/address/`. + +## 8. Register for Gasback + +Register your contract for [Gasback](https://docs.shape.network/tutorials/registering-contract-gasback/index.md) to reclaim 80% of sequencer fees users spend interacting with it. + +## Next Steps + +- **Deploy to mainnet**: Use `--rpc-url https://mainnet.shape.network` and verify against `https://shapescan.xyz/api/` +- **View on Deca**: Once on mainnet, see your collection at `https://deca.art/token/shape//` +- **Add metadata**: Upload JSON metadata to IPFS with [Pinata](https://pinata.cloud/), then call `setBaseURI` to point your tokens at it +- [Build a dApp](https://docs.shape.network/building-on-shape/builder-kit.md) with the Shape Builder Kit + +--- + +Canonical page: https://docs.shape.network/tutorials/registering-contract-gasback/dashboard +Markdown page: https://docs.shape.network/tutorials/registering-contract-gasback/dashboard.md + +# Registering via the Dashboard + +This tutorial will guide you through the process of registering your smart contract for gasback using the Gasback Dashboard UI. + +## Prerequisites + +1. Your smart contract must be deployed on Shape. +2. You need access to a Web3 wallet (like MetaMask) with the account that owns the smart contract you want to register. +3. Your smart contract must have an owner() function which returns the address of the account you will connect to the dashboard + +## Step 1: Access the Dashboard + +Open your web browser and navigate to the [Gasback dashboard](https://gasback.shape.network/). + +![Gasback Dashboard](https://docs.shape.network/gasback-dashboard-1.webp) + +## Step 2: Connect Your Wallet + +1. Click the "Connect Wallet" button in the top right corner of the page. +2. A popup will appear with various wallet options. Select your preferred wallet (e.g., MetaMask). +3. Follow the prompts in your wallet to connect to the site and select the account you want to use. + +![Connect Wallet](https://docs.shape.network/gasback-dashboard-2.webp) + +## Step 3: View Your Gasback Dashboard + +1. Once connected, you'll see your Gasback dashboard. +2. If you haven't registered any contracts yet, you'll see a hero banner explaining that you don't have a gasback NFT yet. + +![Gasback Dashboard](https://docs.shape.network/gasback-dashboard-3.webp) + +## Step 4: Initiate registration and enter contract details + +1. Click the "Register" button in the hero banner or the header. and a popup window titled "Register a new smart contract" will appear. +2. In the "Contract Address" field, enter the address of the smart contract you want to register for gasback. +3. The "NFT Recipient" field should automatically populate with your connected wallet address. This is the address that will receive the gasback NFT. You can change this if you want the NFT to go to a different address. +4. Click “Register” + +![Register Contract](https://docs.shape.network/gasback-dashboard-4.webp) + +## Step 5: Confirm Registration + +1. Read the warning message and double-check that all the information is correct. +2. Click the "Confirm" button. +3. Your wallet will prompt you to confirm the transaction. Review the details and confirm the transaction. +4. Wait for the transaction to be processed and confirmed on the blockchain. + +![Confirm Registration](https://docs.shape.network/gasback-dashboard-5.webp) + +## Step 6: Verify Registration + +1. After the transaction is confirmed, the dashboard should update to reflect your newly registered contract. +2. You did it! You should see your unique gasback NFT that was generated onchain. The art on your NFT will evolve as your token accrues gasback. + +![Verify Registration](https://docs.shape.network/gasback-dashboard-6.webp) + +## Step 7: Managing Your Gasback + +Your dashboard will now display any gasback activity related to your registered contract. Activity can take up to 10 minutes to show up here. Registration itself earns you gasback, so you've already started your journey! + +If you have more contracts you want to register for Gasback, you can click the “manage” button and add their contract addresses to the field, and all the gasback earned by those contracts will be claimable with a single NFT. + +![Manage Gasback](https://docs.shape.network/gasback-dashboard-7.webp) + +That's it! If you're less of a UI person, check out the next section to see how to do this programmatically. + +--- + +Canonical page: https://docs.shape.network/tutorials/registering-contract-gasback +Markdown page: https://docs.shape.network/tutorials/registering-contract-gasback/index.md + +# Registering Your Contract for Gasback + +There are two different methods to register your contract for Gasback registration. You can either use the UI, or register programmatically from the contract you wish to register. This section has tutorials on how to do each approach. + +- [Using the dashboard](https://docs.shape.network/tutorials/registering-contract-gasback/dashboard.md) + +- [Programmatically](https://docs.shape.network/tutorials/registering-contract-gasback/programmatically.md) + +--- + +Canonical page: https://docs.shape.network/tutorials/registering-contract-gasback/programmatically +Markdown page: https://docs.shape.network/tutorials/registering-contract-gasback/programmatically.md + +# Registering Programmatically + +This tutorial will guide you through the process of registering your smart contract for gasback programmatically. The tutorial walks through 3 different approaches you can use, with full example contracts. + +## Prerequisites + +1. Some familiarity with Solidity and Node JS. +2. If you want to actually deploy the contracts we'll go through so that you can get hands on, download the example repo [here](https://github.com/shape-network/gasback-tutorial). +3. (Optional) If you do decide to deploy the contracts and register, you'll need some Shape Sepolia ETH which you can get from the [Alchemy faucet](https://www.alchemy.com/faucets/shape-sepolia) or the [Superchain faucet](https://console.optimism.io/faucet). You will then need to create a `.env` file according to the `.env.example` file in the repo. + +## Example A: Registering inside the contract and sending the Gasback NFT to the contract owner to hold + +The code snippet below is the complete implementation of a contract called ExampleA, that we'll use for the first example. + +A is an Ownable contract, which means external callers can call an `owner()` method to determine which address has control over the contract. + +```solidity filename="ExampleA.sol" +pragma solidity 0.8.20; + +import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; +import {IGasback} from "./interfaces/IGasback.sol"; + +contract ExampleA is Ownable { + IGasback public gasback; + + constructor(address _gasback) Ownable(msg.sender) { + gasback = IGasback(_gasback); + } + + function registerForGasback() public onlyOwner { + gasback.register(owner(), address(this)); + } +} +``` + +As you can see, registration happens in one line, on line 14: `gasback.register(owner(), address(this));`. This says, register this address for gasback, and send the NFT to the owner of this contract. + +Inside the Gasback.sol contract (not shown), the `owner()` function of the contract that is registering gets called, so that the Gasback contract knows that the person due to receive the Gasback NFT is the person who controls the registering contract. + +> Warning: +> +> If your contract tries to register in the constructor, the call will fail. Registration must +> happen after contract construction. + +To deploy the contract above run: + +```bash +npx hardhat deployA --network shapeSepolia +``` + +You'll then see the deployed address in the console. + +To run the registration function, run: + +```bash +npx hardhat registerA --network shapeSepolia +``` + +Where the deployed address is the address printed in the deployment command. + +Once that's done, you can actually visit the [Gasback dashboard](https://gasback.shape.network/) and see your new Gasback NFT! + +## Example B: Registering inside a contract without requiring an owner + +```solidity filename="ExampleB.sol" +pragma solidity 0.8.20; + +import {IGasback} from "./interfaces/IGasback.sol"; +import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; + +contract ExampleB is IERC721Receiver { + IGasback public gasback; + + constructor(address _gasback) { + gasback = IGasback(_gasback); + } + + function registerForGasback() public { + address me = address(this); + gasback.register(me, me); + } + + function onERC721Received( + address operator, + address from, + uint256 tokenId, + bytes calldata data + ) external override returns (bytes4) { + return IERC721Receiver.onERC721Received.selector; + } +} +``` + +Contract B differs from A in a couple of key ways. Firstly, you'll notice that ExampleB is not an Ownable contract. The reason it's still able to register despite this, is that the contract itself is going to be the recipient of the Gasback NFT. This means we don't have to check an owner, because it's clearly registering itself. + +The second key change is the addition of the `onERC721Received` function. This inclusion is needed because Gasback.sol uses `_safeMint` to mint the NFT, which requires that any contract that receives the NFT implements this function, so that we know the NFT won't be stuck forever inside the contract, and the contract is actually expecting to receive and handle NFTs. + +> Warning: +> +> When implementing this pattern a function protected by some form of access control that +> withdraws the NFT from your contract is a great fallback option. + +Similar to example A you can deploy and run the registration function yourself by doing: + +```bash +npx hardhat deployB --network shapeSepolia +``` + +and + +```bash +npx hardhat registerB --network shapeSepolia +``` + +However in this example you won't see the NFT in your dashboard yet because you aren't the owner of it, the contract is! We'll explain how you can still manage the NFT that one of your contracts holds in a later tutorial, when we discuss the concept of **Delegation**. + +## Example C: Registering outside of a contract + +```solidity filename="ExampleC.sol" +pragma solidity 0.8.20; + +import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; + +contract ExampleC is Ownable { + constructor() Ownable(msg.sender) {} +} +``` + +The final example is a tiny contract. It has no logic in it other than to make itself Ownable. But, we can still register it for Gasback! + +The registration logic happens outside of the contract. All you have to do is call the registration on the Gasback contract directly, entering your own address as the NFT recipient and the contract address. + +You can see how this is done in `scripts/register.ts` in the registerC task: + +```typescript +task('registerC', 'Registers the ExampleC contract for gasback') + .addPositionalParam('contractAddress', 'The address of the ExampleC contract to register') + .setAction(async (taskArgs, hre) => { + const { contractAddress } = taskArgs; + + const [address] = await hre.ethers.getSigners(); + + const gasback = await hre.ethers.getContractAt('Gasback', gasbackAddress); + + const tx = await gasback.register(address, contractAddress); + await tx.wait(1); + + console.log('ExampleC registered! Tx hash: ', tx.hash); + }); +``` + +Of course, as proof it works, you can deploy and register using similar commands as before: + +```bash +npx hardhat deployC --network shapeSepolia +``` + +and + +```bash +npx hardhat registerC --network shapeSepolia +``` + +If you want an easy way to do this method, you can simply use the Gasback dashboard UI, connect your wallet, and paste in the contract address. The UI will make the contract call for you. + +## Summary + +That's it! You have now learned 3 different ways to register your contract for Gasback. In the next tutorials, we'll discuss how to delegate gasback rights when your contract owns the NFT instead of you, and we'll learn how to withdraw claimed gasback. + +--- + +Canonical page: https://docs.shape.network/wallet-setup +Markdown page: https://docs.shape.network/wallet-setup.md + +# Wallet Setup + +Set up your wallet on Shape. + +## 1. Add Shape to Your Wallet + +1. Go to the [Shape website](https://shape.network/) +2. Scroll down to the "Get Started" section and click "Add Shape Mainnet" +3. You'll be prompted to switch to the Shape network + - If the network isn't listed, you can [add it manually](https://docs.shape.network/technical-details/network-information.md) + +## 2. Bridge to Shape + +1. Choose a [bridge](https://shape.network/bridge) to Shape +2. Send ETH over to Shape from another chain +3. Once complete, check your ETH balance on Shape + - If you don't see your balance, make sure your wallet is connected to the Shape network + +## 3. Mint Your Stack + +Build your onchain reputation on Shape by earning medals with the Stack. It's also the most effective way to claim more $SHAPE. + +[Mint your Stack](https://stack.shape.network/) + +More on the Stack in the next section. diff --git a/public/llms.txt b/public/llms.txt index e0d3220..6e0278d 100644 --- a/public/llms.txt +++ b/public/llms.txt @@ -1,70 +1,58 @@ -# Shape Network Documentation +# Shape Documentation -> Shape is a culture-first EVM-compatible L2 built on Ethereum and the Optimism Superchain. It returns 80% of sequencer fees to contract owners via Gasback. Chain ID: 360 (mainnet), 11011 (testnet). Currency: ETH. RPC: https://mainnet.shape.network +> Official technical documentation for Shape, an Ethereum L2 built on the OP Stack and part of the Optimism Superchain. -## Getting Started +Mainnet chain ID: 360. Shape Sepolia chain ID: 11011. Gas currency: ETH. Gasback shares 80% of L2 sequencer fees with registered contract owners, excluding L1 data fees. -- [Introduction](https://docs.shape.network): Overview of Shape, the culture-first L2 for creators and the new NFT economy -- [Wallet Setup](https://docs.shape.network/wallet-setup): Add Shape to your wallet, bridge ETH, mint your Stack -- [Gasback](https://docs.shape.network/gasback): Claim back 80% of L2 sequencer fees users spend interacting with your contracts -- [The Stack](https://docs.shape.network/the-stack): Dynamic NFT reputation system with bronze, silver, gold, and special medals +Links below lead to Markdown generated from the same source as the website. Follow the relevant pages for full context. For current $SHAPE token and governance information, see https://shape.network/token. -## Quick Start +## Start Here -- [Quick Start](https://docs.shape.network/quick-start): Developer onboarding hub for Shape -- [Connect to Shape](https://docs.shape.network/quick-start/connect-to-shape): Configure viem, wagmi, Foundry, and ethers.js for Shape Mainnet (chain ID 360) and Shape Sepolia (chain ID 11011) -- [Deploy a Contract](https://docs.shape.network/quick-start/deploy-a-contract): Deploy and verify a smart contract on Shape with Foundry +- [Welcome](https://docs.shape.network/index.md): Shape is the culture-first L2 built on top of Ethereum to power the new NFT economy. +- [Wallet Setup](https://docs.shape.network/wallet-setup.md): Set up your wallet on Shape. +- [Start Building on Shape](https://docs.shape.network/quick-start/index.md): Shape is an EVM-compatible L2 on the Optimism Superchain. Gasback returns 80% of sequencer fees to contract owners. +- [Network Information](https://docs.shape.network/technical-details/network-information.md): Mainnet and testnet chain IDs, ETH gas currency, RPC endpoints, and explorers. -## Building on Shape +## Gasback and Fees -- [Builder Kit](https://docs.shape.network/building-on-shape/builder-kit): Next.js starter with wallet connect (wagmi), NFT fetching, Shape RPC, and Shadcn UI -- [AI Agents](https://docs.shape.network/building-on-shape/ai): Build AI agents with MCP, Shape MCP server, and Vercel AI SDK -- [Transaction Fees](https://docs.shape.network/building-on-shape/transaction-fees): L1 security fees + L2 execution fees. 80% of L2 fees go back to contract owners via Gasback, 15% to Optimism Collective, 5% to Shape Foundation -- [Differences from Ethereum](https://docs.shape.network/building-on-shape/differences-ethereum-shape): EVM equivalent via OP Stack with minor opcode changes, dual-fee system, faster block times -- [Alchemy API](https://docs.shape.network/building-on-shape/alchemy-api): Full Alchemy tool suite available on Shape -- [Superchain Incentives](https://docs.shape.network/building-on-shape/superchain-incentives): RetroPGF, free contract deployment, gas sponsorship, launch support +- [Gasback](https://docs.shape.network/gasback.md): Claim back 80% of the sequencer fees that users spend interacting with your contracts on Shape. +- [Transaction Fees](https://docs.shape.network/building-on-shape/transaction-fees.md): Learn how network fees work on Shape, what changes them, where they go, and how to estimate them. +- [Registering Your Contract for Gasback](https://docs.shape.network/tutorials/registering-contract-gasback/index.md): Choose dashboard or programmatic contract registration for Gasback. -## Technical Reference +## Build Applications -- [Network Information](https://docs.shape.network/technical-details/network-information): Mainnet chain ID 360, RPC https://mainnet.shape.network, explorer https://shapescan.xyz. Testnet chain ID 11011, RPC https://sepolia.shape.network, explorer https://sepolia.shapescan.xyz -- [Contract Addresses](https://docs.shape.network/technical-details/contract-addresses): L1 and L2 contract addresses for mainnet and Sepolia. Gasback contract: 0xf5e602c87d675E978F097503aedE4A766285a08B (mainnet), 0xdF329d59bC797907703F7c198dDA2d770fC45034 (testnet) -- [Run a Node](https://docs.shape.network/technical-details/run-a-node): Run Shape mainnet and Sepolia nodes using op-node with custom rollup.json and genesis.json +- [Connect to Shape](https://docs.shape.network/quick-start/connect-to-shape.md): Shape Mainnet runs on chain ID 360. Shape Sepolia (testnet) runs on chain ID 11011. +- [Deploy a Contract on Shape](https://docs.shape.network/quick-start/deploy-a-contract.md): Deploy a smart contract to Shape Sepolia and verify it on the block explorer using Foundry. +- [Shape Builder Kit for Developers](https://docs.shape.network/building-on-shape/builder-kit.md): The Shape Builder Kit is your go-to starter for crafting dApps on the Shape ecosystem. It's a monorepo with a Next.js frontend (wagmi, viem) and a Hardhat smart contract package, all pre-wired with sensible defaults. +- [Launch an NFT Collection on Shape](https://docs.shape.network/tutorials/mint-nft-collection.md): Deploy an ERC-721 contract to Shape Sepolia, mint an NFT, and verify it on the block explorer. +- [AI Agents on Shape](https://docs.shape.network/building-on-shape/ai.md): Shape MCP, AI integration examples, and agent development guidance. -## Onchain Projects +## Explore and Operate -- [Onchain Compatible](https://docs.shape.network/building-on-shape/onchain-compatible): Collection of interoperable onchain projects on Shape -- [Assembly](https://docs.shape.network/building-on-shape/onchain-compatible/assembly): ERC1155 crafting system built on Otoms. Blueprints, tiers, mutator contracts, fungible and non-fungible items -- [OTOM](https://docs.shape.network/building-on-shape/onchain-compatible/otom): Onchain particle chemistry by Kjetil Golid. Mine otoms, annihilate for energy, react to create molecules +- [The Stack](https://docs.shape.network/the-stack.md): Dynamic NFT achievements, participation, and medals across the Shape ecosystem. +- [Contract Addresses](https://docs.shape.network/technical-details/contract-addresses.md): Official network infrastructure contract addresses. +- [Run a Node](https://docs.shape.network/technical-details/run-a-node.md): Shape is an OP Stack rollup. Running a Shape node requires two clients that talk over the Engine API and authenticate with a shared JWT secret: +- [Differences between Ethereum and Shape](https://docs.shape.network/building-on-shape/differences-ethereum-shape.md): Shape is EVM equivalent, but has some minor differences. -## Tools +## Tools and Further Reading -- [Account Abstraction](https://docs.shape.network/tools/account-abstraction): Alchemy Bundler, Gas Manager, Embedded Accounts, Smart Accounts. Crossmint NFT Checkout and Wallet-as-a-Service -- [Bridges](https://docs.shape.network/tools/bridges): Relay (instant bridging), Superbridge (native bridging), Alchemy bridge. Testnet bridges available for Sepolia -- [Explorers](https://docs.shape.network/tools/explorers): Shapescan (block explorer), Deca (NFT explorer), Zapper (human-readable onchain activity) -- [Data Indexers](https://docs.shape.network/tools/data-indexers): Alchemy NFT/Token/Transfers APIs and Webhooks, Alchemy Subgraphs, Goldsky, Reservoir, SimpleHash -- [Faucets](https://docs.shape.network/tools/faucets): Alchemy and Optimism faucets for Shape Sepolia testnet ETH -- [Node Providers](https://docs.shape.network/tools/node-providers): Alchemy Supernode RPC -- [Oracles - Gelato VRF](https://docs.shape.network/tools/oracles/gelato-vrf): Verifiable randomness using Drand for gaming, DeFi, NFT generation -- [Safes & Asset Security](https://docs.shape.network/tools/safes-asset-security): Safe multisig on Shape, Delegate for hot wallet claim/mint/ownership -- [Sybil Resistance](https://docs.shape.network/tools/sybil-resistance): Gitcoin Passport, Premint allowlists, Crossmint Verifiable Credentials - -## Tutorials - -- [Launch an NFT Collection](https://docs.shape.network/tutorials/mint-nft-collection): Deploy an ERC-721 contract on Shape with Foundry, mint an NFT, verify on Shapescan -- [Register Contract for Gasback (Dashboard)](https://docs.shape.network/tutorials/registering-contract-gasback/dashboard): Step-by-step UI guide to register contracts via the Gasback dashboard -- [Register Contract for Gasback (Programmatic)](https://docs.shape.network/tutorials/registering-contract-gasback/programmatically): Three Solidity approaches to register contracts for Gasback +- [Alchemy API](https://docs.shape.network/building-on-shape/alchemy-api.md): Find out what Alchemy tools are available to use on Shape. +- [Assembly](https://docs.shape.network/building-on-shape/onchain-compatible/assembly.md): The Assembly system, built on top of Otoms, is a flexible ERC1155 implementation enabling the creation, crafting, and management of both fungible and non-fungible items on the blockchain. Built with upgradeability in... +- [Onchain Compatible Projects](https://docs.shape.network/building-on-shape/onchain-compatible/index.md): A collection of projects made with interoperability in mind +- [OTOM by Kjetil Golid](https://docs.shape.network/building-on-shape/onchain-compatible/otom.md): Create and experiment with particles called otoms +- [Superchain incentives](https://docs.shape.network/building-on-shape/superchain-incentives.md): Learn about the Superchain incentives available to you as a Shape builder. +- [Account Abstraction](https://docs.shape.network/tools/account-abstraction.md): On Shape, combine AA with Gasback to subsidize your users and recoup 80% of sequencer fees. +- [Bridges](https://docs.shape.network/tools/bridges.md): Bridge ETH and tokens between Ethereum and Shape. +- [Data Indexers](https://docs.shape.network/tools/data-indexers.md): NFT queries, indexing services, and data APIs. +- [Explorers](https://docs.shape.network/tools/explorers.md): Verify your contracts on Shapescan to make them readable. See Deploy a Contract for verification steps. +- [Faucets](https://docs.shape.network/tools/faucets.md): Get free testnet ETH on Shape Sepolia for development. +- [Node Providers](https://docs.shape.network/tools/node-providers.md): Public and provider RPC endpoints for mainnet and testnet. +- [Gelato VRF](https://docs.shape.network/tools/oracles/gelato-vrf.md): Request verifiable randomness from smart contracts using Gelato VRF. +- [Safes & Asset Security](https://docs.shape.network/tools/safes-asset-security.md): Manage high-value assets and team operations securely on Shape. +- [Sybil Resistance](https://docs.shape.network/tools/sybil-resistance.md): Protect your app from bots and sybil attacks while preserving user privacy. +- [Registering via the Dashboard](https://docs.shape.network/tutorials/registering-contract-gasback/dashboard.md): This tutorial will guide you through the process of registering your smart contract for gasback using the Gasback Dashboard UI. +- [Registering Programmatically](https://docs.shape.network/tutorials/registering-contract-gasback/programmatically.md): This tutorial will guide you through the process of registering your smart contract for gasback programmatically. The tutorial walks through 3 different approaches you can use, with full example contracts. ## Optional -- [Shape Website](https://shape.network) -- [Discord](https://discord.com/invite/shape-l2) -- [X / Twitter](https://x.com/shape) -- [GitHub](https://github.com/shape-network) -- [Shape MCP Server](https://github.com/shape-network/mcp-server): MCP server for AI agents to query Gasback, NFT analytics, Stack medals -- [Builder Kit Repo](https://github.com/shape-network/builder-kit): Next.js starter template source code -- [Assembly Repo](https://github.com/shape-network/assembly): Assembly items system source code and contracts -- [OTOM Contracts](https://github.com/shape-network/otom-contracts): OTOM smart contracts source code -- [Gasback Dashboard](https://gasback.shape.network): Register and manage Gasback for your contracts -- [The Stack App](https://stack.shape.network): Mint your Stack and track medals -- [Shapescan](https://shapescan.xyz): Block explorer -- [Deca](https://deca.art): NFT explorer +- [All technical documentation](https://docs.shape.network/llms-full.txt): All generated pages in one file. Use individual pages for narrower questions. diff --git a/public/quick-start/connect-to-shape.md b/public/quick-start/connect-to-shape.md new file mode 100644 index 0000000..bd6aeeb --- /dev/null +++ b/public/quick-start/connect-to-shape.md @@ -0,0 +1,76 @@ +# Connect to Shape + +Shape Mainnet runs on chain ID `360`. Shape Sepolia (testnet) runs on chain ID `11011`. + +> The public RPCs are rate-limited. For production apps, use [Alchemy](https://www.alchemy.com/rpc/shape) (`https://shape-mainnet.g.alchemy.com/v2/YOUR_KEY`). Free tier available. + +The examples below use viem v2+ and wagmi v2+. Both export `shape` and `shapeSepolia` chain definitions. + +## viem + +```ts +import { createPublicClient, http } from 'viem'; +import { shape } from 'viem/chains'; + +const client = createPublicClient({ + chain: shape, + transport: http('https://mainnet.shape.network'), +}); +``` + +For Shape Sepolia, use `shapeSepolia` and the testnet RPC: + +```ts +import { createPublicClient, http } from 'viem'; +import { shapeSepolia } from 'viem/chains'; + +const client = createPublicClient({ + chain: shapeSepolia, + transport: http('https://sepolia.shape.network'), +}); +``` + +## wagmi + +```ts +import { http, createConfig } from 'wagmi'; +import { shape, shapeSepolia } from 'wagmi/chains'; + +export const config = createConfig({ + chains: [shape, shapeSepolia], + transports: { + [shape.id]: http('https://mainnet.shape.network'), + [shapeSepolia.id]: http('https://sepolia.shape.network'), + }, +}); +``` + +## Foundry + +Add a profile to `foundry.toml`: + +```toml +# foundry.toml +[profile.shape-sepolia] +eth_rpc_url = "https://sepolia.shape.network" +chain_id = 11011 +``` + +## ethers.js v6 + +```ts +import { JsonRpcProvider } from 'ethers'; + +const provider = new JsonRpcProvider('https://mainnet.shape.network'); +``` + +## Network Reference + +| | Mainnet | Sepolia | +| --- | --- | --- | +| Chain ID | `360` | `11011` | +| RPC | `https://mainnet.shape.network` | `https://sepolia.shape.network` | +| Explorer | [shapescan.xyz](https://shapescan.xyz/) | [sepolia.shapescan.xyz](https://sepolia.shapescan.xyz/) | +| Currency | ETH | ETH | + +See [Network Information](https://docs.shape.network/technical-details/network-information.md) for the full reference. diff --git a/public/quick-start/deploy-a-contract.md b/public/quick-start/deploy-a-contract.md new file mode 100644 index 0000000..7ce60d0 --- /dev/null +++ b/public/quick-start/deploy-a-contract.md @@ -0,0 +1,66 @@ +# Deploy a Contract on Shape + +Deploy a smart contract to Shape Sepolia and verify it on the block explorer using Foundry. + +## Prerequisites + +- [Foundry](https://book.getfoundry.sh/getting-started/installation) installed +- Shape Sepolia ETH from the [Alchemy Faucet](https://www.alchemy.com/faucets/shape-sepolia) +- A wallet private key funded with testnet ETH + +## 1. Create a Project + +```bash +forge init my-shape-contract +cd my-shape-contract +``` + +This scaffolds a project with a `Counter.sol` contract in `src/`. + +## 2. Deploy + +```bash +forge create src/Counter.sol:Counter \ + --rpc-url https://sepolia.shape.network \ + --private-key $PRIVATE_KEY +``` + +Save the `Deployed to` address from the output. + +## 3. Verify on the Explorer + +```bash +forge verify-contract src/Counter.sol:Counter \ + --verifier blockscout \ + --verifier-url https://sepolia.shapescan.xyz/api/ +``` + +Replace `` with the address from step 2. + +## 4. Deploy to Mainnet + +When ready for mainnet, use the mainnet RPC and verify against the mainnet explorer: + +```bash +forge create src/Counter.sol:Counter \ + --rpc-url https://mainnet.shape.network \ + --private-key $PRIVATE_KEY +``` + +```bash +forge verify-contract src/Counter.sol:Counter \ + --verifier blockscout \ + --verifier-url https://shapescan.xyz/api/ +``` + +## 5. Register for Gasback + +Gasback returns 80% of sequencer fees to contract owners. Register your deployed contract to start earning. + +See [Registering Your Contract for Gasback](https://docs.shape.network/tutorials/registering-contract-gasback/index.md) for the full walkthrough. + +## Next Steps + +- [Build a dApp](https://docs.shape.network/building-on-shape/builder-kit.md) with the Shape Builder Kit +- [Connect to Shape](https://docs.shape.network/quick-start/connect-to-shape.md) from your frontend +- [Gasback](https://docs.shape.network/gasback.md) (how fee reclamation works) diff --git a/public/quick-start/index.md b/public/quick-start/index.md new file mode 100644 index 0000000..34e4f51 --- /dev/null +++ b/public/quick-start/index.md @@ -0,0 +1,16 @@ +# Start Building on Shape + +Shape is an EVM-compatible L2 on the [Optimism Superchain](https://www.optimism.io/superchain). Gasback returns 80% of sequencer fees to contract owners. + +- [Connect to Shape](https://docs.shape.network/quick-start/connect-to-shape.md): Configure viem, wagmi, Foundry, and ethers.js for Shape + +- [Deploy a Contract](https://docs.shape.network/quick-start/deploy-a-contract.md): Deploy and verify a smart contract with Foundry + +- [Build a dApp](https://docs.shape.network/building-on-shape/builder-kit.md): Scaffold a full-stack dApp with the Shape Builder Kit + +## Resources + +- [Shape Sepolia Faucet](https://www.alchemy.com/faucets/shape-sepolia) (testnet ETH) +- [Alchemy Dashboard](https://www.alchemy.com/dashboard) (API keys and enhanced RPCs) +- [Network Information](https://docs.shape.network/technical-details/network-information.md) (chain IDs, RPCs, explorers) +- [Shape Discord](https://discord.com/invite/shape-l2) (builder support) diff --git a/public/technical-details/contract-addresses.md b/public/technical-details/contract-addresses.md new file mode 100644 index 0000000..6e24505 --- /dev/null +++ b/public/technical-details/contract-addresses.md @@ -0,0 +1,111 @@ +# Contract Addresses + +## Mainnet + +### Ethereum (L1) + +| Name | Address | +| ----------------------------------- | -------------------------------------------- | +| `L2OutputOracleProxy` | `0x6Ef8c69CfE4635d866e3E02732068022c06e724D` | +| `OptimismPortalProxy` | `0xEB06fFa16011B5628BaB98E29776361c83741dd3` | +| `L1StandardBridgeProxy` | `0x62Edd5f4930Ea92dCa3fB81689bDD9b9d076b57B` | +| `AddressManager` | `0xcee78437aE9e15cee9c78E63757E0153c0FD7479` | +| `AnchorStateRegistryProxy` | `0x02987E7294379B9DDa99d593b0C94c68266222D1` | +| `DelayedWETHProxy` | `0xfEc7865DAc5139886585F03146Ff61D9b31c2d57` | +| `DisputeGameFactoryProxy` | `0x575Aecd84083f93877291901907698F7db0Bd8b0` | +| `L1CrossDomainMessengerProxy` | `0x2b18602877181C3cB72C687E2A771E123A3788E3` | +| `L1ERC721BridgeProxy` | `0xe9d3E49b0636016c5fE9eaA2347948D0bA9f15Af` | +| `Mips` | `0xD30c2Cd3cd6112E61FDfb03e4b232564d7e5C91f` | +| `OptimismMintableERC20FactoryProxy` | `0x319322906beAdf69dF5d4607169c63D692B1aDC1` | +| `PreimageOracle` | `0xDF6a16a71d0BC7a1Bbe8FffB33700eC3d9448A5B` | +| `ProtocolVersionsProxy` | `0xa77995E10b0A833CDD4fA414C26E869F7aa32DDd` | +| `ProxyAdmin` | `0x11B190Ae661c6d6884dFEE48E215691E0DdB842e` | +| `SuperchainConfigProxy` | `0x125664BEf08177ca43f6f301E63118b1e4cCDe09` | +| `SystemConfigProxy` | `0xfF11e41D5C4F522E423Ff6C064Ff8D55AF8f7355` | +| `SystemOwnerSafe` | `0xacAF178b5048CB56712dc59E95fBA72F7990A005` | + +### Shape Mainnet (L2) + +| Name | Address | +| ------------------------------- | -------------------------------------------- | +| `Gasback` | `0xf5e602c87d675E978F097503aedE4A766285a08B` | +| `RecipientValidator` | `0x12e50C2B9Dd2741bd07Df4E2E544f3412fd584cE` | +| `WETH9` | `0x4200000000000000000000000000000000000006` | +| `multicall3` | `0xca11bde05977b3631167028862be2a173976ca11` | +| `ImmutableCreate2Factory` | `0x0000000000ffe8b47b3e2130213b802212439497` | +| `Create2Deployer` | `0x13b0D85CcB8bf860b6b79AF3029fCA081AE9beF2` | +| `DeterministicDeploymentProxy` | `0x4e59b44847b379578588920ca78fbf26c0b4956c` | +| `Seaport 1.6` | `0x0000000000000068F116a894984e2DB1123eB395` | +| `ConduitController` | `0x00000000F9490004C11Cef243f5400493c00Ad63` | +| `GitcoinPassportDecoder` | `0x2443D22Db6d25D141A1138D80724e3Eee54FD4C2` | +| `GitcoinResolver` | `0x90E2C4472Df225e8D31f44725B75FFaA244d5D33` | +| `GitcoinVerifier` | `0x16db23c4b99bbC9A6Bf55dF7a787C9AEFD261185` | +| `GitcoinAttester` | `0xCc90105D4A2aa067ee768120AdA19886021dF422` | +| `L2CrossDomainMessenger` | `0x4200000000000000000000000000000000000007` | +| `L2StandardBridge` | `0x4200000000000000000000000000000000000010` | +| `SequencerFeeVault` | `0x4200000000000000000000000000000000000011` | +| `OptimismMintableERC20Factory` | `0x4200000000000000000000000000000000000012` | +| `GasPriceOracle` | `0x420000000000000000000000000000000000000F` | +| `GovernanceToken` | `0x4200000000000000000000000000000000000042` | +| `L1Block` | `0x4200000000000000000000000000000000000015` | +| `L2ToL1MessagePasser` | `0x4200000000000000000000000000000000000016` | +| `L2ERC721Bridge` | `0x4200000000000000000000000000000000000014` | +| `OptimismMintableERC721Factory` | `0x4200000000000000000000000000000000000017` | +| `ProxyAdmin` | `0x4200000000000000000000000000000000000018` | +| `BaseFeeVault` | `0x4200000000000000000000000000000000000019` | +| `L1FeeVault` | `0x420000000000000000000000000000000000001a` | +| `SchemaRegistry` | `0x4200000000000000000000000000000000000020` | +| `EAS` | `0x4200000000000000000000000000000000000021` | +| `BeaconBlockRoot` | `0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02` | +| `LegacyMessagePasser` | `0x4200000000000000000000000000000000000000` | +| `DeployerWhitelist` | `0x4200000000000000000000000000000000000002` | + +## Testnet (Sepolia) + +### Sepolia (L1) + +| Name | Address | +| ----------------------------------- | -------------------------------------------- | +| `AddressManager` | `0x42721d8512d62aA26B2Cfa1AE18bEEd5a9Ab1337` | +| `AnchorStateRegistryProxy` | `0x41ea3c370896632121Cdde1b94a4eCcf23DA4532` | +| `DelayedWETHProxy` | `0x7cc9cA91BA4f92F4C967E93a1AAd97beB18d3877` | +| `DisputeGameFactoryProxy` | `0x93eaa7A1E7d7af7eD9D612F9957988C8631c33e8` | +| `L1CrossDomainMessengerProxy` | `0xF9F730650e1AB4D23E2ac983934271ca7c5EF293` | +| `L1ERC721BridgeProxy` | `0x19f02c55254d2644eF94f30C74A932D64e1D4F86` | +| `L1StandardBridgeProxy` | `0x341ab1DAfdfB73b3D6D075ef10b29e3cACB2A653` | +| `L2OutputOracleProxy` | `0x532dDCed3440Eab81c529Ac8b0d7e429B5C05c52` | +| `Mips` | `0xaCf1Ed7357E41f652407ae6cFE1024705c758C38` | +| `OptimismMintableERC20FactoryProxy` | `0x46085E2e648488e49FBeaF6544b8e9Dc96df8BDd` | +| `OptimismPortalProxy` | `0xfF8Ca2B4d8122E41441F7ccDCf61b8692198Bd1E` | +| `PreimageOracle` | `0x8F3B1c59eD4439ebF564604aA4B93130DA4CD1D5` | +| `ProtocolVersionsProxy` | `0x8B901e6F6a49C950088d11C81166BCE2E3171C03` | +| `ProxyAdmin` | `0xd60a706Bf6108F090d055787B9B353FA7EEE1355` | +| `SuperchainConfigProxy` | `0xe5b3692266FF4Ab8A96A9C7Da6EeEe532CCc7916` | +| `SystemConfigProxy` | `0xa1aC91ED91EbE40E00d61E233c8026318b4da5fb` | +| `SystemOwnerSafe` | `0x4c4526C8C55c4e1a6F2aaf91e37f07c97786e0f5` | + +### Shape Sepolia (L2) + +| Name | Address | +| ------------------------------- | -------------------------------------------- | +| `Gasback` | `0xdF329d59bC797907703F7c198dDA2d770fC45034` | +| `WETH9` | `0x4200000000000000000000000000000000000006` | +| `L2CrossDomainMessenger` | `0x4200000000000000000000000000000000000007` | +| `L2StandardBridge` | `0x4200000000000000000000000000000000000010` | +| `SequencerFeeVault` | `0x4200000000000000000000000000000000000011` | +| `OptimismMintableERC20Factory` | `0x4200000000000000000000000000000000000012` | +| `GasPriceOracle` | `0x420000000000000000000000000000000000000F` | +| `GovernanceToken` | `0x4200000000000000000000000000000000000042` | +| `L1Block` | `0x4200000000000000000000000000000000000015` | +| `L2ToL1MessagePasser` | `0x4200000000000000000000000000000000000016` | +| `L2ERC721Bridge` | `0x4200000000000000000000000000000000000014` | +| `OptimismMintableERC721Factory` | `0x4200000000000000000000000000000000000017` | +| `ProxyAdmin` | `0x4200000000000000000000000000000000000018` | +| `BaseFeeVault` | `0x4200000000000000000000000000000000000019` | +| `L1FeeVault` | `0x420000000000000000000000000000000000001a` | +| `SchemaRegistry` | `0x4200000000000000000000000000000000000020` | +| `EAS` | `0x4200000000000000000000000000000000000021` | +| `BeaconBlockRoot` | `0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02` | +| `LegacyMessagePasser` | `0x4200000000000000000000000000000000000000` | +| `DeployerWhitelist` | `0x4200000000000000000000000000000000000002` | +| `LegacyERC20ETH` | `0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000` | diff --git a/public/technical-details/network-information.md b/public/technical-details/network-information.md new file mode 100644 index 0000000..6842893 --- /dev/null +++ b/public/technical-details/network-information.md @@ -0,0 +1,22 @@ +# Network Information + +## Mainnet + +| Network Name | Shape | +| --------------- | ----------------------------------------------- | +| Chain ID | `360` | +| Currency Symbol | `ETH` | +| RPC Endpoint | `https://mainnet.shape.network` | +| Block Explorer | [https://shapescan.xyz](https://shapescan.xyz/) | + +## Testnet + +| Network Name | Shape Sepolia | +| --------------- | --------------------------------------------------------------------------------- | +| Chain ID | `11011` | +| Currency Symbol | `ETH` | +| RPC Endpoint | `https://sepolia.shape.network` | +| Block Explorer | [https://sepolia.shapescan.xyz](https://sepolia.shapescan.xyz/) | + +> For production systems or high throughput testing, we recommend using a node from +> [Alchemy](https://www.alchemy.com/supernode), one of our node providers. diff --git a/public/technical-details/run-a-node.md b/public/technical-details/run-a-node.md new file mode 100644 index 0000000..7d1cd93 --- /dev/null +++ b/public/technical-details/run-a-node.md @@ -0,0 +1,354 @@ +# Run a Node + +Shape is an [OP Stack](https://docs.optimism.io/stack/getting-started) rollup. Running a Shape node requires two clients that talk over the [Engine API](https://github.com/ethereum/execution-apis/blob/main/src/engine/common.md) and authenticate with a shared JWT secret: + +- **Execution client (op-geth)** runs the EVM and stores chain state. +- **Consensus client (op-node)** derives the L2 chain from L1 data and feeds blocks to the execution client. + +## Prerequisites + +### Hardware requirements + +| Component | Full node | Archive node | +| --------- | --------- | ------------ | +| CPU | Reasonably modern, multi-core | Same | +| RAM | 16 GB minimum | 16 GB minimum | +| Storage | 700 GB+ SSD (grows ~100 GB / 6 months) | 14 TB+ NVMe SSD (grows ~3.5 TB / 6 months) | + +Archive nodes should use NVMe SSDs. op-geth's `--datadir.ancient` flag can offload older data to a cheaper HDD. + +### Software dependencies + +- [Go](https://go.dev/dl/) 1.21+ +- [just](https://github.com/casey/just#installation) (op-node build tool) +- Make (op-geth build tool) +- Git +- An **L1 Ethereum RPC endpoint** (e.g., [Alchemy](https://www.alchemy.com/), Infura, or your own node) +- An **L1 Beacon (consensus) endpoint** (required since Ecotone for blob retrieval) + +### Network ports + +Expose the following ports for P2P sync: + +| Port | Protocol | Purpose | +| ----- | -------- | ------- | +| 30303 | TCP + UDP | op-geth peer discovery and block propagation | +| 9222 | TCP + UDP | op-node peer discovery | + +## Choose paths + +The commands below assume these shell variables: + +```bash +export OP_GETH_DIR=$HOME/op-geth +export OPTIMISM_DIR=$HOME/optimism +export OP_NODE_DIR=$OPTIMISM_DIR/op-node +export DATADIR=$HOME/.shape +export CONFIG_DIR=$HOME/.shape-config + +mkdir -p "$DATADIR/geth" "$CONFIG_DIR" +``` + +Adjust them if you want different locations. + +## Build the clients + +Build both binaries first. You need the same `op-geth` and `op-node` binaries whether you sync from a snapshot or from genesis. + +### 1. Build op-geth + +```bash +git clone https://github.com/ethereum-optimism/op-geth.git "$OP_GETH_DIR" +cd "$OP_GETH_DIR" +git checkout +make geth +``` + +Check [op-geth releases](https://github.com/ethereum-optimism/op-geth/releases) for the required release branch. + +### 2. Build op-node + +```bash +git clone https://github.com/ethereum-optimism/optimism.git "$OPTIMISM_DIR" +cd "$OPTIMISM_DIR" +git checkout +cd "$OP_NODE_DIR" +just +``` + +Check [optimism releases](https://github.com/ethereum-optimism/optimism/releases) for the required release branch. + +## Option A: Sync from snapshot (fastest) + +[Alchemy snapshots](https://www.alchemy.com/snapshots/shape) let you skip the full sync by downloading a compressed chaindata archive and starting near the chain tip. + +### 1. Download the snapshot + +Visit [alchemy.com/snapshots/shape](https://www.alchemy.com/snapshots/shape) and download the latest `.tar.lz4` snapshot for your network (mainnet or Sepolia). + +### 2. Install lz4 and decompress + +```bash +# macOS +brew install lz4 + +# Ubuntu/Debian +sudo apt-get install -y lz4 +``` + +If you have existing data, stop your node and clear the old chaindata first: + +```bash +rm -rf "$DATADIR/geth/chaindata" +rm -rf "$DATADIR/geth/lightchaindata" +``` + +Decompress the snapshot: + +```bash +lz4 -c -d .tar.lz4 | tar -x -C "$DATADIR/geth/" +``` + +### 3. Download the rollup config + +Save the `rollup.json` for your network to `$CONFIG_DIR/rollup.json`: + +**Shape Mainnet:** +- [rollup.json](https://arweave.net/Lh9vjNsHKHOKzGwWwlvVz2tsxcL_h5Wc-Ga0udO3Xm0) + +**Shape Sepolia:** +- [rollup.json](https://arweave.net/gSb3hOzLaBIBy-AyWA2O2_03sfXJ-IwPqmV6Mhstmj8) + +### 4. Continue to [Configure and run](#configure-and-run) + +Your node should be in sync within minutes of starting. + +## Option B: Sync from genesis + +### 1. Download genesis and rollup configs + +Save the files for your network to `$CONFIG_DIR/rollup.json` and `$CONFIG_DIR/genesis.json`: + +**Shape Mainnet:** +- [rollup.json](https://arweave.net/Lh9vjNsHKHOKzGwWwlvVz2tsxcL_h5Wc-Ga0udO3Xm0) +- [genesis.json](https://arweave.net/LrSrsEJsUtSWNAzkpKqkwE9RG3JZP1SmlOQNlTu8Nxk) + +**Shape Sepolia:** +- [rollup.json](https://arweave.net/gSb3hOzLaBIBy-AyWA2O2_03sfXJ-IwPqmV6Mhstmj8) +- [genesis.json](https://arweave.net/nw6opum2ALT9T39TSAAK_Wq0Z75aZJWd6J2RmiWHm_s) + +### 2. Initialize the datadir + +```bash +"$OP_GETH_DIR/build/bin/geth" init --datadir="$DATADIR" "$CONFIG_DIR/genesis.json" +``` + +### 3. Continue to [Configure and run](#configure-and-run) + +## Configure and run + +### 1. Generate a JWT secret + +op-geth and op-node authenticate over the Engine API with a shared secret. Save it to `$CONFIG_DIR/jwt.txt`: + +```bash +openssl rand -hex 32 > "$CONFIG_DIR/jwt.txt" +``` + +### 2. Start op-geth + +**Shape Mainnet:** + +```bash +"$OP_GETH_DIR/build/bin/geth" \ + --datadir="$DATADIR" \ + --http \ + --http.port=8545 \ + --http.addr=0.0.0.0 \ + --http.api=eth,net,web3 \ + --ws \ + --ws.port=8546 \ + --ws.addr=0.0.0.0 \ + --ws.api=eth,net,web3 \ + --authrpc.addr=localhost \ + --authrpc.port=8551 \ + --authrpc.jwtsecret="$CONFIG_DIR/jwt.txt" \ + --authrpc.vhosts=* \ + --verbosity=3 \ + --rollup.sequencerhttp=https://mainnet.shape.network \ + --rollup.disabletxpoolgossip=true \ + --syncmode=snap +``` + +**Shape Sepolia:** Replace `--rollup.sequencerhttp` with `https://sepolia.shape.network`. + +**For archive mode:** Add `--gcmode=archive` and change `--syncmode=full`. + +### 3. Start op-node + +Set your L1 endpoints: + +```bash +export L1_RPC_URL= # e.g., https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY +export L1_RPC_KIND= # alchemy, quicknode, infura, basic, etc. +export L1_BEACON_URL= # e.g., https://ethereum-beacon-api.publicnode.com +``` + +**Shape Mainnet:** + +```bash +"$OP_NODE_DIR/bin/op-node" \ + --l1=$L1_RPC_URL \ + --l1.rpckind=$L1_RPC_KIND \ + --l1.beacon=$L1_BEACON_URL \ + --l2=ws://localhost:8551 \ + --l2.jwt-secret="$CONFIG_DIR/jwt.txt" \ + --rollup.config="$CONFIG_DIR/rollup.json" \ + --l2.enginekind=geth \ + --syncmode=execution-layer \ + --override.granite=1727370000 \ + --override.holocene=1739880000 \ + --override.isthmus=1774530000 \ + --p2p.listen.tcp=9222 \ + --p2p.listen.udp=9222 \ + --rpc.addr=127.0.0.1 \ + --rpc.port=9545 \ + --metrics.enabled \ + --metrics.port=7300 +``` + +**Shape Sepolia:** + +```bash +"$OP_NODE_DIR/bin/op-node" \ + --l1=$L1_RPC_URL \ + --l1.rpckind=$L1_RPC_KIND \ + --l1.beacon=$L1_BEACON_URL \ + --l2=ws://localhost:8551 \ + --l2.jwt-secret="$CONFIG_DIR/jwt.txt" \ + --rollup.config="$CONFIG_DIR/rollup.json" \ + --l2.enginekind=geth \ + --syncmode=execution-layer \ + --override.ecotone=0 \ + --override.fjord=1721732400 \ + --override.granite=1727197200 \ + --override.holocene=1739880000 \ + --override.isthmus=1763650800 \ + --p2p.listen.tcp=9222 \ + --p2p.listen.udp=9222 \ + --rpc.addr=127.0.0.1 \ + --rpc.port=9545 \ + --metrics.enabled \ + --metrics.port=7300 +``` + +For Sepolia, use a Sepolia L1 RPC for `L1_RPC_URL`. + +> **Do not expose the op-node RPC publicly.** The `--rpc.addr` should be `127.0.0.1` (localhost) unless you have a specific reason and a firewall in place. + +### Sync modes + +| Mode | op-node flag | op-geth flag | Use case | +| ---- | ------------ | ------------ | -------- | +| Snap sync | `--syncmode=execution-layer` | `--syncmode=snap` (default) | Downloads state at chain tip via P2P. Fastest for full nodes. | +| Full sync | `--syncmode=execution-layer` | `--syncmode=full` | Executes every block. Required for archive nodes. | + +## Verifying your node + +After startup, look for: + +1. op-geth logs showing `Syncing beacon headers` as it downloads headers from peers. +2. op-geth logs showing state download progress (percentage and data volumes). +3. Once caught up, both clients log new blocks every 2 seconds. + +Check sync status via JSON-RPC: + +```bash +curl -s -X POST http://localhost:8545 \ + -H "Content-Type: application/json" \ + -d '{"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}' +``` + +Returns `false` when fully synced. + +## Monitoring + +op-node exposes Prometheus metrics at `http://localhost:7300/metrics` when started with `--metrics.enabled`. + +| Metric | What it tells you | +| ------ | ----------------- | +| `op_node_default_refs_number` | Current L1/L2 block heights. If these stall, sync has stopped. | +| `op_node_default_p2p_peer_count` | Connected peers. Zero means the node falls back to slow L1-only derivation. | +| `op_node_default_rpc_client_request_duration_seconds` | RPC call latency. Spikes usually point to your L1 provider. | + +## Blob archiver + +Since Ecotone, batch data is posted as [EIP-4844 blobs](https://eips.ethereum.org/EIPS/eip-4844). Standard beacon nodes prune blobs after ~18 days. + +You need a blob archiver if your node may go offline for 18+ days or you are syncing from genesis without a recent snapshot. + +Options: +1. Run an L1 beacon node with pruning disabled (e.g., Lighthouse with `--prune-blobs=false`) +2. Use a third-party beacon endpoint that retains blobs beyond the 18-day window + +Point op-node at a fallback endpoint that has the old blobs: + +```bash +--l1.beacon-fallbacks= +``` + +## Troubleshooting + +### Node stalling or can't find peers + +Pass the bootnode enodes directly to op-node with `--p2p.bootnodes`: + +**Shape Mainnet:** + +``` +--p2p.bootnodes=enode://ae31be7c6596f4bc3657f90b65a1569c7b0db10c976649f06fe5cfb26139064d78d22b41aede293aa7358fc336d086051ac7fce78f063dce89e1da19c7b88aee@34.228.226.23:0?discport=30301,enode://0bea78f02c9bee58326b3a612dae63dc5a0193fb3dfc9be687c9757d25606405ef9f87810157598fce35688bdb5b3834dc6283afab6dc5774abbd6c5a7b17cea@3.85.27.162:0?discport=30301 +``` + +**Shape Sepolia:** + +``` +--p2p.bootnodes=enode://34fc07c447b843f3915f72cae27daeda7f2f8c3ea4b9132aed188387d3208d1d5cd7eeea58d30d038c14f985a5b108ad6b2172815ed8b757c9de9f609741b2a6@34.228.9.78:0?discport=30301,enode://61841b7682f808f5ce8222f15d7de7f118a2c2c3e342fe42ea41e987ae22fb90e49ef2b5f394897e791c33c6fc59d7ad064851ee653badb2d6ece7a94040944b@54.91.75.177:0?discport=30301 +``` + +### 401 Unauthorized: signature invalid + +The JWT secret doesn't match between op-node and op-geth. Ensure both point to the same `jwt.txt` file. + +### 403 Forbidden: invalid host specified + +Add `--authrpc.vhosts=*` to op-geth, or set it to the specific hostname op-node uses to connect. + +### P2P directory permission denied + +op-node can't write to its P2P discovery directory. Either grant write access or redirect with: + +```bash +--p2p.discovery.path=/path/with/write/access +--p2p.peerstore.path=/path/with/write/access +``` + +### Wrong chain / mismatched genesis + +Verify that: +- `L1_RPC_URL` points to the correct L1 network (Ethereum mainnet for Shape, Sepolia for Shape Sepolia) +- `rollup.json` matches the network you intend to run +- op-geth was initialized with the correct `genesis.json` + +### Unclean shutdown detected + +op-geth prints this warning on startup after a crash or kill. It usually recovers on its own. If the database is unrecoverable, re-initialize from genesis or restore from a [snapshot](https://www.alchemy.com/snapshots/shape). + +## References + +- [Optimism node operator docs](https://docs.optimism.io/node-operators/overview) +- [Run a node from source (OP docs)](https://docs.optimism.io/node-operators/tutorials/run-node-from-source) +- [Build from source (OP docs)](https://docs.optimism.io/node-operators/tutorials/node-from-source) +- [Alchemy Shape snapshots](https://www.alchemy.com/snapshots/shape) +- [op-node configuration reference](https://docs.optimism.io/node-operators/reference/op-node-config) +- [op-geth configuration reference](https://docs.optimism.io/node-operators/reference/op-geth-config) +- [OP Stack troubleshooting](https://docs.optimism.io/node-operators/guides/troubleshooting) diff --git a/public/the-stack.md b/public/the-stack.md new file mode 100644 index 0000000..a0dda25 --- /dev/null +++ b/public/the-stack.md @@ -0,0 +1,52 @@ +# The Stack + +The **Stack** is a dynamic NFT that serves as a living record of your achievements and contributions across the Shape ecosystem. + +By engaging with projects on Shape, you earn medals that showcase your journey and build your reputation in the community. + +## Getting Started + +### 1. Mint Your Stack + +Start by minting your Stack at [stack.shape.network](https://stack.shape.network/) + +### 2. Engage with Projects + +Engage with different projects in various ways on Shape. Interactions include: + +- Collecting NFTs +- Minting new creations +- Bidding on artwork auctions +- Exploring apps, games, and experiments + +### 3. Earn Medals + +As you engage, you'll earn medals issued by the community projects you interact with. There are 4 types of medals: + +- **Bronze (🟤):** Awarded for initial interactions +- **Silver (⚪):** Awarded for deeper involvement +- **Gold (🟡):** Awarded for significant contributions +- **Special (⚫):** Awarded for exceptional achievements + +### 4. Claim Medals + +Once a medal has been earned, you can claim it via your Stack dashboard. + +Your Stack NFT will dynamically update as you claim medals. + +### 5. Climb Ranks + +As you earn medals, you climb ranks in the [Leaderboard](https://stack.shape.network/leaderboard). + +Higher ranks may grant access to exclusive opportunities, such as allowlist spots for future Stack projects. + +## The Stack Keeps Stacking + +New projects and medals are added regularly. + +Stay up to date by following [@shape](https://twitter.com/shape) for the latest news. + +> Do you have a project you'd like to make part of the Stack? +> +> Reach out on [Twitter/X](https://x.com/shape) or in +> [Discord](https://discord.com/invite/shape-l2) to let us know. diff --git a/public/tools/account-abstraction.md b/public/tools/account-abstraction.md new file mode 100644 index 0000000..997358d --- /dev/null +++ b/public/tools/account-abstraction.md @@ -0,0 +1,25 @@ +# Account Abstraction + +On Shape, combine AA with [Gasback](https://docs.shape.network/gasback.md) to subsidize your users and recoup 80% of sequencer fees. + +| Tool | Use case | +| --- | --- | +| Alchemy Bundler + Gas Manager | Full AA stack: bundled UserOps, gas sponsorship | +| Alchemy Embedded Accounts | Email/social login, no seed phrase | +| Alchemy Smart Accounts | Programmable accounts with custom validation | +| Crossmint NFT Checkout | Credit card NFT purchases, no wallet needed | +| Crossmint WaaS | Invisible wallets embedded in your app | + +See [Alchemy's AA overview](https://www.alchemy.com/learn/account-abstraction) for background. + +- [Alchemy Bundler](https://www.alchemy.com/account-abstraction-infrastructure): A highly reliable ERC-4337 bundler + +- [Alchemy Gas Manager](https://www.alchemy.com/gas-manager): Sponsor gas for your users + +- [Alchemy Embedded Accounts](https://www.alchemy.com/embedded-accounts): Bring users onchain in seconds. No seed phrase, no gas + +- [Alchemy Smart Accounts](https://www.alchemy.com/account-contracts): Fully abstract the user experience with secure & extensible smart accounts + +- [Crossmint NFT Checkout](https://www.crossmint.com/products/nft-checkout): Sell NFTs via credit cards and cross-chain payments + +- [Crossmint Wallet-as-a-Service](https://www.crossmint.com/): Invisible wallets, embedded in your app diff --git a/public/tools/bridges.md b/public/tools/bridges.md new file mode 100644 index 0000000..ecab082 --- /dev/null +++ b/public/tools/bridges.md @@ -0,0 +1,17 @@ +# Bridges + +Bridge ETH and tokens between Ethereum and Shape. + +## Mainnet + +- [Relay](https://relay.link/shape): Instant bridging & cross-chain execution + +- [Superbridge](https://superbridge.app/shape-mainnet): Fast and secure native bridging + +- [Alchemy](https://shape-mainnet.bridge.alchemy.com/) + +## Sepolia + +- [Relay (Sepolia)](https://testnets.relay.link/bridge/shape-sepolia) + +- [Superbridge (Sepolia)](https://superbridge.app/shape-testnet) diff --git a/public/tools/data-indexers.md b/public/tools/data-indexers.md new file mode 100644 index 0000000..b72af5c --- /dev/null +++ b/public/tools/data-indexers.md @@ -0,0 +1,35 @@ +# Data Indexers + +| Service | Best for | +| --- | --- | +| Alchemy NFT/Token/Transfers APIs | General-purpose queries, NFT metadata, token balances | +| Alchemy Subgraphs | Custom GraphQL queries on indexed contract events | +| Alchemy Webhooks | Real-time notifications (transfers, mints, contract events) | +| Goldsky | Streaming onchain data to your database (Postgres, Kafka) | +| Reservoir | NFT marketplace data (listings, sales, collection stats) | +| SimpleHash | Cross-chain NFT and token metadata aggregation | + +Fetch NFTs owned by an address using the Alchemy NFT API: + +```ts +const res = await fetch( + `https://shape-mainnet.g.alchemy.com/nft/v3/${ALCHEMY_KEY}/getNFTsForOwner?owner=${address}` +); +const { ownedNfts } = await res.json(); +``` + +- [Alchemy NFT API](https://www.alchemy.com/nft-api): An API to launch, verify, analyze, trade & display NFTs + +- [Alchemy Subgraphs](https://www.alchemy.com/subgraphs): A fast & reliable GraphQL API + +- [Alchemy Token API](https://www.alchemy.com/token-api): Complete token data, no token list required + +- [Alchemy Transfers API](https://www.alchemy.com/transfers-api): Retrieve all historical transaction activity, including internal transfers + +- [Alchemy Webhooks](https://www.alchemy.com/webhooks): Realtime notifications for your users + +- [Goldsky](https://goldsky.com/): Livestream onchain data to your database + +- [Reservoir](https://reservoir.tools/): From market data to metadata, Reservoir APIs provide all-in-one endpoints + +- [SimpleHash](https://simplehash.com/): Instant access to Token & NFT market prices, metadata and media diff --git a/public/tools/explorers.md b/public/tools/explorers.md new file mode 100644 index 0000000..0efcc5d --- /dev/null +++ b/public/tools/explorers.md @@ -0,0 +1,18 @@ +# Explorers + +| Explorer | Focus | +| --- | --- | +| Shapescan | Block explorer: transactions, contracts, verification | +| Shapescan Sepolia | Testnet block explorer | +| Deca | NFT explorer: collections, metadata, floor prices | +| Zapper | Portfolio and activity feed in a human-readable format | + +Verify your contracts on Shapescan to make them readable. See [Deploy a Contract](https://docs.shape.network/quick-start/deploy-a-contract.md) for verification steps. + +- [Shape Mainnet Explorer](https://shapescan.xyz/) + +- [Shape Sepolia Testnet Explorer](https://explorer-sepolia.shape.network/) + +- [Deca](https://deca.art/): See all NFTs on Shape in one place + +- [Zapper](https://zapper.xyz/): See what's happening onchain in a human readable way diff --git a/public/tools/faucets.md b/public/tools/faucets.md new file mode 100644 index 0000000..ce3eb10 --- /dev/null +++ b/public/tools/faucets.md @@ -0,0 +1,14 @@ +# Faucets + +Get free testnet ETH on Shape Sepolia for development. + +1. Go to the Alchemy or Optimism faucet +2. Sign in with an account (free tier works) +3. Enter your wallet address +4. Receive testnet ETH (usually within seconds) + +- [Alchemy Faucet](https://www.alchemy.com/faucets/shape-sepolia) + +- [Optimism Faucet](https://console.optimism.io/faucet) + +> You can also [bridge Sepolia ETH](https://docs.shape.network/tools/bridges.md) to get started. diff --git a/public/tools/node-providers.md b/public/tools/node-providers.md new file mode 100644 index 0000000..e3dd389 --- /dev/null +++ b/public/tools/node-providers.md @@ -0,0 +1,14 @@ +# Node Providers + +| Provider | Endpoint | Notes | +| --- | --- | --- | +| Public RPC | `https://mainnet.shape.network` | Rate-limited, not for production | +| Alchemy | `https://shape-mainnet.g.alchemy.com/v2/YOUR_KEY` | Higher limits, WebSocket, enhanced APIs | + +Sepolia: `https://sepolia.shape.network` (public) or `https://shape-sepolia.g.alchemy.com/v2/YOUR_KEY` (Alchemy). + +WebSocket: `wss://shape-mainnet.g.alchemy.com/v2/YOUR_KEY` + +The public RPC is rate-limited and not suitable for production. Use [Alchemy](https://www.alchemy.com/rpc/shape) (free tier available). + +- [Alchemy Supernode](https://www.alchemy.com/rpc/shape): A highly reliable RPC diff --git a/public/tools/oracles/gelato-vrf.md b/public/tools/oracles/gelato-vrf.md new file mode 100644 index 0000000..df12a76 --- /dev/null +++ b/public/tools/oracles/gelato-vrf.md @@ -0,0 +1,100 @@ +# Gelato VRF + +- **Mechanism**: Uses [Drand](https://drand.love/), a decentralized source for random numbers. +- **Benefits**: Provides genuine, verifiable random values for blockchain applications. + +## Applications of Gelato VRF + +- **Gaming and Gambling**: For fair outcomes in online games and decentralized gambling. +- **Decentralized Finance (DeFi)**: Random selections for lotteries in DeFi protocols. +- **NFT Generation**: Random trait generation for unique digital assets. +- **Protocol Decision Making**: Randomized selections for validators or jurors. + +## Steps to Set Up Gelato VRF + +1. **Set Up Development Environment**: Install either Foundry or Hardhat. +2. **Install Gelato VRF Contracts**: Use specific commands for Hardhat or Foundry. +3. **Inherit** `GelatoVRFConsumerBase` **Contract**: Incorporate it into your contract. +4. **Request Randomness**: Call `_requestRandomness()` function. +5. **Implement Callback Function**: Define how your contract handles the randomness response. +6. **Include** `dedicated msg.sender`: Essential for contract security and function. + +## Quick Start + +### Step 1: Set Up Your Development Environment + +Make sure you have Hardhat or Foundry ready for use. + +### Step 2: Install Gelato VRF Contracts + +For Hardhat, clone the repository and set up the environment. For Foundry, use the `forge install` command. + +### Step 3: Inherit GelatoVRFConsumerBase Contract + +Create a contract that inherits from **GelatoVRFConsumerBase**. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity 0.8.18; + +import {GelatoVRFConsumerBase} from "./GelatoVRFConsumerBase.sol"; + +contract YourContract is GelatoVRFConsumerBase { + // Your contract's code +} +``` + +### Step 4: Request Randomness + +To request randomness, call the \_requestRandomness() function. You should protect the call since it will take from your 1Balance. The data argument will be passed back to you by the W3F. + +```solidity +function requestRandomness(bytes memory data) external { + require(msg.sender == ...); + uint64 requestId = _requestRandomness(data); +} +``` + +### Step 5: Implement Callback Function + +```solidity +function _fulfillRandomness( + bytes32 randomness, + uint64 requestId, + bytes memory data +) internal override { + // Your implementation here +} +``` + +### Step 6: Include Dedicated msg.sender + +When you're ready to deploy your Gelato VRF-compatible contract, an important step is to include the dedicated msg.sender as a constructor parameter. This ensures that your contract is set up to work with the correct operator for fulfilling the randomness requests. It's crucial for ensuring that only authorized requests are processed. + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity 0.8.18; + +import {GelatoVRFConsumerBase} from "./GelatoVRFConsumerBase.sol"; + +contract YourContract is GelatoVRFConsumerBase { + constructor(address operator) + GelatoVRFConsumerBase(operator) { + // Additional initializations + } + + // The rest of your contract code +} +``` + +## Task Creation + +Upon deploying your contract, you will need to create a Gelato Task. This can be done via the [Gelato UI](https://app.gelato.network/). Next, you will be prompted to provide the address of the Request Contract to which the Gelato nodes should respond. Enter the address of your contract, and once all details have been correctly entered, proceed with launching your Gelato VRF instance. + +Now everytime you call the `_requestRandomness()` function, the Gelato nodes will respond with a random number that you can use in your contract. + +For more detailed information, refer to the [Gelato VRF documentation](https://docs.gelato.network/web3-services/vrf). + +![Gelato VRF 1](https://docs.shape.network/gelato-gui-1.webp) + +![Gelato VRF 2](https://docs.shape.network/gelato-gui-2.webp) diff --git a/public/tools/safes-asset-security.md b/public/tools/safes-asset-security.md new file mode 100644 index 0000000..a354046 --- /dev/null +++ b/public/tools/safes-asset-security.md @@ -0,0 +1,10 @@ +# Safes & Asset Security + +Manage high-value assets and team operations securely on Shape. + +- **Safe**: Multi-signature wallet for team treasuries, protocol governance, or any operation requiring multiple approvals. Shape's Safe is at [safe.shape.network](https://safe.shape.network/). +- **Delegate**: Prove NFT ownership or claim airdrops from a hot wallet without moving assets from cold storage. + +- [Safe](https://safe.shape.network/): A decentralized custody protocol and collective asset management platform + +- [Delegate](https://delegate.xyz/): Claim airdrops, mint NFTs, and prove ownership via your hot wallet diff --git a/public/tools/sybil-resistance.md b/public/tools/sybil-resistance.md new file mode 100644 index 0000000..9ebe430 --- /dev/null +++ b/public/tools/sybil-resistance.md @@ -0,0 +1,13 @@ +# Sybil Resistance + +Protect your app from bots and sybil attacks while preserving user privacy. + +- **Passport**: Privacy-preserving identity scoring. Good for gating access, weighting rewards, detecting bots. +- **Premint**: Allowlist management for mints. Good for curated drops, community-first launches. +- **Crossmint Verifiable Credentials**: Issue and verify credentials at scale. Good for KYC-lite, compliance, loyalty programs. + +- [Passport](https://app.passport.xyz/#/shape/): A tool for dApps to defend against sybils while preserving user privacy + +- [Premint](https://www.premint.xyz/): Create allowlists tailored to your requirements + +- [Crossmint Verifiable Credentials](https://www.crossmint.com/products/verifiable-credentials): Issue and verify credentials at scale diff --git a/public/tutorials/mint-nft-collection.md b/public/tutorials/mint-nft-collection.md new file mode 100644 index 0000000..1072b24 --- /dev/null +++ b/public/tutorials/mint-nft-collection.md @@ -0,0 +1,196 @@ +# Launch an NFT Collection on Shape + +Deploy an ERC-721 contract to Shape Sepolia, mint an NFT, and verify it on the block explorer. + +## Prerequisites + +- [Foundry](https://book.getfoundry.sh/getting-started/installation) installed +- Shape Sepolia ETH from the [Alchemy Faucet](https://www.alchemy.com/faucets/shape-sepolia) +- A wallet private key funded with testnet ETH + +## 1. Set Up the Project + +```bash +forge init my-nft && cd my-nft +rm src/Counter.sol test/Counter.t.sol script/Counter.s.sol +forge install OpenZeppelin/openzeppelin-contracts --no-commit +``` + +Add the `remappings` line to `foundry.toml`: + +```toml +[profile.default] +src = "src" +out = "out" +libs = ["lib"] +remappings = ["@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/"] +``` + +## 2. Write the Contract + +Create `src/MyNFT.sol`: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; + +contract MyNFT is ERC721, Ownable { + uint256 public totalSupply; + uint256 public constant MAX_SUPPLY = 1000; + string private _baseTokenURI; + + constructor() ERC721("MyNFT", "MNFT") Ownable(msg.sender) {} + + function mint(address to) external onlyOwner { + require(totalSupply < MAX_SUPPLY, "Max supply reached"); + _mint(to, totalSupply); + totalSupply++; + } + + function setBaseURI(string calldata baseURI) external onlyOwner { + _baseTokenURI = baseURI; + } + + function _baseURI() internal view override returns (string memory) { + return _baseTokenURI; + } +} +``` + +## 3. Test + +Create `test/MyNFT.t.sol`: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +import {Test} from "forge-std/Test.sol"; +import {MyNFT} from "../src/MyNFT.sol"; + +contract MyNFTTest is Test { + MyNFT nft; + + function setUp() public { + nft = new MyNFT(); + } + + function test_mint() public { + nft.mint(address(this)); + assertEq(nft.ownerOf(0), address(this)); + assertEq(nft.totalSupply(), 1); + } +} +``` + +```bash +forge test +``` + +## 4. Deploy to Shape Sepolia + +```bash +export PRIVATE_KEY= + +forge create src/MyNFT.sol:MyNFT \ + --rpc-url https://sepolia.shape.network \ + --private-key $PRIVATE_KEY +``` + +Save the `Deployed to` address from the output. + +## 5. Mint an NFT + +```bash +cast send "mint(address)" \ + --rpc-url https://sepolia.shape.network \ + --private-key $PRIVATE_KEY +``` + +Confirm the mint: + +```bash +cast call "ownerOf(uint256)" 0 \ + --rpc-url https://sepolia.shape.network +``` + +This returns your address (ABI-encoded, zero-padded to 32 bytes). + +## 6. Optional: Let Users Mint From Another Chain + +If your mint UI should let users start from Ethereum, Base, Arbitrum, or another supported chain, use Relay cross-chain call execution. The UI can let the user pay from an origin-chain balance while Relay executes the NFT mint call on Shape. + +The most important contract detail is to mint to an explicit recipient, like `mint(address to)`, instead of relying only on `msg.sender`. Relay's Shape-side address executes the destination call, so your UI should encode the buyer's address into the mint calldata and your contract should allow the Relay address to call that mint path. Treat this as a narrow exception: most arbitrary addresses should still be blocked from minting this way, but the Relay executor or relayer address you configure for Shape needs permission to call the function and mint the NFT to the recipient. + +```ts +import { getClient } from '@relayprotocol/relay-sdk'; +import { encodeFunctionData, parseEther, zeroAddress } from 'viem'; + +const relayClient = getClient(); +const shapeSepoliaChainId = 11011; // Use 360 for Shape mainnet. +const mintPrice = parseEther('0.01'); + +const callData = encodeFunctionData({ + abi: nftAbi, + functionName: 'mint', + args: [userAddress], +}); + +const quote = await relayClient.actions.getQuote({ + wallet, + chainId: originChainId, + toChainId: shapeSepoliaChainId, + currency: zeroAddress, + toCurrency: zeroAddress, + user: userAddress, + recipient: userAddress, + amount: mintPrice.toString(), + tradeType: 'EXACT_OUTPUT', + txs: [ + { + to: nftContractAddress, + value: mintPrice.toString(), + data: callData, + }, + ], +}); + +await relayClient.actions.execute({ + quote, + wallet, + onProgress: (progress) => { + // Use this to show states like: + // confirm in wallet -> origin transaction submitted -> relaying -> minted + }, +}); +``` + +For a free mint, set the mint transaction `value` and quote `amount` to `"0"`. For a paid mint, use `EXACT_OUTPUT` with the exact ETH value your mint call requires on Shape. Keep quotes fresh, check the user's origin-chain balance before enabling the mint button, and show a clear error if Relay has insufficient liquidity or the user lacks enough ETH for the amount, Relay fees, and origin-chain gas. + +The Stack mint UI uses the same pattern, with one extra convenience: users can optionally send additional ETH to themselves on Shape in the same Relay execution. That is just a second transaction in `txs` and is useful for onboarding, but most mint UIs only need the Shape contract call. + +See Relay's [Call Execution Integration Guide](https://docs.relay.link/references/api/api_guides/calling-integration-guide#common-use-cases) for the full quote, execution, and status flow. + +## 7. Verify on Shapescan + +```bash +forge verify-contract src/MyNFT.sol:MyNFT \ + --verifier blockscout \ + --verifier-url https://sepolia.shapescan.xyz/api/ +``` + +Once verified, view your contract at `https://sepolia.shapescan.xyz/address/`. + +## 8. Register for Gasback + +Register your contract for [Gasback](https://docs.shape.network/tutorials/registering-contract-gasback/index.md) to reclaim 80% of sequencer fees users spend interacting with it. + +## Next Steps + +- **Deploy to mainnet**: Use `--rpc-url https://mainnet.shape.network` and verify against `https://shapescan.xyz/api/` +- **View on Deca**: Once on mainnet, see your collection at `https://deca.art/token/shape//` +- **Add metadata**: Upload JSON metadata to IPFS with [Pinata](https://pinata.cloud/), then call `setBaseURI` to point your tokens at it +- [Build a dApp](https://docs.shape.network/building-on-shape/builder-kit.md) with the Shape Builder Kit diff --git a/public/tutorials/registering-contract-gasback/dashboard.md b/public/tutorials/registering-contract-gasback/dashboard.md new file mode 100644 index 0000000..4a97437 --- /dev/null +++ b/public/tutorials/registering-contract-gasback/dashboard.md @@ -0,0 +1,65 @@ +# Registering via the Dashboard + +This tutorial will guide you through the process of registering your smart contract for gasback using the Gasback Dashboard UI. + +## Prerequisites + +1. Your smart contract must be deployed on Shape. +2. You need access to a Web3 wallet (like MetaMask) with the account that owns the smart contract you want to register. +3. Your smart contract must have an owner() function which returns the address of the account you will connect to the dashboard + +## Step 1: Access the Dashboard + +Open your web browser and navigate to the [Gasback dashboard](https://gasback.shape.network/). + +![Gasback Dashboard](https://docs.shape.network/gasback-dashboard-1.webp) + +## Step 2: Connect Your Wallet + +1. Click the "Connect Wallet" button in the top right corner of the page. +2. A popup will appear with various wallet options. Select your preferred wallet (e.g., MetaMask). +3. Follow the prompts in your wallet to connect to the site and select the account you want to use. + +![Connect Wallet](https://docs.shape.network/gasback-dashboard-2.webp) + +## Step 3: View Your Gasback Dashboard + +1. Once connected, you'll see your Gasback dashboard. +2. If you haven't registered any contracts yet, you'll see a hero banner explaining that you don't have a gasback NFT yet. + +![Gasback Dashboard](https://docs.shape.network/gasback-dashboard-3.webp) + +## Step 4: Initiate registration and enter contract details + +1. Click the "Register" button in the hero banner or the header. and a popup window titled "Register a new smart contract" will appear. +2. In the "Contract Address" field, enter the address of the smart contract you want to register for gasback. +3. The "NFT Recipient" field should automatically populate with your connected wallet address. This is the address that will receive the gasback NFT. You can change this if you want the NFT to go to a different address. +4. Click “Register” + +![Register Contract](https://docs.shape.network/gasback-dashboard-4.webp) + +## Step 5: Confirm Registration + +1. Read the warning message and double-check that all the information is correct. +2. Click the "Confirm" button. +3. Your wallet will prompt you to confirm the transaction. Review the details and confirm the transaction. +4. Wait for the transaction to be processed and confirmed on the blockchain. + +![Confirm Registration](https://docs.shape.network/gasback-dashboard-5.webp) + +## Step 6: Verify Registration + +1. After the transaction is confirmed, the dashboard should update to reflect your newly registered contract. +2. You did it! You should see your unique gasback NFT that was generated onchain. The art on your NFT will evolve as your token accrues gasback. + +![Verify Registration](https://docs.shape.network/gasback-dashboard-6.webp) + +## Step 7: Managing Your Gasback + +Your dashboard will now display any gasback activity related to your registered contract. Activity can take up to 10 minutes to show up here. Registration itself earns you gasback, so you've already started your journey! + +If you have more contracts you want to register for Gasback, you can click the “manage” button and add their contract addresses to the field, and all the gasback earned by those contracts will be claimable with a single NFT. + +![Manage Gasback](https://docs.shape.network/gasback-dashboard-7.webp) + +That's it! If you're less of a UI person, check out the next section to see how to do this programmatically. diff --git a/public/tutorials/registering-contract-gasback/index.md b/public/tutorials/registering-contract-gasback/index.md new file mode 100644 index 0000000..41d3233 --- /dev/null +++ b/public/tutorials/registering-contract-gasback/index.md @@ -0,0 +1,7 @@ +# Registering Your Contract for Gasback + +There are two different methods to register your contract for Gasback registration. You can either use the UI, or register programmatically from the contract you wish to register. This section has tutorials on how to do each approach. + +- [Using the dashboard](https://docs.shape.network/tutorials/registering-contract-gasback/dashboard.md) + +- [Programmatically](https://docs.shape.network/tutorials/registering-contract-gasback/programmatically.md) diff --git a/public/tutorials/registering-contract-gasback/programmatically.md b/public/tutorials/registering-contract-gasback/programmatically.md new file mode 100644 index 0000000..9dcaa67 --- /dev/null +++ b/public/tutorials/registering-contract-gasback/programmatically.md @@ -0,0 +1,168 @@ +# Registering Programmatically + +This tutorial will guide you through the process of registering your smart contract for gasback programmatically. The tutorial walks through 3 different approaches you can use, with full example contracts. + +## Prerequisites + +1. Some familiarity with Solidity and Node JS. +2. If you want to actually deploy the contracts we'll go through so that you can get hands on, download the example repo [here](https://github.com/shape-network/gasback-tutorial). +3. (Optional) If you do decide to deploy the contracts and register, you'll need some Shape Sepolia ETH which you can get from the [Alchemy faucet](https://www.alchemy.com/faucets/shape-sepolia) or the [Superchain faucet](https://console.optimism.io/faucet). You will then need to create a `.env` file according to the `.env.example` file in the repo. + +## Example A: Registering inside the contract and sending the Gasback NFT to the contract owner to hold + +The code snippet below is the complete implementation of a contract called ExampleA, that we'll use for the first example. + +A is an Ownable contract, which means external callers can call an `owner()` method to determine which address has control over the contract. + +```solidity filename="ExampleA.sol" +pragma solidity 0.8.20; + +import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; +import {IGasback} from "./interfaces/IGasback.sol"; + +contract ExampleA is Ownable { + IGasback public gasback; + + constructor(address _gasback) Ownable(msg.sender) { + gasback = IGasback(_gasback); + } + + function registerForGasback() public onlyOwner { + gasback.register(owner(), address(this)); + } +} +``` + +As you can see, registration happens in one line, on line 14: `gasback.register(owner(), address(this));`. This says, register this address for gasback, and send the NFT to the owner of this contract. + +Inside the Gasback.sol contract (not shown), the `owner()` function of the contract that is registering gets called, so that the Gasback contract knows that the person due to receive the Gasback NFT is the person who controls the registering contract. + +> Warning: +> +> If your contract tries to register in the constructor, the call will fail. Registration must +> happen after contract construction. + +To deploy the contract above run: + +```bash +npx hardhat deployA --network shapeSepolia +``` + +You'll then see the deployed address in the console. + +To run the registration function, run: + +```bash +npx hardhat registerA --network shapeSepolia +``` + +Where the deployed address is the address printed in the deployment command. + +Once that's done, you can actually visit the [Gasback dashboard](https://gasback.shape.network/) and see your new Gasback NFT! + +## Example B: Registering inside a contract without requiring an owner + +```solidity filename="ExampleB.sol" +pragma solidity 0.8.20; + +import {IGasback} from "./interfaces/IGasback.sol"; +import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; + +contract ExampleB is IERC721Receiver { + IGasback public gasback; + + constructor(address _gasback) { + gasback = IGasback(_gasback); + } + + function registerForGasback() public { + address me = address(this); + gasback.register(me, me); + } + + function onERC721Received( + address operator, + address from, + uint256 tokenId, + bytes calldata data + ) external override returns (bytes4) { + return IERC721Receiver.onERC721Received.selector; + } +} +``` + +Contract B differs from A in a couple of key ways. Firstly, you'll notice that ExampleB is not an Ownable contract. The reason it's still able to register despite this, is that the contract itself is going to be the recipient of the Gasback NFT. This means we don't have to check an owner, because it's clearly registering itself. + +The second key change is the addition of the `onERC721Received` function. This inclusion is needed because Gasback.sol uses `_safeMint` to mint the NFT, which requires that any contract that receives the NFT implements this function, so that we know the NFT won't be stuck forever inside the contract, and the contract is actually expecting to receive and handle NFTs. + +> Warning: +> +> When implementing this pattern a function protected by some form of access control that +> withdraws the NFT from your contract is a great fallback option. + +Similar to example A you can deploy and run the registration function yourself by doing: + +```bash +npx hardhat deployB --network shapeSepolia +``` + +and + +```bash +npx hardhat registerB --network shapeSepolia +``` + +However in this example you won't see the NFT in your dashboard yet because you aren't the owner of it, the contract is! We'll explain how you can still manage the NFT that one of your contracts holds in a later tutorial, when we discuss the concept of **Delegation**. + +## Example C: Registering outside of a contract + +```solidity filename="ExampleC.sol" +pragma solidity 0.8.20; + +import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; + +contract ExampleC is Ownable { + constructor() Ownable(msg.sender) {} +} +``` + +The final example is a tiny contract. It has no logic in it other than to make itself Ownable. But, we can still register it for Gasback! + +The registration logic happens outside of the contract. All you have to do is call the registration on the Gasback contract directly, entering your own address as the NFT recipient and the contract address. + +You can see how this is done in `scripts/register.ts` in the registerC task: + +```typescript +task('registerC', 'Registers the ExampleC contract for gasback') + .addPositionalParam('contractAddress', 'The address of the ExampleC contract to register') + .setAction(async (taskArgs, hre) => { + const { contractAddress } = taskArgs; + + const [address] = await hre.ethers.getSigners(); + + const gasback = await hre.ethers.getContractAt('Gasback', gasbackAddress); + + const tx = await gasback.register(address, contractAddress); + await tx.wait(1); + + console.log('ExampleC registered! Tx hash: ', tx.hash); + }); +``` + +Of course, as proof it works, you can deploy and register using similar commands as before: + +```bash +npx hardhat deployC --network shapeSepolia +``` + +and + +```bash +npx hardhat registerC --network shapeSepolia +``` + +If you want an easy way to do this method, you can simply use the Gasback dashboard UI, connect your wallet, and paste in the contract address. The UI will make the contract call for you. + +## Summary + +That's it! You have now learned 3 different ways to register your contract for Gasback. In the next tutorials, we'll discuss how to delegate gasback rights when your contract owns the NFT instead of you, and we'll learn how to withdraw claimed gasback. diff --git a/public/wallet-setup.md b/public/wallet-setup.md new file mode 100644 index 0000000..b434e3b --- /dev/null +++ b/public/wallet-setup.md @@ -0,0 +1,25 @@ +# Wallet Setup + +Set up your wallet on Shape. + +## 1. Add Shape to Your Wallet + +1. Go to the [Shape website](https://shape.network/) +2. Scroll down to the "Get Started" section and click "Add Shape Mainnet" +3. You'll be prompted to switch to the Shape network + - If the network isn't listed, you can [add it manually](https://docs.shape.network/technical-details/network-information.md) + +## 2. Bridge to Shape + +1. Choose a [bridge](https://shape.network/bridge) to Shape +2. Send ETH over to Shape from another chain +3. Once complete, check your ETH balance on Shape + - If you don't see your balance, make sure your wallet is connected to the Shape network + +## 3. Mint Your Stack + +Build your onchain reputation on Shape by earning medals with the Stack. It's also the most effective way to claim more $SHAPE. + +[Mint your Stack](https://stack.shape.network/) + +More on the Stack in the next section. diff --git a/scripts/generate-ai-docs.mjs b/scripts/generate-ai-docs.mjs new file mode 100644 index 0000000..099e52a --- /dev/null +++ b/scripts/generate-ai-docs.mjs @@ -0,0 +1,295 @@ +import { readFile, readdir, mkdir, writeFile, rm } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ORIGIN = 'https://docs.shape.network'; +const decode = (text) => + text.replace( + /&(apos|quot|amp|lt|gt|nbsp);/g, + (_, key) => ({ apos: "'", quot: '"', amp: '&', lt: '<', gt: '>', nbsp: ' ' })[key] + ); + +// Protect code before processing MDX: imports and JSX inside examples are content. +export function protectCode(text) { + const saved = []; + const save = (value) => { + saved.push(value); + return `\u0000CODE${saved.length - 1}\u0000`; + }; + let fence; + let block = []; + const lines = []; + for (const line of text.split('\n')) { + const marker = line.match(/^ {0,3}(`{3,}|~{3,})/); + if (!fence && marker) { + fence = marker[1]; + block = [line]; + } else if (fence) { + block.push(line); + if ( + marker && + marker[1][0] === fence[0] && + marker[1].length >= fence.length && + /^ {0,3}(`{3,}|~{3,})\s*$/.test(line) + ) { + lines.push(save(block.join('\n'))); + fence = undefined; + } + } else lines.push(line); + } + if (fence) throw new Error('Unclosed code fence'); + const protectedText = lines.join('\n').replace(/(`+)([^\n]*?)\1/g, save); + return { + text: protectedText, + restore: (value) => value.replace(/\u0000CODE(\d+)\u0000/g, (_, index) => saved[Number(index)]), + }; +} + +function attr(attributes, name, paths) { + const literal = attributes.match(new RegExp(`\\b${name}="([^"]*)"`)); + if (literal) return decode(literal[1]); + const ref = attributes.match(new RegExp(`\\b${name}=\\{paths\\.(\\w+)\\}`)); + if (ref && paths[ref[1]]) return paths[ref[1]]; + throw new Error(`Unsupported or missing ${name}: ${attributes}`); +} + +function renderJsx(text, components, paths) { + text = text.replace(/<([A-Z]\w*)\s*\/>/g, (_, name) => { + if (!(name in components)) throw new Error(`Unsupported component: ${name}`); + return renderJsx(components[name], components, paths); + }); + text = text.replace(//g, (_, attributes) => { + const title = attr(attributes, 'title', paths); + const href = attr(attributes, 'href', paths); + const subtitle = /\bsubtitle=/.test(attributes) + ? `: ${attr(attributes, 'subtitle', paths)}` + : ''; + return `\n- [${title}](${href})${subtitle}\n`; + }); + text = text.replace( + /([\s\S]*?)<\/Link>/g, + (_, attributes, label) => + `[${label.trim().replace(/\s+/g, ' ')}](${attr(attributes, 'href', paths)})` + ); + text = text + .replace(/<\/?Cards>/g, '') + .replace(//g, '\n') + .replace(/\{' '\}/g, ' '); + text = text.replace( + /([\s\S]*?)<\/Callout>/g, + (_, type, body) => + '\n' + + (type === 'warning' ? '> Warning:\n>\n' : '') + + body + .trim() + .split('\n') + .map((line) => '> ' + line.trim()) + .join('\n') + + '\n' + ); + if (/<\/?[A-Za-z][^>]*>/.test(text)) throw new Error('Unconverted JSX/HTML in document'); + return decode(text); +} + +export function convert( + source, + { components = {}, paths = {}, routes = new Map(), route = '/' } = {} +) { + const code = protectCode(source); + let text = code.text.replace(/^---\n[\s\S]*?\n---\n/, ''); + text = text.replace(/^import\s+[\s\S]*?;\s*$/gm, ''); + text = renderJsx(text, components, paths); + text = text.replace(/\]\(([^\s)]+)\)/g, (_, href) => { + if (href.startsWith('#')) return `](${href})`; + const url = new URL(href, ORIGIN + route); + if (url.origin === ORIGIN) { + const markdown = routes.get(url.pathname.replace(/\/$/, '') || '/'); + if (markdown) url.pathname = markdown; + else if (!path.extname(url.pathname)) throw new Error(`Unmapped internal link: ${href}`); + } + return `](${url.href})`; + }); + return ( + code.restore( + text + .replace(/[ \t]+$/gm, '') + .replace(/\n{3,}/g, '\n\n') + .trim() + ) + '\n' + ); +} + +async function walk(directory) { + const result = []; + for (const entry of await readdir(directory, { withFileTypes: true })) { + const full = path.join(directory, entry.name); + if (entry.isDirectory()) result.push(...(await walk(full))); + else if (/\.mdx?$/.test(entry.name)) result.push(full); + } + return result.sort(); +} + +export async function generate(root) { + const content = path.join(root, 'content'); + const publicDir = path.join(root, 'public'); + const pathsSource = await readFile(path.join(root, 'paths.ts'), 'utf8'); + const paths = Object.fromEntries( + [...pathsSource.matchAll(/(\w+):\s*'([^']*)'/g)].map((match) => [match[1], match[2]]) + ); + const components = {}; + for (const name of ['cards.tsx', 'callouts.tsx']) { + const source = await readFile(path.join(root, 'components', name), 'utf8'); + for (const match of source.matchAll( + /export const (\w+)[\s\S]*?return \(([\s\S]*?)\n \);\n};/g + )) + components[match[1]] = match[2]; + } + const records = (await walk(content)).map((file) => { + const relative = path + .relative(content, file) + .replaceAll(path.sep, '/') + .replace(/\.mdx?$/, ''); + const route = '/' + relative.replace(/(^|\/)index$/, ''); + return { file, route: route.replace(/\/$/, '') || '/', markdown: '/' + relative + '.md' }; + }); + const routes = new Map(records.map((record) => [record.route, record.markdown])); + if (routes.size !== records.length) throw new Error('Duplicate content routes'); + const rendered = []; + for (const record of records) { + const source = await readFile(record.file, 'utf8'); + const body = convert(source, { components, paths, routes, route: record.route }); + const title = body.match(/^# (.+)$/m)?.[1]; + if (!title) throw new Error(`Missing title: ${record.file}`); + const descriptions = { + '/technical-details/network-information': + 'Mainnet and testnet chain IDs, ETH gas currency, RPC endpoints, and explorers.', + '/technical-details/contract-addresses': + 'Official network infrastructure contract addresses.', + '/the-stack': + 'Dynamic NFT achievements, participation, and medals across the Shape ecosystem.', + '/tutorials/registering-contract-gasback': + 'Choose dashboard or programmatic contract registration for Gasback.', + '/building-on-shape/ai': + 'Shape MCP, AI integration examples, and agent development guidance.', + '/tools/node-providers': 'Public and provider RPC endpoints for mainnet and testnet.', + '/tools/data-indexers': 'NFT queries, indexing services, and data APIs.', + '/tools/oracles/gelato-vrf': + 'Request verifiable randomness from smart contracts using Gelato VRF.', + }; + const paragraph = body + .split('\n\n') + .map((block) => block.trim()) + .find((block) => block && !/^(#|>|-|\d+\.|\||`|~)/.test(block)); + let description = (descriptions[record.route] || paragraph || 'Documentation for ' + title) + .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1') + .replace(/[*`]/g, '') + .replace(/\s+/g, ' ') + .trim(); + if (description.length > 220) + description = description.slice(0, 217).replace(/\s+\S*$/, '') + '...'; + rendered.push({ ...record, title, description, body }); + } + + // Remove only previously generated pages, so deleted source pages cannot linger. + const manifestPath = path.join(publicDir, '.ai-docs-manifest.json'); + let previous = []; + try { + previous = JSON.parse(await readFile(manifestPath, 'utf8')); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + } + for (const relative of previous) { + const target = path.resolve(publicDir, relative); + if (!target.startsWith(path.resolve(publicDir) + path.sep) || !relative.endsWith('.md')) + throw new Error('Invalid generated file manifest'); + await rm(target, { force: true }); + } + await mkdir(publicDir, { recursive: true }); + for (const record of rendered) { + const file = path.join(publicDir, record.markdown); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, record.body); + } + const sections = [ + [ + 'Start Here', + ['/', '/wallet-setup', '/quick-start', '/technical-details/network-information'], + ], + [ + 'Gasback and Fees', + [ + '/gasback', + '/building-on-shape/transaction-fees', + '/tutorials/registering-contract-gasback', + ], + ], + [ + 'Build Applications', + [ + '/quick-start/connect-to-shape', + '/quick-start/deploy-a-contract', + '/building-on-shape/builder-kit', + '/tutorials/mint-nft-collection', + '/building-on-shape/ai', + ], + ], + [ + 'Explore and Operate', + [ + '/the-stack', + '/technical-details/contract-addresses', + '/technical-details/run-a-node', + '/building-on-shape/differences-ethereum-shape', + ], + ], + ]; + const used = new Set(); + let index = + '# Shape Documentation\n\n> Official technical documentation for Shape, an Ethereum L2 built on the OP Stack and part of the Optimism Superchain.\n\n' + + 'Mainnet chain ID: 360. Shape Sepolia chain ID: 11011. Gas currency: ETH. Gasback shares 80% of L2 sequencer fees with registered contract owners, excluding L1 data fees.\n\n' + + 'Links below lead to Markdown generated from the same source as the website. Follow the relevant pages for full context. For current $SHAPE token and governance information, see https://shape.network/token.\n\n'; + for (const [title, entries] of [ + ...sections, + ['Tools and Further Reading', rendered.map((record) => record.route)], + ]) { + const selected = entries.filter((route) => !used.has(route)); + index += `## ${title}\n\n`; + for (const route of selected) { + const record = rendered.find((record) => record.route === route); + if (!record) throw new Error(`Missing curated route: ${route}`); + used.add(route); + index += `- [${record.title}](${ORIGIN}${record.markdown}): ${record.description}\n`; + } + index += '\n'; + } + index += + '## Optional\n\n- [All technical documentation](' + + ORIGIN + + '/llms-full.txt): All generated pages in one file. Use individual pages for narrower questions.\n'; + await writeFile(path.join(publicDir, 'llms.txt'), index); + const full = + '# Shape Technical Documentation\n\nGenerated from the official documentation source. This is the technical corpus; token and governance information is maintained at https://shape.network/token.\n\n' + + rendered + .map( + (record) => + `---\n\nCanonical page: ${ORIGIN}${record.route}\nMarkdown page: ${ORIGIN}${record.markdown}\n\n${record.body}` + ) + .join('\n'); + await writeFile(path.join(publicDir, 'llms-full.txt'), full); + await writeFile( + manifestPath, + JSON.stringify( + rendered.map((record) => record.markdown.slice(1)), + null, + 2 + ) + '\n' + ); + return { pages: rendered.length, bytes: Buffer.byteLength(full) }; +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const result = await generate(path.resolve(process.argv[2] || '.')); + console.log( + `Generated ${result.pages} Markdown pages, llms.txt, and llms-full.txt (${result.bytes} bytes).` + ); +} diff --git a/scripts/generate-ai-docs.test.mjs b/scripts/generate-ai-docs.test.mjs new file mode 100644 index 0000000..56aebb5 --- /dev/null +++ b/scripts/generate-ai-docs.test.mjs @@ -0,0 +1,69 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { convert, generate } from './generate-ai-docs.mjs'; +import { readFile } from 'node:fs/promises'; +import path from 'node:path'; + +test('code examples retain imports, JSX, placeholders, and exports', () => { + const source = + '# Test\n\n```tsx\nimport { x } from "x";\nexport const a = ;\n```\n\nKeep `
` as a placeholder.\n'; + assert.equal(convert(source), source); +}); +test('multiline MDX imports and frontmatter are removed', () => { + const source = '---\ntitle: Test\n---\nimport {\n A, B\n} from "components";\n\n# Test\n'; + assert.equal(convert(source), '# Test\n'); +}); +test('cards keep descriptions and target generated Markdown', () => { + const output = convert('# Test\n', { + routes: new Map([['/next', '/next.md']]), + }); + assert.match(output, /\[Next\]\(https:\/\/docs.shape.network\/next.md\): Details/); +}); +test('component warnings and source-driven links survive', () => { + const output = convert('# Test\n', { + components: { + Warning: + 'Do not register in the constructor. Help', + }, + paths: { help: 'https://example.com/help' }, + }); + assert.match(output, /> Warning:/); + assert.match(output, /Do not register in the constructor/); + assert.match(output, /\[Help\]\(https:\/\/example.com\/help\)/); +}); +test('unsupported components, broken internal links, and broken fences fail loudly', () => { + assert.throws(() => convert('# Test\n'), /Unsupported component/); + assert.throws(() => convert('# Test\n[Lost](/missing)'), /Unmapped internal link/); + assert.throws(() => convert('# Test\n```ts\nbroken'), /Unclosed code fence/); +}); +test('fragment links and HTML entities are preserved correctly', () => { + assert.equal(convert('# Test\n\nIt's [here](#test).\n'), "# Test\n\nIt's [here](#test).\n"); +}); + +// Optional integration test against the actual repository, not fabricated content. +const repo = process.env.SHAPE_DOCS_TEST_ROOT; +if (repo) + test('every source code block is preserved and generation is deterministic', async () => { + const { pages } = await generate(repo); + const manifest = JSON.parse( + await readFile(path.join(repo, 'public/.ai-docs-manifest.json'), 'utf8') + ); + assert.equal(manifest.length, pages); + const files = new Set(manifest); + const originalIndex = await readFile(path.join(repo, 'public/llms.txt'), 'utf8'); + const blocks = (value) => value.match(/^(`{3,}|~{3,})[^\n]*\n[\s\S]*?^\1\s*$/gm) || []; + for (const relative of manifest) { + const output = await readFile(path.join(repo, 'public', relative), 'utf8'); + const source = await readFile( + path.join(repo, 'content', relative.replace(/\.md$/, '.mdx')), + 'utf8' + ); + assert.deepEqual(blocks(output), blocks(source), relative); + for (const match of output.matchAll( + /\]\(https:\/\/docs\.shape\.network\/([^\s)]+\.md)(?:#[^)]*)?\)/g + )) + assert.ok(files.has(match[1]), `${relative}: missing ${match[1]}`); + } + await generate(repo); + assert.equal(await readFile(path.join(repo, 'public/llms.txt'), 'utf8'), originalIndex); + }); From 327141ef7989f12d93318beb7e2a6503d1027c79 Mon Sep 17 00:00:00 2001 From: pravijndeca Date: Fri, 2 Oct 2026 10:26:10 -0700 Subject: [PATCH 2/3] Generate AI documentation at build time from canonical content --- .gitignore | 6 + README.md | 2 +- app/[[...mdxPath]]/page.tsx | 6 +- package.json | 2 +- public/.ai-docs-manifest.json | 34 - public/building-on-shape/ai.md | 119 - public/building-on-shape/alchemy-api.md | 10 - public/building-on-shape/builder-kit.md | 100 - .../differences-ethereum-shape.md | 36 - .../onchain-compatible/assembly.md | 335 --- .../onchain-compatible/index.md | 9 - .../onchain-compatible/otom.md | 238 -- .../superchain-incentives.md | 13 - public/building-on-shape/transaction-fees.md | 94 - public/gasback.md | 24 - public/index.md | 36 - public/llms-full.txt | 2613 ----------------- public/llms.txt | 58 - public/quick-start/connect-to-shape.md | 76 - public/quick-start/deploy-a-contract.md | 66 - public/quick-start/index.md | 16 - .../technical-details/contract-addresses.md | 111 - .../technical-details/network-information.md | 22 - public/technical-details/run-a-node.md | 354 --- public/the-stack.md | 52 - public/tools/account-abstraction.md | 25 - public/tools/bridges.md | 17 - public/tools/data-indexers.md | 35 - public/tools/explorers.md | 18 - public/tools/faucets.md | 14 - public/tools/node-providers.md | 14 - public/tools/oracles/gelato-vrf.md | 100 - public/tools/safes-asset-security.md | 10 - public/tools/sybil-resistance.md | 13 - public/tutorials/mint-nft-collection.md | 196 -- .../registering-contract-gasback/dashboard.md | 65 - .../registering-contract-gasback/index.md | 7 - .../programmatically.md | 168 -- public/wallet-setup.md | 25 - scripts/generate-ai-docs.mjs | 26 +- 40 files changed, 18 insertions(+), 5147 deletions(-) delete mode 100644 public/.ai-docs-manifest.json delete mode 100644 public/building-on-shape/ai.md delete mode 100644 public/building-on-shape/alchemy-api.md delete mode 100644 public/building-on-shape/builder-kit.md delete mode 100644 public/building-on-shape/differences-ethereum-shape.md delete mode 100644 public/building-on-shape/onchain-compatible/assembly.md delete mode 100644 public/building-on-shape/onchain-compatible/index.md delete mode 100644 public/building-on-shape/onchain-compatible/otom.md delete mode 100644 public/building-on-shape/superchain-incentives.md delete mode 100644 public/building-on-shape/transaction-fees.md delete mode 100644 public/gasback.md delete mode 100644 public/index.md delete mode 100644 public/llms-full.txt delete mode 100644 public/llms.txt delete mode 100644 public/quick-start/connect-to-shape.md delete mode 100644 public/quick-start/deploy-a-contract.md delete mode 100644 public/quick-start/index.md delete mode 100644 public/technical-details/contract-addresses.md delete mode 100644 public/technical-details/network-information.md delete mode 100644 public/technical-details/run-a-node.md delete mode 100644 public/the-stack.md delete mode 100644 public/tools/account-abstraction.md delete mode 100644 public/tools/bridges.md delete mode 100644 public/tools/data-indexers.md delete mode 100644 public/tools/explorers.md delete mode 100644 public/tools/faucets.md delete mode 100644 public/tools/node-providers.md delete mode 100644 public/tools/oracles/gelato-vrf.md delete mode 100644 public/tools/safes-asset-security.md delete mode 100644 public/tools/sybil-resistance.md delete mode 100644 public/tutorials/mint-nft-collection.md delete mode 100644 public/tutorials/registering-contract-gasback/dashboard.md delete mode 100644 public/tutorials/registering-contract-gasback/index.md delete mode 100644 public/tutorials/registering-contract-gasback/programmatically.md delete mode 100644 public/wallet-setup.md diff --git a/.gitignore b/.gitignore index 2708fdb..eb02267 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,9 @@ node_modules .env _pagefind/ .claude/settings.local.json + +# Generated from content/ at build time +/public/llms.txt +/public/llms-full.txt +/public/.ai-docs-manifest.json +/public/**/*.md diff --git a/README.md b/README.md index 65fad71..e77bd6c 100644 --- a/README.md +++ b/README.md @@ -52,4 +52,4 @@ bun run test:ai-docs Edit the MDX source or shared components, then regenerate the assets. Do not edit generated Markdown directly. The converter handles the current static MDX patterns and stops on unknown components, unclosed code fences, or unmapped documentation links. Add conversion support and a test when introducing a new MDX component. Fenced code blocks are preserved verbatim. -Generated files under `public/` are committed so previews and local development can read them before a production build. Regenerate them with source changes. `.ai-docs-manifest.json` records the generated page paths so deleted pages are removed on regeneration and HTML alternatives use the same route map. +Generated files under `public/` are ignored by Git. Both development and production scripts generate them from the existing source before starting Next.js. `.ai-docs-manifest.json` records the generated page paths so deleted pages are removed on regeneration and HTML alternatives use the same route map. Titles, summaries, examples, and component text come from the original content; only navigation grouping is configured in the generator. diff --git a/app/[[...mdxPath]]/page.tsx b/app/[[...mdxPath]]/page.tsx index 28119ea..bf0fb5f 100644 --- a/app/[[...mdxPath]]/page.tsx +++ b/app/[[...mdxPath]]/page.tsx @@ -1,4 +1,5 @@ -import markdownPages from '../../public/.ai-docs-manifest.json'; +import { readFile } from 'node:fs/promises'; +import path from 'node:path'; import { generateStaticParamsFor, importPage } from 'nextra/pages'; import { useMDXComponents as getMDXComponents } from '../../mdx-components'; @@ -7,6 +8,9 @@ export const generateStaticParams = generateStaticParamsFor('mdxPath'); export async function generateMetadata(props) { const params = await props.params; const { metadata } = await importPage(params.mdxPath); + const markdownPages: string[] = JSON.parse( + await readFile(path.join(process.cwd(), 'public/.ai-docs-manifest.json'), 'utf8') + ); const segments = params.mdxPath || []; const route = '/' + segments.join('/'); const indexes = new Set( diff --git a/package.json b/package.json index 3ced691..2954a92 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "scripts": { - "dev": "next dev", + "dev": "node scripts/generate-ai-docs.mjs && next dev", "build": "node scripts/generate-ai-docs.mjs && next build", "start": "next start", "postbuild": "pagefind --site .next/server/app --output-path public/_pagefind", diff --git a/public/.ai-docs-manifest.json b/public/.ai-docs-manifest.json deleted file mode 100644 index 54c46e2..0000000 --- a/public/.ai-docs-manifest.json +++ /dev/null @@ -1,34 +0,0 @@ -[ - "building-on-shape/ai.md", - "building-on-shape/alchemy-api.md", - "building-on-shape/builder-kit.md", - "building-on-shape/differences-ethereum-shape.md", - "building-on-shape/onchain-compatible/assembly.md", - "building-on-shape/onchain-compatible/index.md", - "building-on-shape/onchain-compatible/otom.md", - "building-on-shape/superchain-incentives.md", - "building-on-shape/transaction-fees.md", - "gasback.md", - "index.md", - "quick-start/connect-to-shape.md", - "quick-start/deploy-a-contract.md", - "quick-start/index.md", - "technical-details/contract-addresses.md", - "technical-details/network-information.md", - "technical-details/run-a-node.md", - "the-stack.md", - "tools/account-abstraction.md", - "tools/bridges.md", - "tools/data-indexers.md", - "tools/explorers.md", - "tools/faucets.md", - "tools/node-providers.md", - "tools/oracles/gelato-vrf.md", - "tools/safes-asset-security.md", - "tools/sybil-resistance.md", - "tutorials/mint-nft-collection.md", - "tutorials/registering-contract-gasback/dashboard.md", - "tutorials/registering-contract-gasback/index.md", - "tutorials/registering-contract-gasback/programmatically.md", - "wallet-setup.md" -] diff --git a/public/building-on-shape/ai.md b/public/building-on-shape/ai.md deleted file mode 100644 index 1a3f566..0000000 --- a/public/building-on-shape/ai.md +++ /dev/null @@ -1,119 +0,0 @@ -# AI Agents on Shape - -This guide gets you started with the Model Context Protocol (MCP) and our Shape MCP server, tools to make your AI agents smarter onchain. We'll cover the basics, show how to plug in Vercel AI, and spark some NFT agent ideas. - -## What is MCP? - -MCP (Model Context Protocol) is a standard for letting AI models like ChatGPT, Grok, or Claude safely access and interact with external data. Think blockchains, APIs, or tools. It's like giving your agent a direct communication channel to Shape, with features for tool calls, resources, and permissions. MCP keeps things structured and extensible, while keeping granular control over access or authorization for example. - -For a deep dive, check the [official MCP intro](https://modelcontextprotocol.io/introduction). In short: MCP turns your AI into an Shape-connoisseur, chaining queries like "fetch Shape NFTs" to "analyze collections trends" without leaving the chat. - -## Shape MCP Server: Your On-Chain Data Bridge - -We've built a dedicated MCP server for Shape, wrapping key data like Gasback distributions, NFT analytics, and Stack medals. It's open-source, forkable, and ready for your agents. Built with [xmcp](https://xmcp.dev/), it's TypeScript-first so no need to learn Python, and it deploys in minutes. - -- **Repository**: [github.com/shape-network/mcp-server](https://github.com/shape-network/mcp-server) -- **Why Use It?** Agents can query Shape without raw RPC calls. E.g., simulate Gasback rewards or track Stack achievements. It's modular, so you can extend it for any project. - -### Quick Setup - -Fork the repo and deploy your own instance, keeping things non-hosted and under your control. - -1. Fork and clone: `git clone https://github.com/shape-network/mcp-server` -2. Install: `yarn install` -3. Env vars in `.env`: `ALCHEMY_API_KEY=your-key`, `CHAIN_ID=360` (mainnet), optional `REDIS_URL` for caching. -4. Run locally: `yarn dev` (at http://localhost:3002/mcp) -5. Deploy to Vercel: Import the fork, set env vars in the UI, and hit deploy. - -For full tools and examples, see the [README](https://github.com/shape-network/mcp-server/blob/main/README.md). - -## Building AI Agents with Vercel AI SDK - -[Vercel AI SDK](https://ai-sdk.dev/docs/introduction) makes agent development a breeze. It's TypeScript-first, works with models like ChatGPT, Grok, or Claude, and handles streaming, tool calls, and chaining. Pair it with our MCP server for Shape-specific capabilities. - -### First Steps - -1. **Setup a Next.js App**: `npx create-next-app my-shape-agent`. (Pro tip: If you want a head start, run `bun create shape-app my-shape-agent` to scaffold a full Shape project with wallet connect, RPC setup, smart contracts, and UI components. See the [Builder Kit](https://docs.shape.network/building-on-shape/builder-kit.md) docs for details.) -2. **Install SDK**: `npm i ai @ai-sdk/openai @modelcontextprotocol/sdk viem wagmi` (for onchain integration) — [more info](https://ai-sdk.dev/docs/introduction). -3. **Connect MCP**: In an API route (e.g., /api/agent.ts): - - ```ts - import { openai } from '@ai-sdk/openai'; - import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; - import { experimental_createMCPClient, streamText } from 'ai'; - - export const maxDuration = 30; - - export async function POST(req: Request) { - const { messages } = await req.json(); - - // Connect to your deployed MCP server - const url = new URL('https://shape-mcp-server.vercel.app/mcp'); // or http://localhost:3002/mcp for local - const mcpClient = await experimental_createMCPClient({ - transport: new StreamableHTTPClientTransport(url), - }); - - // Get all available tools exposed - const tools = await mcpClient.tools(); - - const result = await streamText({ - model: openai('gpt-4o'), - tools, - messages, - maxSteps: 10, // Allow up to 10 sequential tool calls - system: 'You are a helpful assistant that [...]', // add your custom system prompt - onFinish: async () => { - await mcpClient.close(); - }, - }); - - return result.toDataStreamResponse(); - } - ``` - -4. **Add UI**: Use `useChat` hook in a page: - - ```ts - import { useChat } from 'ai/react'; - - export default function AgentChat() { - const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({ - api: '/api/agent', - maxSteps: 10, // Enable multi-step tool usage - }); - - return ( -
-
- {messages.map(m => ( -
- {m.role}: {m.content} -
- ))} - {isLoading &&
Thinking...
} -
-
- - -
-
- ); - } - ``` - -5. **Deploy**: Push to GitHub, import to Vercel, set env vars, and go live. - -For full docs, see [Vercel AI SDK](https://vercel.com/docs/ai-sdk). - -## AI Agent Ideas for NFTs on Shape - -Shape's low fees and Gasback make it ideal for NFT agents. Here are fun starters—build these for the upcoming hackathon! - -- **NFT Curator Bot**: Queries `getCollectionAnalytics` to spot trending collections, then uses `getShapeNft` to suggest buys. Agent prompt: "Curate 5 underrated NFTs under 0.1 ETH—why buy?" -- **Gasback Optimizer**: Simulates rewards with `simulateGasbackRewards` for creators. Chains with `getTopShapeCreators` for comparisons. Prompt: "Optimize my contract for max Gasback—tx volume tips?" -- **Stack Achievement Coach**: Tracks progress via `getStackAchievements`, suggests actions (e.g., "Mint 3 more for gold medal"). Prompt: "What's my Stack level? Steps to next tier?" -- **Collection Analyzer**: Combines `getCollectionAnalytics` and `getChainStatus` to time mints. Prompt: "Is now good to mint on collection X? Gas low?" - -These leverage MCP for on-chain data, Vercel AI for reasoning—start simple, add wallet integration (wagmi) for actions. - -Questions? Hit up [@williamhzo](https://x.com/williamhzo) or [Shape Discord](https://discord.com/invite/shape-l2). Let's build!! diff --git a/public/building-on-shape/alchemy-api.md b/public/building-on-shape/alchemy-api.md deleted file mode 100644 index e90f7ba..0000000 --- a/public/building-on-shape/alchemy-api.md +++ /dev/null @@ -1,10 +0,0 @@ -# Alchemy API - -Find out what Alchemy tools are available to use on Shape. - -Checkout [Alchemy's Quickstart guide](https://docs.alchemy.com/reference/shape-api-quickstart) for Shape API. The [full suite](https://www.alchemy.com/) of Alchemy tools are available for builders on Shape. - -Visit your [Alchemy dashboard](https://dashboard.alchemy.com/) and start building now! - -> Visit your [Alchemy dashboard](https://www.alchemy.com/dashboard) and start building -> now! diff --git a/public/building-on-shape/builder-kit.md b/public/building-on-shape/builder-kit.md deleted file mode 100644 index e22866c..0000000 --- a/public/building-on-shape/builder-kit.md +++ /dev/null @@ -1,100 +0,0 @@ -# Shape Builder Kit for Developers - -The Shape Builder Kit is your go-to starter for crafting dApps on the Shape ecosystem. It's a monorepo with a Next.js frontend (wagmi, viem) and a Hardhat smart contract package, all pre-wired with sensible defaults. - -- **Batteries Included**: Wallet connection, Shape RPC integration, and NFT fetching out of the box. No reinventing the wheel. -- **AI-Ready**: Pairs seamlessly with the [Shape MCP server](https://docs.shape.network/building-on-shape/ai.md) and Vercel AI SDK for agentic apps. -- **Fast Track to Deploy**: Built for Vercel, so you can deploy to prod in minutes and focus on getting your first users! - -It's completely open and composable: use it to kickstart, then tweak to your style & needs. Check it out: [github.com/shape-network/builder-kit](https://github.com/shape-network/builder-kit). - -## Quickstart with `create-shape-app` - -The fastest way to get started is [`create-shape-app`](https://github.com/shape-network/create-shape-app), a CLI that scaffolds a new project from the latest Builder Kit release. One command and you're in: - -```bash -npx create-shape-app my-app -# or -bun create shape-app my-app -``` - -Also works with pnpm and yarn: - -```bash -pnpm dlx create-shape-app my-app -yarn create shape-app my-app -``` - -The CLI will download the latest Builder Kit release, install dependencies, and initialize a git repository. - -### CLI Options - -| Option | Description | -| --- | --- | -| `-y, --yes` | Skip interactive confirmation prompts | -| `--pm ` | Select package manager (auto-detected if omitted) | -| `--skip-install` | Skip dependency installation | -| `--skip-git` | Skip git init and initial commit | -| `--template-ref ` | Pin a specific Builder Kit release tag (e.g. `v1.0.0`) | - -## Project Structure - -The scaffolded project is a monorepo with two packages: - -``` -my-app/ -├── apps/web/ # Next.js + wagmi frontend -└── packages/contract/ # Hardhat smart contracts -``` - -## Configuration - -Copy `.env.example` to `.env` and fill in your values: - -```env -NEXT_PUBLIC_ALCHEMY_KEY=your-alchemy-key -NEXT_PUBLIC_CHAIN_ID=11011 # 11011 for Shape Sepolia, 360 for Shape Mainnet -NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID= # Optional -DEPLOYER_PRIVATE_KEY= # For contract deployment, must be funded on target network -``` - -Get an Alchemy API key from the [Alchemy Dashboard](https://www.alchemy.com/dashboard). - -## Development - -```bash -bun dev # Run the web app locally -bun build # Build for production -bun lint # Lint -bun type-check # Type-check -``` - -### Smart Contracts - -```bash -bun contracts:compile # Compile contracts and regenerate artifacts -bun contracts:test # Run contract tests -bun contracts:deploy:shape-sepolia # Deploy to Shape Sepolia -bun contracts:artifact # Regenerate deployment artifacts for the web app -bun wagmi:generate # Regenerate wagmi typed ABI hooks -``` - -## What's Included? - -- **Wallet Connection**: wagmi for MetaMask (or other wallet providers) integration. Connect with one click. -- **Shape RPC**: Pre-configured with Shape's RPC via Alchemy. Swap to your own node in `.env`. -- **Smart Contracts**: Hardhat setup with a sample `HelloShape` contract, deployment scripts, and typed wagmi hooks generated from your ABIs. -- **UI Components**: Based on [shadcn/ui](https://ui.shadcn.com/) & Tailwind CSS, customize to your heart's content. -- **AI-Ready**: Pairs with the [Shape MCP server](https://docs.shape.network/building-on-shape/ai.md) and Vercel AI SDK for agentic apps. - -## Deploy to Vercel - -Push to GitHub, import to [Vercel](https://vercel.com/new), set env vars in the UI, and deploy. Instant live app! - -## Resources - -- [Builder Kit repository](https://github.com/shape-network/builder-kit) -- [create-shape-app on npm](https://www.npmjs.com/package/create-shape-app) -- [Live demo](https://builder-kit.vercel.app/) - -Questions? Hit up [@williamhzo](https://x.com/williamhzo) or [Shape Discord](https://discord.com/invite/shape-l2). Let's build! diff --git a/public/building-on-shape/differences-ethereum-shape.md b/public/building-on-shape/differences-ethereum-shape.md deleted file mode 100644 index b095e99..0000000 --- a/public/building-on-shape/differences-ethereum-shape.md +++ /dev/null @@ -1,36 +0,0 @@ -# Differences between Ethereum and Shape - -Shape is EVM equivalent, but has some minor differences. - -Shape is built on Optimism's [OP Stack](https://docs.optimism.io/stack/getting-started), an open-source public good designed to be EVM equivalent and introduce as few changes as possible to the Ethereum protocol. This makes it easy to build on Shape. - -There are some minor differences developers should be aware of: - -## Key Differences - -### Opcodes - -Shape maintains EVM equivalence but has some modified opcodes to support its Layer 2 architecture. For detailed information about specific opcode changes, refer to the [Optimism documentation](https://docs.optimism.io/chain/differences#opcodes). - -### Transaction Fees - -Shape's transaction fee structure differs from Ethereum's: - -- Shape uses a dual-fee system with L1 and L2 fees -- L2 fees are significantly lower than Ethereum's gas fees -- Shape has [Gasback](https://docs.shape.network/gasback.md), returning 80% of L2 fees to contract owners - -More information [here](https://docs.shape.network/building-on-shape/transaction-fees.md). - -### Block Time - -- Shape produces blocks every 2 seconds (vs Ethereum's ~12 seconds) -- This enables quicker transaction confirmations - -### Network Architecture - -- Shape is a Layer 2 solution built on top of Ethereum -- It inherits Ethereum's security while providing scalability benefits -- Transactions are batched and submitted to Ethereum for final settlement - -For more detailed technical information about these differences, please refer to the [Optimism documentation](https://docs.optimism.io/chain/differences/). diff --git a/public/building-on-shape/onchain-compatible/assembly.md b/public/building-on-shape/onchain-compatible/assembly.md deleted file mode 100644 index c48b1b2..0000000 --- a/public/building-on-shape/onchain-compatible/assembly.md +++ /dev/null @@ -1,335 +0,0 @@ -# Assembly - -## Overview - -The Assembly system, built on top of Otoms, is a flexible ERC1155 implementation enabling the creation, crafting, and management of both fungible and non-fungible items on the blockchain. Built with upgradeability in mind, the system allows for component-based crafting where items can be created using blueprints that define required components with specific properties. - -It's a community-driven and open source project, source code is available [here on GitHub](https://github.com/shape-network/assembly), where you'll find both code for the web dApp implementation and the contracts. - -We greatly welcome contributions to the project! Please reach out on [Discord](https://discord.com/invite/shape-L2) or [Twitter/X](https://x.com/shape) if you'd like to get involved. - -### Key Components - -- **OtomItems**: Main ERC1155 token contract that implements the token standard and handles token operations -- **OtomItemsCore**: Manages item definitions, crafting logic, and item usage behaviors -- **OtomItemsTracking**: Tracks ownership and supplies of items without requiring an offchain indexer - -## Item Types - -The system supports two primary item types: - -1. **Fungible Items**: Standard fungible tokens that stack in inventory, useful for resources or consumables that all have identical properties at all times e.g. bricks, oak logs, gold ore -2. **Non-Fungible Items**: Unique items that can have tiers (1-7) and dynamic properties, suitable for equipment or collectibles where each instance of an item could have different properties at any given time e.g. a car with differing amounts of fuel in the tank - -## Item and Token ID System - -The Otom Items system uses two ID types to track items and their instances: - -- **Item IDs**: Sequential identifiers that represent item definitions or blueprints. Each distinct item type (like "Steel Sword" or "Health Potion") has a unique item ID assigned when it's created. Item IDs define what an item is, including its blueprint requirements, traits, and behaviors. -- **Token IDs**: ERC1155 token identifiers that represent specific instances or quantities of items owned by users. For fungible items, the token ID == item ID, as all instances are identical. For non-fungible items, each crafted instance receives a unique token ID that maps back to its parent item ID. The system maintains this mapping through `getItemIdForToken()`. Non-fungible tokens also store tier information and the actual components used in crafting, enabling dynamic properties based on crafting input. Practically, token IDs are derived by concatenating the item id and the mint count of that item - -The system uses a specific function `getNonFungibleTokenId(itemId, mintIndex)` to generate token IDs for non-fungible items: - -``` -function getNonFungibleTokenId(uint256 itemId, uint256 mintIndex) { - return (uint256(keccak256(abi.encodePacked(itemId, mintIndex))) % 2 ** 128) + 2 ** 128; -} - -``` - -This function creates a unique token ID by hashing the item ID and mint index together, then ensuring the result is above 2^128. This approach guarantees that: - -1. Each non-fungible token has a unique ID -2. The token ID range is distinct from fungible tokens (all non-fungible token IDs are greater than 2^128), and all fungible token ids are less than 2^128 -3. ID collisions are prevented by the cryptographic properties of keccak256 hashing, which creates a unique output for each unique (itemId, mintIndex) pair - -## Blueprint System - -Items are defined by blueprints that specify: - -- Required components (Otoms, variable Otoms, or other items) -- Property criteria that components must meet -- Quantities of each component needed - -### Component Types - -``` -OTOM - Specific Otom token required -VARIABLE_OTOM - Any Otom meeting property criteria -FUNGIBLE_ITEM - Fungible item component -NON_FUNGIBLE_ITEM - Non-fungible item component - -``` - -### Property Criteria - -Components can be required to have specific properties within defined ranges: - -``` -PropertyCriterion: -- PropertyType (e.g., ATOM_RADIUS, MASS, ELECTRONEGATIVITY) -- Min/Max values for numerical properties -- Boolean values for flag properties -- String values for categorical properties e.g. the decay type must match some string -- Bytes32 values for the universe hash property - -``` - -## Item Creation and Crafting - -### Creation Flow - -1. User creates item definitions with `createFungibleItem` or `createNonFungibleItem` -2. Each item receives a unique ID and blueprint definition -3. Base traits can be defined at creation time, and for non fungible tokens, get updated as the item is used, or at craft time if the blueprint is variable. Fungible token base traits never change. - -### Crafting Flow - -1. User calls `craftItem` with item ID, amount, and any variable components - 1. When crafting variable blueprints, two arrays are provided, 1 for otom token ids used in the variable slots, and 1 for the item token ids used in the variable slots. The ordering of ids within those arrays matter - the first VARIABLE_OTOM blueprint component will be filled by the first element in the first array, and so on. - 2. Arrays are not needed for OTOM and FUNGIBLE ITEM blueprint components because the token ids are predefined in the blueprint. -2. System verifies user has required components meeting criteria -3. System burns the components as part of crafting -4. For non-fungible items, tier is calculated via mutator contract -5. New item tokens are minted to the user with appropriate traits - -Items can be "frozen", meaning their core properties (name, description, mutator address, initial traits) can no longer be updated, and the behaviour of mutation is set in stone. Freezing is a one way operation. - -## Tier System - -Non-fungible items have optional tiers (1-7) that are calculated by mutator contracts based on components used and price paid in crafting. - -The intent is for users to seek out the most powerful otoms to use in blueprints, so that they can get the top tier version of the item. - -Tiers are not named, they should just be referred to as T1 through T7. This is so that at a glance every user knows the relative power the item is considered to have. - -If all instances of a non fungible item are equal, the developer can set the tier to 0 and no tier will be set. - -## Item Usage - -Items can be: - -- **Crafted**: Trigger custom logic in mutator contracts through `onCraft` - - This hook allows custom checks to be made when crafting an item e.g. a limited edition craft only available for a set time period. -- **Used**: Trigger custom logic in mutator contracts through `useItem` - - ONLY non fungible items can be used in this way - - The intent is that "using" an item then causes the traits to be altered in some way. Differing traits for the same item is only possible if the item is non fungible - - Using an item may destroy it, if the mutator contract called in the use function says so -- **Consumed**: Burned via `consumeItem` - - ONLY fungible items can be consumed - - Fungible items have no reason to be "used" because the tokens are all identical. But they can still be "consumed", e.g., using 10 bricks to build a house, the 10 bricks will be consumed. - -The `useItem` and `consumeItem` functions are expected to be called by contracts, not by users directly. In order for the calls to succeed, the user must have granted approval to the caller to be allowed to use their OtomItems nfts. There are 3 ways to grant approval: - -1. Call the ERC1155 `setApprovalForAll` function on the nft contract itself - unsafe because it means the operator will have access to all of the user's items even if they aren't relevant -2. Call `setApprovalForItemIds` on the core contract, which approves an operator to consume that item or use any instance of a non fungible item -3. Call `setApprovalForTokenIds` on the core contract, which approves an operator to use/consume that specific token id - -## Trait System - -Items have dynamic traits that: - -``` -Trait: -- typeName: The name of the trait -- valueString: String representation (for STRING type traits) -- valueNumber: Numeric representation (for NUMBER type traits) -- traitType: Either NUMBER or STRING - -``` - -- Can be updated through item usage via mutator contracts -- Affect item functionality and appearance -- Store custom metadata relevant to the item - -## Rendering - -The rendering is handled by a hot swappable renderer contract. All token metadata is onchain. The image rendered is simply the name of the item (and tier), plus the blueprint used to create it. - -When creating items, users can provide a "default image uri" for the fungible token and for all tiers of non fungible tokens. This image is not what will appear in wallets and marketplaces, but front ends for the items system (e.g. Assembly), can use these images instead of the onchain svg. - -## Creating items - -### Step-by-step guides for creating different items for Assembly - -We'll be using Hardhat in the examples below. Here's the [Otoms repo](https://github.com/shape-network/assembly/tree/main/packages/contracts/contracts/items) if you'd prefer to take a look beforehand. - -#### Creating fungible items - -1. Fill in the following data (use this example data to get started) - -```jsx -const item = { - // name, description, & imageUri: used to generate the NFT metadata. - name: 'Jusonic Ore', - description: 'A ductile metal, known for its strength and lightweight', - imageUri: 'https://arweave.net/cBCEZ6bqtmdkS6Vj8dIAgXhl4O8oDSyAWuqCMlCDToU', - // blueprint: list of Otoms used to craft your Item - // (in our example we chose the Otom Ju2 with the an amount of 2). - blueprint: [ - { - componentType: 0, // ComponentType.OTOM - itemIdOrOtomTokenId: - '35159569680903626501449329353512578019171730918789714169601127546706358467814', // Ju2 - amount: 3, - criteria: [], - }, - ], - // traits: these are optional - traits: [ - { - typeName: 'Strength', - valueString: '70', - valueNumber: 70, - traitType: 0, // TraitType.NUMBER - }, - { - typeName: 'Weight', - valueString: '10', - valueNumber: 10, - traitType: 0, // TraitType.NUMBER - }, - { - typeName: 'Build Materials', - valueString: 'Three Ju2', - valueNumber: 0, - traitType: 1, // TraitType.STRING - }, - ], - // costInWei: what you want to charge for the item - costInWei: 0, - // feeRecipient: who should get the fees generated from by item - feeRecipient: '0x0000000000000000000000000000000000000000', -}; -``` - -1. Call the `createFungibleItem` function on the `OtomItemsCore` contract - -```jsx -const core = await ethers.getContractAt( - 'OtomItemsCore', - '0xe8af571878D33CfecA4eA11caEf124E5ef105a30' // Shape Mainnet -); - -await core.createFungibleItem( - item.name, - item.description, - item.imageUri, - item.blueprint, - item.traits, - item.costInWei, - item.feeRecipient -); -``` - -And that's all you need to create your first fungible Assembly item. - -#### Creating non-fungible items - -1. Fill in the following data - 1. **Note: this example data is different than the previous example data** - -```jsx -const testPick = { - // name, description, & imageUri: used to generate the NFT metadata. - name: 'Invisibility Cloak', - description: 'A mythical cloak that grants invisibility', - imageUri: 'https://arweave.net/D3uuvnLDY48wmJ_Qic5l3AUrQ1pfOaUYn79t9PJYG18', - // tieredImageUris: used for tiered items; optionally leave empty. - tieredImageUris: ['', '', '', '', '', '', ''], - // blueprint: list of Otoms used to craft your Item - // (in our example we chose the Otom Ju3 with the an amount of 1). - blueprint: [ - { - componentType: 0, // ComponentType.OTOM - itemIdOrOtomTokenId: - '59556967404187678662646267921069430003902119556859655597906602022599940926148', // T15 - amount: 1, - criteria: [], - }, - { - componentType: 0, // ComponentType.OTOM - itemIdOrOtomTokenId: - '103207475906385737307003328874764609497044818069100475897999853498353983732479', // Sr2 - amount: 2, - criteria: [], - }, - ], - // traits: these are optional, - // but become useful when paired with a mutator contract (more on that later). - traits: [ - { - typeName: 'Ability', - valueString: 'Invisibility', - valueNumber: 0, - traitType: 1, // TraitType.STRING - }, - { - typeName: 'Build Materials', - valueString: 'T15 and two Sr2', - valueNumber: 0, - traitType: 1, // TraitType.STRING - }, - ], - // costInWei: what you want to charge for the item - costInWei: 0, - // feeRecipient: who should get the fee - feeRecipient: '0x0000000000000000000000000000000000000000', -}; -``` - -1. Call the `createNonFungibleItem` function on the `OtomItemsCore` contract - -```jsx -const core = await ethers.getContractAt( - 'OtomItemsCore', - '0xe8af571878D33CfecA4eA11caEf124E5ef105a30' // Shape Mainnet -); - -await core.createNonFungibleItem( - item.name, - item.description, - item.imageUri, - item.tieredImageUris, - item.blueprint, - item.traits, - '0x0000000000000000000000000000000000000000', - // ^this is where you mutator address would go - item.costInWei, - item.feeRecipient -); -``` - -Now you can create non-fungible items for Assembly. - -#### Creating non-fungible items (with a mutator) - -1. Create your mutator contract and implement the `IOtomItemMutator` hooks for custom item logic (`calculateTier`, `onCraft`, `onItemUse`, `onTransfer`) - 1. **Here is the [interface](https://github.com/shape-network/assembly/blob/main/packages/contracts/contracts/interfaces/IOtomItemMutator.sol) you will need, and here is an example of a [generic mutator](https://github.com/shape-network/assembly/blob/main/packages/contracts/contracts/items/mutators/GenericMutator.sol)** -2. Once you've deployed your mutator contract, follow step #1 of the previous tutorial - 1. **Note: If you handle tiers inside your mutator contract, try adding `tieredImageUris`** -3. Now we will call the `createNonFungibleItem` function on the `OtomItemsCore` contract, this time we pass in our mutator address - -```jsx -const core = await ethers.getContractAt( - 'OtomItemsCore', - '0xe8af571878D33CfecA4eA11caEf124E5ef105a30' // Shape Mainnet -); - -const mutatorAddress = '0xYourContractAddressHere'; - -await core.createNonFungibleItem( - item.name, - item.description, - item.imageUri, - item.tieredImageUris, - item.blueprint, - item.traits, - mutatorAddress, - // ^this is the only difference - item.costInWei, - item.feeRecipient -); -``` - -Now you've created an Assembly item with a custom mutator contract. diff --git a/public/building-on-shape/onchain-compatible/index.md b/public/building-on-shape/onchain-compatible/index.md deleted file mode 100644 index 44ba861..0000000 --- a/public/building-on-shape/onchain-compatible/index.md +++ /dev/null @@ -1,9 +0,0 @@ -# Onchain Compatible Projects - -A collection of projects made with interoperability in mind - -- [Assembly](https://docs.shape.network/building-on-shape/onchain-compatible/assembly.md): A flexible ERC1155 system for creating and crafting composable items - -- [OTOM by Kjetil Golid](https://docs.shape.network/building-on-shape/onchain-compatible/otom.md): Create and experiment with particles called otoms - -- [Moveable Type by DEAFBEEF](https://moveabletype.deafbeef.com/) diff --git a/public/building-on-shape/onchain-compatible/otom.md b/public/building-on-shape/onchain-compatible/otom.md deleted file mode 100644 index 7c26d69..0000000 --- a/public/building-on-shape/onchain-compatible/otom.md +++ /dev/null @@ -1,238 +0,0 @@ -# OTOM by Kjetil Golid - -Create and experiment with particles called otoms - -**Website**: [otom.xyz](https://otom.xyz/) - -**Repo:** [github.com/shape-network/otom-contracts](https://github.com/shape-network/otom-contracts) - -There are four main actions a chemist can take within the otoms universe. - -1. **Mine for Otoms** -2. **Annihilate said Otoms and receive Energy (ERC20)** -3. **Use Energy along with multiple Otoms to initiate a reaction** -4. **Analyze reactions and receive molecules (Chemists can analyze multiple unanalyzed reactions in a single transaction)** - -## Contracts - -### Shape Mainnet - -| Link | Description | Address | -| ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | -| [**Otoms**](https://shapescan.xyz/address/0x2f9810789aebBB6cdC6c0332948fF3B6D11121E3?tab=contract) | Main NFT contract for minting otoms | `0x2f9810789aebBB6cdC6c0332948fF3B6D11121E3` | -| [**OtomsDatabase**](https://shapescan.xyz/address/0x953761a771d6Ad9F888e41b3E7c9338a32b1A346?tab=contract) | DB used for storing information related to things like; tokenURI, Molecules, Who first discovered a Molecule, Universes | `0x953761a771d6Ad9F888e41b3E7c9338a32b1A346` | -| [**OtomsReactionOutputs**](https://shapescan.xyz/address/0x7d5A370F277e1847E4f768a88758237c6E3456eD?tab=contract) | Secondary NFT contract of unextracted Molecules | `0x7d5A370F277e1847E4f768a88758237c6E3456eD` | -| [**Energy**](https://shapescan.xyz/address/0x42276dF82BAb34c3CCcA9e5c058b6ff7EA4d07e3?tab=contract) | Fungible token used in reactions | `0x42276dF82BAb34c3CCcA9e5c058b6ff7EA4d07e3` | -| [**Reactor**](https://shapescan.xyz/address/0xB8874fCE9b702B191C306A21c7A4a101FB14a0fc?tab=contract) | Main reactor contract, used to initialize and analyze reactions | `0xB8874fCE9b702B191C306A21c7A4a101FB14a0fc` | -| [**Annihilator**](https://shapescan.xyz/address/0xca3088aedaAB138cAB3F0c135ceD77aF1a8b9063?tab=contract) | Used to convert NFT Otoms into fungible Energy | `0xca3088aedaAB138cAB3F0c135ceD77aF1a8b9063` | - -### Shape Sepolia - -| Link | Description | Address | -| ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | -| [**Otoms**](https://sepolia.shapescan.xyz/address/0xc709F59f1356230025d4fdFDCeD92341A14FF2F8?tab=contract) | Main NFT contract for minting otoms | `0xc709F59f1356230025d4fdFDCeD92341A14FF2F8` | -| [**OtomsDatabase**](https://sepolia.shapescan.xyz/address/0xC6E01938846D3d62EafD7FF485afeE416f6D8A40?tab=contract) | DB used for storing information related to things like; tokenURI, Molecules, Who first discovered a Molecule, Universes | `0xC6E01938846D3d62EafD7FF485afeE416f6D8A40` | -| [**OtomsReactionOutputs**](https://sepolia.shapescan.xyz/address/0x042125947523dD14dc64e3093a53DfCcdF07d979?tab=contract) | Secondary NFT contract of unextracted Molecules | `0x042125947523dD14dc64e3093a53DfCcdF07d979` | -| [**Energy**](https://sepolia.shapescan.xyz/address/0xe59D1719d3F8c149B009cB05a7679ce1dC074787?tab=contract) | Fungible token used in reactions | `0xe59D1719d3F8c149B009cB05a7679ce1dC074787` | -| [**Reactor**](https://sepolia.shapescan.xyz/address/0x62C87dd718E60c31993cf1a5EB32EE472C7eD144?tab=contract) | Main reactor contract, used to initialize and analyze reactions | `0x62C87dd718E60c31993cf1a5EB32EE472C7eD144` | -| [**Annihilator**](https://sepolia.shapescan.xyz/address/0xC998b6604aA50F71dd1b52884544c9107cf267E9?tab=contract) | Used to convert NFT Otoms into fungible Energy | `0xC998b6604aA50F71dd1b52884544c9107cf267E9` | - -## Functionality - -### Mining Otoms - -```solidity filename="Otoms.sol" -/** - * @dev Mines atoms based on the provided payloads. - * @param _payloads The payloads to mine atoms from. - * @return The token IDs of the mined atoms. - */ -function mine( - MiningPayload[] calldata payloads -) external returns (uint256[] memory); -``` - -### Mining Payload - -```solidity filename="IOtoms.sol" -struct MiningPayload { - Molecule minedMolecule; - bytes32 miningHash; - string tokenUri; - bytes32 universeHash; - uint256 expiry; - bytes signature; -} -``` - -### Reacting with Otoms - -```solidity filename="Reactor.sol" -/** - * @dev Initiates a reaction with the provided atom IDs and energy amount. - * @param atomIds The token IDs of the atoms to be used in the reaction. - * @param energyAmount The amount of energy to be used in the reaction. - * @return The token ID of the output of the reaction. - */ -function initiateReaction( - uint256[] memory atomIds, - uint256 energyAmount -) external returns (uint256); - -/** - * @dev Analyses the provided reaction results and returns - * the output of the reaction. - * @param reactionResults The results of the reaction. - * @param expiry The expiry time of the reaction. - * @param signature The signature of the reaction. - * @return The output of the reaction. - */ -function analyseReactions( - ReactionResult[] memory reactionResults, - uint256 expiry, - bytes memory signature -) external; -``` - -### Annihilating Otoms - -```solidity filename="Annihilator.sol" -/** - * @dev Annihilates the provided atom IDs. - * @param atomIds The token IDs of the atoms to be annihilated. - * @return The amount of energy produced by the annihilations. - */ -function annihilate( - uint256[] memory atomIds -) external nonReentrant returns (uint256) -``` - -## Structs - -```solidity filename="IOtomsDatabase.sol" -struct Molecule { - string id; - string name; - bytes32 universeHash; - uint256 activationEnergy; - uint256 radius; - Bond bond; - Atom[] givingAtoms; - Atom[] receivingAtoms; - uint256 electricalConductivity; - uint256 thermalConductivity; - uint256 toughness; - uint256 hardness; - uint256 ductility; -} - -struct Atom { - uint256 radius; - uint256 volume; - uint256 mass; - uint256 density; - uint256 electronegativity; - bool metallic; - string name; - string series; - uint256 periodicTableX; - uint256 periodicTableY; - AtomStructure structure; - Nucleus nucleus; -} -``` - -> We've included the three main structs used for mining otoms. Check out `IOtoms.sol` and -> `IOtomsDatabase.sol` for more info. - -## Data - -```solidity filename="OtomsDatabase.sol" -function getMoleculeByTokenId( - uint256 tokenId -) external view returns (Molecule memory); - -function getUniverseInformation( - bytes32 universeHash -) external view returns (UniverseInformation memory); - -function getMoleculesDiscovered( - bytes32 universeHash -) external view returns (Molecule[] memory); - -function getMoleculesDiscoveredPaginated( - bytes32 universeHash, - uint256 offset, - uint256 limit -) external view returns (Molecule[] memory molecules, uint256 total); - -function activeUniverses() external view returns (bytes32[] memory); -``` - -### Otoms - -```solidity filename="Otoms.sol" -function moleculeIsAtom( - Molecule memory _molecule -) external pure returns (bool); -``` - -### ReactionOutputs - -```solidity filename="OtomsReactionOutputs.sol" -function getReactionOutputData( - uint256 tokenId -) external view returns (ReactionOutputData memory); -``` - -## Encoding Utilities - -```solidity filename="IOtomsEncoder.sol" -function encodeMolecule( - Molecule memory _newMolecule -) external pure returns (bytes32); - -function encodeAtom( - Atom memory _newAtom -) external pure returns (bytes32); - -function encodeStructure( - AtomStructure memory _newStructure -) external pure returns (bytes32); - -function encodeNucleus( - Nucleus memory _newNucleus -) external pure returns (bytes32); - -function encodeUniverseInformation( - UniverseInformation memory _universeInformation -) external pure returns (bytes32); - -function getSeedUniverseMessageHash( - UniverseInformation memory _universeInformation, - uint256 expiry, - address sender -) external view returns (bytes32); - -function getMiningMessageHash( - Molecule memory _newAtom, - bytes32 _miningHash, - string memory _tokenUri, - bytes32 _universeHash, - uint256 expiry, - address sender -) external view returns (bytes32); - -function getMiningHash( - address _chemist, - bytes32 _universeHash, - uint256 _nonce -) external pure returns (bytes32); - -function getMultipleMiningHashes( - address _chemist, - bytes32 _universeHash, - uint256 _startingNonce, - uint256 _count -) external pure returns (bytes32[] memory); -``` diff --git a/public/building-on-shape/superchain-incentives.md b/public/building-on-shape/superchain-incentives.md deleted file mode 100644 index 89819d3..0000000 --- a/public/building-on-shape/superchain-incentives.md +++ /dev/null @@ -1,13 +0,0 @@ -# Superchain incentives - -Learn about the Superchain incentives available to you as a Shape builder. - -Shape is a part of the [Superchain](https://app.optimism.io/superchain/). This means when you build on Shape, you become eligible for additional incentives, including: - -- [RetroPGF](https://app.optimism.io/retropgf): Rewarding your onchain impact - -- [Free contract deployment](https://docs.optimism.io/builders/app-developers/tutorials/deploy-for-free): Claim deployment rebates - -- [Gas sponsorship](https://console.optimism.io/): For your early users - -- [Launch support](https://console.optimism.io/): Amplified marketing through Superchain channels diff --git a/public/building-on-shape/transaction-fees.md b/public/building-on-shape/transaction-fees.md deleted file mode 100644 index 1266506..0000000 --- a/public/building-on-shape/transaction-fees.md +++ /dev/null @@ -1,94 +0,0 @@ -# Transaction Fees - -Learn how network fees work on Shape, what changes them, where they go, and how to estimate them. - -## How do network fees on Shape work? - -Shape transaction fees are paid in **Ether** ("ETH"). - -Every Shape transaction involves two separate costs: - -- **L1 Fee**: the security fee for publishing transaction data to Ethereum. -- **L2 Fee**: the execution fee for running the transaction on Shape. - -Fees on Shape are much cheaper than what you'd pay for an equivalent transaction on Ethereum. The total cost can still vary based on Ethereum network activity, Shape network activity, transaction size, and any priority fee you choose to include. - -## L1 Fee - -The L1 Fee is paid to ensure your transaction's data is published to Ethereum, guaranteeing its availability for nodes to download and execute. This is crucial for maintaining the security properties of Shape. - -This fee varies depending on the current base fee on Ethereum and the amount of transaction data that needs to be published. If the timing of your transaction is flexible, submitting during periods of lower Ethereum gas can reduce the L1 Fee. - -L1 Fees are used to cover costs paid to Ethereum validators. - -## L2 Fee - -The L2 Fee is paid to execute your transaction on Shape. It has two components: a base fee and a priority fee. - -The **base fee** is the minimum required for your transaction to be included in a block. - -The **priority fee** is _optional_, and you decide how much to pay if you choose to include it. - -> Shape executes transactions in descending priority order - with higher priority fees taking -> precedence over lower priority fees - so the priority fee allows you to efficiently express -> the urgency of your transaction. - -The L2 Fee is also known as the **Sequencer Fee**. You can find more information about transaction fee calculation in the [OP Stack transaction fee documentation](https://docs.optimism.io/op-stack/transactions/fees). - -## Where do fees go? - -L1 Fees are used to cover the cost of publishing transaction data to Ethereum. - -**Shape directs 80% of ETH collected from L2 Fees back to the contracts that generated the activity**, ensuring the creators and platforms that thrive on the network share in its success. - -> Learn more about how this works in [Gasback](https://docs.shape.network/gasback.md). - -For the remaining 20%: - -- 15% goes to the Optimism Collective to fund public goods -- 5% goes to infrastructure and the Shape Foundation during the early stages of the network - -## Minimum Base Fee - -Shape uses a minimum L2 base fee to keep execution fees from falling to near-zero during quiet periods. This floor keeps blockspace predictably priced while preserving low transaction costs for apps, creators, and users. - -The minimum L2 base fee on Shape Mainnet is 10,000,000 wei (0.01 gwei). Shape may adjust this value as network usage evolves. At 0.01 gwei, a transaction using 200,000 L2 gas costs about $0.004 in L2 base fee when ETH is $2,000, before priority fees and the separate L1 data fee. - -### Why it matters - -- **Gasback alignment**: The minimum applies to L2 execution fees, which are the fees Shape shares with registered contracts through Gasback. -- **More reliable inclusion**: A nonzero floor helps the fee market respond when demand increases after quiet periods, reducing the chance that transactions wait while fees catch up. -- **Predictable app costs**: During normal demand, the L2 base fee should remain close to the floor. During congestion, it can rise with network usage. -- **Healthier blockspace pricing**: The floor discourages low-value spam while keeping normal Shape transactions inexpensive. - -## EIP-1559 fee behavior - -Shape uses the OP Stack's implementation of EIP-1559 for L2 execution fees. The L2 base fee adjusts in response to network demand, while the priority fee lets users express transaction urgency. - -When Shape is less busy, the L2 base fee can decrease. When blocks are more heavily used, the L2 base fee can increase. This is separate from the L1 Fee, which varies with Ethereum gas costs and the size of the transaction data being posted. - -OP Stack chains can tune fee behavior with parameters such as EIP-1559 elasticity, EIP-1559 denominator, gas limit, and minimum base fee. Shape-specific values are not listed here unless published or verified from the live network configuration. For the underlying OP Stack parameter model, see the [OP Stack fee parameter documentation](https://docs.optimism.io/chain-operators/guides/management/transaction-fees-101). - -## Querying the L1 fee - -The **GasPriceOracle** predeploy at `0x420000000000000000000000000000000000000F` lets you programmatically estimate the L1 Fee component before signing and submitting a transaction. - -| Method | Returns | -| ------------------------------------ | -------------------------------------------------------------------- | -| `getL1Fee(bytes)` | Exact L1 fee for a fully serialized transaction | -| `getL1FeeUpperBound(uint256 txSize)` | Upper-bound L1 fee estimate from approximate transaction byte length | -| `l1BaseFee()` | Current Ethereum L1 base fee as seen by Shape | -| `blobBaseFee()` | Current EIP-4844 blob base fee | -| `baseFeeScalar()` | Scalar applied to the L1 base fee component | -| `blobBaseFeeScalar()` | Scalar applied to the blob base fee component | - -Use `getL1FeeUpperBound` when you need a quick estimate before the transaction is fully constructed. Use `getL1Fee` with the complete serialized transaction for an exact estimate before signing. - -The GasPriceOracle address is also listed in [Contract Addresses](https://docs.shape.network/technical-details/contract-addresses.md). - -## Related resources - -- [Gasback](https://docs.shape.network/gasback.md) -- [Network Information](https://docs.shape.network/technical-details/network-information.md) -- [Contract Addresses](https://docs.shape.network/technical-details/contract-addresses.md) -- [OP Stack transaction fees](https://docs.optimism.io/op-stack/transactions/fees) diff --git a/public/gasback.md b/public/gasback.md deleted file mode 100644 index 2d6f5d2..0000000 --- a/public/gasback.md +++ /dev/null @@ -1,24 +0,0 @@ -# Gasback - -Claim back 80% of the sequencer fees that users spend interacting with your contracts on Shape. - -## What is Gasback? - -Shape redistributes the **majority of sequencer fees spent by users to execute transactions** back to the contracts they interacted with, ensuring the creators and platforms that thrive on the network share in its success. This concept is called **Gasback**. - -### I own a contract on Shape. How much gas do I get back? - -All contract owners can claim back **80%** of the [L2 Fees](https://docs.shape.network/building-on-shape/transaction-fees.md) generated from users interacting with their contracts on Shape. - -### How do I take part in Gasback? - -**Gasback** is open to all smart contract owners on Shape. There are two ways to register your contracts: - -1. [Register via the Dashboard](https://docs.shape.network/tutorials/registering-contract-gasback/dashboard.md) -2. [Register programmatically](https://docs.shape.network/tutorials/registering-contract-gasback/programmatically.md) - -Once registered, you'll be able to claim your share of the sequencer fees generated by your contracts' activity. - -> Learn how to -> [register your contracts for Gasback here](https://docs.shape.network/tutorials/registering-contract-gasback/index.md) -> . diff --git a/public/index.md b/public/index.md deleted file mode 100644 index 7f9ec85..0000000 --- a/public/index.md +++ /dev/null @@ -1,36 +0,0 @@ -# Welcome - -Shape is the culture-first L2 built on top of Ethereum to power the new NFT economy. - -The network is an open space where everyone is free to create whatever they want - from fine art, to weird experiments, to whole new ideas - making it the place for culture to take root. - -## Why create on Shape? - -### Shape Culture. Get Gasback. - -As a creator on Shape, you can claim back 80% of sequencer fees users spend interacting with your contracts. This includes contracts you build yourself, contracts you acquire ownership of, and contracts that you deploy through other platforms. - -> Learn more about how this works in [Gasback](https://docs.shape.network/gasback.md). - -### The best of Ethereum. - -Shape is [EVM equivalent](https://docs.shape.network/building-on-shape/differences-ethereum-shape.md). This means your creator experience is the same as on Ethereum, just at a fraction of the cost. - -### Secure, stable & scalable. - -Shape inherits its security directly from Ethereum, keeping the networks intrinsically linked forever. - -Shape also prioritizes stability and scalability, utilizing [Alchemy](https://docs.shape.network/building-on-shape/alchemy-api.md) and [Optimism](https://www.optimism.io/) as key infrastructure partners to help achieve and maintain these states. - -### Shape the Superchain. - -Shape is a member of the [Superchain](https://docs.optimism.io/stack/explainer), which unlocks a range of further benefits for the entire ecosystem - including ongoing network-level cooperation, funding of public goods, and additional builder incentives on Shape. - -### Home for unique NFT experiments - -Shape is the proof that NFTs aren't just static images that people can buy and sell. - -- Deep dive into the rabbit hole of onchain chemistry with [OTOM](https://docs.shape.network/building-on-shape/onchain-compatible/otom.md) by Kjetil Golid. -- Wander in Leander Herzog's [Infinite Garden](https://infinite-garden.xyz/) -- Create & craft your own [Assembly Items](https://docs.shape.network/building-on-shape/onchain-compatible/assembly.md) -- And [many more...](https://shape.network/) diff --git a/public/llms-full.txt b/public/llms-full.txt deleted file mode 100644 index 38b0578..0000000 --- a/public/llms-full.txt +++ /dev/null @@ -1,2613 +0,0 @@ -# Shape Technical Documentation - -Generated from the official documentation source. This is the technical corpus; token and governance information is maintained at https://shape.network/token. - ---- - -Canonical page: https://docs.shape.network/building-on-shape/ai -Markdown page: https://docs.shape.network/building-on-shape/ai.md - -# AI Agents on Shape - -This guide gets you started with the Model Context Protocol (MCP) and our Shape MCP server, tools to make your AI agents smarter onchain. We'll cover the basics, show how to plug in Vercel AI, and spark some NFT agent ideas. - -## What is MCP? - -MCP (Model Context Protocol) is a standard for letting AI models like ChatGPT, Grok, or Claude safely access and interact with external data. Think blockchains, APIs, or tools. It's like giving your agent a direct communication channel to Shape, with features for tool calls, resources, and permissions. MCP keeps things structured and extensible, while keeping granular control over access or authorization for example. - -For a deep dive, check the [official MCP intro](https://modelcontextprotocol.io/introduction). In short: MCP turns your AI into an Shape-connoisseur, chaining queries like "fetch Shape NFTs" to "analyze collections trends" without leaving the chat. - -## Shape MCP Server: Your On-Chain Data Bridge - -We've built a dedicated MCP server for Shape, wrapping key data like Gasback distributions, NFT analytics, and Stack medals. It's open-source, forkable, and ready for your agents. Built with [xmcp](https://xmcp.dev/), it's TypeScript-first so no need to learn Python, and it deploys in minutes. - -- **Repository**: [github.com/shape-network/mcp-server](https://github.com/shape-network/mcp-server) -- **Why Use It?** Agents can query Shape without raw RPC calls. E.g., simulate Gasback rewards or track Stack achievements. It's modular, so you can extend it for any project. - -### Quick Setup - -Fork the repo and deploy your own instance, keeping things non-hosted and under your control. - -1. Fork and clone: `git clone https://github.com/shape-network/mcp-server` -2. Install: `yarn install` -3. Env vars in `.env`: `ALCHEMY_API_KEY=your-key`, `CHAIN_ID=360` (mainnet), optional `REDIS_URL` for caching. -4. Run locally: `yarn dev` (at http://localhost:3002/mcp) -5. Deploy to Vercel: Import the fork, set env vars in the UI, and hit deploy. - -For full tools and examples, see the [README](https://github.com/shape-network/mcp-server/blob/main/README.md). - -## Building AI Agents with Vercel AI SDK - -[Vercel AI SDK](https://ai-sdk.dev/docs/introduction) makes agent development a breeze. It's TypeScript-first, works with models like ChatGPT, Grok, or Claude, and handles streaming, tool calls, and chaining. Pair it with our MCP server for Shape-specific capabilities. - -### First Steps - -1. **Setup a Next.js App**: `npx create-next-app my-shape-agent`. (Pro tip: If you want a head start, run `bun create shape-app my-shape-agent` to scaffold a full Shape project with wallet connect, RPC setup, smart contracts, and UI components. See the [Builder Kit](https://docs.shape.network/building-on-shape/builder-kit.md) docs for details.) -2. **Install SDK**: `npm i ai @ai-sdk/openai @modelcontextprotocol/sdk viem wagmi` (for onchain integration) — [more info](https://ai-sdk.dev/docs/introduction). -3. **Connect MCP**: In an API route (e.g., /api/agent.ts): - - ```ts - import { openai } from '@ai-sdk/openai'; - import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; - import { experimental_createMCPClient, streamText } from 'ai'; - - export const maxDuration = 30; - - export async function POST(req: Request) { - const { messages } = await req.json(); - - // Connect to your deployed MCP server - const url = new URL('https://shape-mcp-server.vercel.app/mcp'); // or http://localhost:3002/mcp for local - const mcpClient = await experimental_createMCPClient({ - transport: new StreamableHTTPClientTransport(url), - }); - - // Get all available tools exposed - const tools = await mcpClient.tools(); - - const result = await streamText({ - model: openai('gpt-4o'), - tools, - messages, - maxSteps: 10, // Allow up to 10 sequential tool calls - system: 'You are a helpful assistant that [...]', // add your custom system prompt - onFinish: async () => { - await mcpClient.close(); - }, - }); - - return result.toDataStreamResponse(); - } - ``` - -4. **Add UI**: Use `useChat` hook in a page: - - ```ts - import { useChat } from 'ai/react'; - - export default function AgentChat() { - const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({ - api: '/api/agent', - maxSteps: 10, // Enable multi-step tool usage - }); - - return ( -
-
- {messages.map(m => ( -
- {m.role}: {m.content} -
- ))} - {isLoading &&
Thinking...
} -
-
- - -
-
- ); - } - ``` - -5. **Deploy**: Push to GitHub, import to Vercel, set env vars, and go live. - -For full docs, see [Vercel AI SDK](https://vercel.com/docs/ai-sdk). - -## AI Agent Ideas for NFTs on Shape - -Shape's low fees and Gasback make it ideal for NFT agents. Here are fun starters—build these for the upcoming hackathon! - -- **NFT Curator Bot**: Queries `getCollectionAnalytics` to spot trending collections, then uses `getShapeNft` to suggest buys. Agent prompt: "Curate 5 underrated NFTs under 0.1 ETH—why buy?" -- **Gasback Optimizer**: Simulates rewards with `simulateGasbackRewards` for creators. Chains with `getTopShapeCreators` for comparisons. Prompt: "Optimize my contract for max Gasback—tx volume tips?" -- **Stack Achievement Coach**: Tracks progress via `getStackAchievements`, suggests actions (e.g., "Mint 3 more for gold medal"). Prompt: "What's my Stack level? Steps to next tier?" -- **Collection Analyzer**: Combines `getCollectionAnalytics` and `getChainStatus` to time mints. Prompt: "Is now good to mint on collection X? Gas low?" - -These leverage MCP for on-chain data, Vercel AI for reasoning—start simple, add wallet integration (wagmi) for actions. - -Questions? Hit up [@williamhzo](https://x.com/williamhzo) or [Shape Discord](https://discord.com/invite/shape-l2). Let's build!! - ---- - -Canonical page: https://docs.shape.network/building-on-shape/alchemy-api -Markdown page: https://docs.shape.network/building-on-shape/alchemy-api.md - -# Alchemy API - -Find out what Alchemy tools are available to use on Shape. - -Checkout [Alchemy's Quickstart guide](https://docs.alchemy.com/reference/shape-api-quickstart) for Shape API. The [full suite](https://www.alchemy.com/) of Alchemy tools are available for builders on Shape. - -Visit your [Alchemy dashboard](https://dashboard.alchemy.com/) and start building now! - -> Visit your [Alchemy dashboard](https://www.alchemy.com/dashboard) and start building -> now! - ---- - -Canonical page: https://docs.shape.network/building-on-shape/builder-kit -Markdown page: https://docs.shape.network/building-on-shape/builder-kit.md - -# Shape Builder Kit for Developers - -The Shape Builder Kit is your go-to starter for crafting dApps on the Shape ecosystem. It's a monorepo with a Next.js frontend (wagmi, viem) and a Hardhat smart contract package, all pre-wired with sensible defaults. - -- **Batteries Included**: Wallet connection, Shape RPC integration, and NFT fetching out of the box. No reinventing the wheel. -- **AI-Ready**: Pairs seamlessly with the [Shape MCP server](https://docs.shape.network/building-on-shape/ai.md) and Vercel AI SDK for agentic apps. -- **Fast Track to Deploy**: Built for Vercel, so you can deploy to prod in minutes and focus on getting your first users! - -It's completely open and composable: use it to kickstart, then tweak to your style & needs. Check it out: [github.com/shape-network/builder-kit](https://github.com/shape-network/builder-kit). - -## Quickstart with `create-shape-app` - -The fastest way to get started is [`create-shape-app`](https://github.com/shape-network/create-shape-app), a CLI that scaffolds a new project from the latest Builder Kit release. One command and you're in: - -```bash -npx create-shape-app my-app -# or -bun create shape-app my-app -``` - -Also works with pnpm and yarn: - -```bash -pnpm dlx create-shape-app my-app -yarn create shape-app my-app -``` - -The CLI will download the latest Builder Kit release, install dependencies, and initialize a git repository. - -### CLI Options - -| Option | Description | -| --- | --- | -| `-y, --yes` | Skip interactive confirmation prompts | -| `--pm ` | Select package manager (auto-detected if omitted) | -| `--skip-install` | Skip dependency installation | -| `--skip-git` | Skip git init and initial commit | -| `--template-ref ` | Pin a specific Builder Kit release tag (e.g. `v1.0.0`) | - -## Project Structure - -The scaffolded project is a monorepo with two packages: - -``` -my-app/ -├── apps/web/ # Next.js + wagmi frontend -└── packages/contract/ # Hardhat smart contracts -``` - -## Configuration - -Copy `.env.example` to `.env` and fill in your values: - -```env -NEXT_PUBLIC_ALCHEMY_KEY=your-alchemy-key -NEXT_PUBLIC_CHAIN_ID=11011 # 11011 for Shape Sepolia, 360 for Shape Mainnet -NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID= # Optional -DEPLOYER_PRIVATE_KEY= # For contract deployment, must be funded on target network -``` - -Get an Alchemy API key from the [Alchemy Dashboard](https://www.alchemy.com/dashboard). - -## Development - -```bash -bun dev # Run the web app locally -bun build # Build for production -bun lint # Lint -bun type-check # Type-check -``` - -### Smart Contracts - -```bash -bun contracts:compile # Compile contracts and regenerate artifacts -bun contracts:test # Run contract tests -bun contracts:deploy:shape-sepolia # Deploy to Shape Sepolia -bun contracts:artifact # Regenerate deployment artifacts for the web app -bun wagmi:generate # Regenerate wagmi typed ABI hooks -``` - -## What's Included? - -- **Wallet Connection**: wagmi for MetaMask (or other wallet providers) integration. Connect with one click. -- **Shape RPC**: Pre-configured with Shape's RPC via Alchemy. Swap to your own node in `.env`. -- **Smart Contracts**: Hardhat setup with a sample `HelloShape` contract, deployment scripts, and typed wagmi hooks generated from your ABIs. -- **UI Components**: Based on [shadcn/ui](https://ui.shadcn.com/) & Tailwind CSS, customize to your heart's content. -- **AI-Ready**: Pairs with the [Shape MCP server](https://docs.shape.network/building-on-shape/ai.md) and Vercel AI SDK for agentic apps. - -## Deploy to Vercel - -Push to GitHub, import to [Vercel](https://vercel.com/new), set env vars in the UI, and deploy. Instant live app! - -## Resources - -- [Builder Kit repository](https://github.com/shape-network/builder-kit) -- [create-shape-app on npm](https://www.npmjs.com/package/create-shape-app) -- [Live demo](https://builder-kit.vercel.app/) - -Questions? Hit up [@williamhzo](https://x.com/williamhzo) or [Shape Discord](https://discord.com/invite/shape-l2). Let's build! - ---- - -Canonical page: https://docs.shape.network/building-on-shape/differences-ethereum-shape -Markdown page: https://docs.shape.network/building-on-shape/differences-ethereum-shape.md - -# Differences between Ethereum and Shape - -Shape is EVM equivalent, but has some minor differences. - -Shape is built on Optimism's [OP Stack](https://docs.optimism.io/stack/getting-started), an open-source public good designed to be EVM equivalent and introduce as few changes as possible to the Ethereum protocol. This makes it easy to build on Shape. - -There are some minor differences developers should be aware of: - -## Key Differences - -### Opcodes - -Shape maintains EVM equivalence but has some modified opcodes to support its Layer 2 architecture. For detailed information about specific opcode changes, refer to the [Optimism documentation](https://docs.optimism.io/chain/differences#opcodes). - -### Transaction Fees - -Shape's transaction fee structure differs from Ethereum's: - -- Shape uses a dual-fee system with L1 and L2 fees -- L2 fees are significantly lower than Ethereum's gas fees -- Shape has [Gasback](https://docs.shape.network/gasback.md), returning 80% of L2 fees to contract owners - -More information [here](https://docs.shape.network/building-on-shape/transaction-fees.md). - -### Block Time - -- Shape produces blocks every 2 seconds (vs Ethereum's ~12 seconds) -- This enables quicker transaction confirmations - -### Network Architecture - -- Shape is a Layer 2 solution built on top of Ethereum -- It inherits Ethereum's security while providing scalability benefits -- Transactions are batched and submitted to Ethereum for final settlement - -For more detailed technical information about these differences, please refer to the [Optimism documentation](https://docs.optimism.io/chain/differences/). - ---- - -Canonical page: https://docs.shape.network/building-on-shape/onchain-compatible/assembly -Markdown page: https://docs.shape.network/building-on-shape/onchain-compatible/assembly.md - -# Assembly - -## Overview - -The Assembly system, built on top of Otoms, is a flexible ERC1155 implementation enabling the creation, crafting, and management of both fungible and non-fungible items on the blockchain. Built with upgradeability in mind, the system allows for component-based crafting where items can be created using blueprints that define required components with specific properties. - -It's a community-driven and open source project, source code is available [here on GitHub](https://github.com/shape-network/assembly), where you'll find both code for the web dApp implementation and the contracts. - -We greatly welcome contributions to the project! Please reach out on [Discord](https://discord.com/invite/shape-L2) or [Twitter/X](https://x.com/shape) if you'd like to get involved. - -### Key Components - -- **OtomItems**: Main ERC1155 token contract that implements the token standard and handles token operations -- **OtomItemsCore**: Manages item definitions, crafting logic, and item usage behaviors -- **OtomItemsTracking**: Tracks ownership and supplies of items without requiring an offchain indexer - -## Item Types - -The system supports two primary item types: - -1. **Fungible Items**: Standard fungible tokens that stack in inventory, useful for resources or consumables that all have identical properties at all times e.g. bricks, oak logs, gold ore -2. **Non-Fungible Items**: Unique items that can have tiers (1-7) and dynamic properties, suitable for equipment or collectibles where each instance of an item could have different properties at any given time e.g. a car with differing amounts of fuel in the tank - -## Item and Token ID System - -The Otom Items system uses two ID types to track items and their instances: - -- **Item IDs**: Sequential identifiers that represent item definitions or blueprints. Each distinct item type (like "Steel Sword" or "Health Potion") has a unique item ID assigned when it's created. Item IDs define what an item is, including its blueprint requirements, traits, and behaviors. -- **Token IDs**: ERC1155 token identifiers that represent specific instances or quantities of items owned by users. For fungible items, the token ID == item ID, as all instances are identical. For non-fungible items, each crafted instance receives a unique token ID that maps back to its parent item ID. The system maintains this mapping through `getItemIdForToken()`. Non-fungible tokens also store tier information and the actual components used in crafting, enabling dynamic properties based on crafting input. Practically, token IDs are derived by concatenating the item id and the mint count of that item - -The system uses a specific function `getNonFungibleTokenId(itemId, mintIndex)` to generate token IDs for non-fungible items: - -``` -function getNonFungibleTokenId(uint256 itemId, uint256 mintIndex) { - return (uint256(keccak256(abi.encodePacked(itemId, mintIndex))) % 2 ** 128) + 2 ** 128; -} - -``` - -This function creates a unique token ID by hashing the item ID and mint index together, then ensuring the result is above 2^128. This approach guarantees that: - -1. Each non-fungible token has a unique ID -2. The token ID range is distinct from fungible tokens (all non-fungible token IDs are greater than 2^128), and all fungible token ids are less than 2^128 -3. ID collisions are prevented by the cryptographic properties of keccak256 hashing, which creates a unique output for each unique (itemId, mintIndex) pair - -## Blueprint System - -Items are defined by blueprints that specify: - -- Required components (Otoms, variable Otoms, or other items) -- Property criteria that components must meet -- Quantities of each component needed - -### Component Types - -``` -OTOM - Specific Otom token required -VARIABLE_OTOM - Any Otom meeting property criteria -FUNGIBLE_ITEM - Fungible item component -NON_FUNGIBLE_ITEM - Non-fungible item component - -``` - -### Property Criteria - -Components can be required to have specific properties within defined ranges: - -``` -PropertyCriterion: -- PropertyType (e.g., ATOM_RADIUS, MASS, ELECTRONEGATIVITY) -- Min/Max values for numerical properties -- Boolean values for flag properties -- String values for categorical properties e.g. the decay type must match some string -- Bytes32 values for the universe hash property - -``` - -## Item Creation and Crafting - -### Creation Flow - -1. User creates item definitions with `createFungibleItem` or `createNonFungibleItem` -2. Each item receives a unique ID and blueprint definition -3. Base traits can be defined at creation time, and for non fungible tokens, get updated as the item is used, or at craft time if the blueprint is variable. Fungible token base traits never change. - -### Crafting Flow - -1. User calls `craftItem` with item ID, amount, and any variable components - 1. When crafting variable blueprints, two arrays are provided, 1 for otom token ids used in the variable slots, and 1 for the item token ids used in the variable slots. The ordering of ids within those arrays matter - the first VARIABLE_OTOM blueprint component will be filled by the first element in the first array, and so on. - 2. Arrays are not needed for OTOM and FUNGIBLE ITEM blueprint components because the token ids are predefined in the blueprint. -2. System verifies user has required components meeting criteria -3. System burns the components as part of crafting -4. For non-fungible items, tier is calculated via mutator contract -5. New item tokens are minted to the user with appropriate traits - -Items can be "frozen", meaning their core properties (name, description, mutator address, initial traits) can no longer be updated, and the behaviour of mutation is set in stone. Freezing is a one way operation. - -## Tier System - -Non-fungible items have optional tiers (1-7) that are calculated by mutator contracts based on components used and price paid in crafting. - -The intent is for users to seek out the most powerful otoms to use in blueprints, so that they can get the top tier version of the item. - -Tiers are not named, they should just be referred to as T1 through T7. This is so that at a glance every user knows the relative power the item is considered to have. - -If all instances of a non fungible item are equal, the developer can set the tier to 0 and no tier will be set. - -## Item Usage - -Items can be: - -- **Crafted**: Trigger custom logic in mutator contracts through `onCraft` - - This hook allows custom checks to be made when crafting an item e.g. a limited edition craft only available for a set time period. -- **Used**: Trigger custom logic in mutator contracts through `useItem` - - ONLY non fungible items can be used in this way - - The intent is that "using" an item then causes the traits to be altered in some way. Differing traits for the same item is only possible if the item is non fungible - - Using an item may destroy it, if the mutator contract called in the use function says so -- **Consumed**: Burned via `consumeItem` - - ONLY fungible items can be consumed - - Fungible items have no reason to be "used" because the tokens are all identical. But they can still be "consumed", e.g., using 10 bricks to build a house, the 10 bricks will be consumed. - -The `useItem` and `consumeItem` functions are expected to be called by contracts, not by users directly. In order for the calls to succeed, the user must have granted approval to the caller to be allowed to use their OtomItems nfts. There are 3 ways to grant approval: - -1. Call the ERC1155 `setApprovalForAll` function on the nft contract itself - unsafe because it means the operator will have access to all of the user's items even if they aren't relevant -2. Call `setApprovalForItemIds` on the core contract, which approves an operator to consume that item or use any instance of a non fungible item -3. Call `setApprovalForTokenIds` on the core contract, which approves an operator to use/consume that specific token id - -## Trait System - -Items have dynamic traits that: - -``` -Trait: -- typeName: The name of the trait -- valueString: String representation (for STRING type traits) -- valueNumber: Numeric representation (for NUMBER type traits) -- traitType: Either NUMBER or STRING - -``` - -- Can be updated through item usage via mutator contracts -- Affect item functionality and appearance -- Store custom metadata relevant to the item - -## Rendering - -The rendering is handled by a hot swappable renderer contract. All token metadata is onchain. The image rendered is simply the name of the item (and tier), plus the blueprint used to create it. - -When creating items, users can provide a "default image uri" for the fungible token and for all tiers of non fungible tokens. This image is not what will appear in wallets and marketplaces, but front ends for the items system (e.g. Assembly), can use these images instead of the onchain svg. - -## Creating items - -### Step-by-step guides for creating different items for Assembly - -We'll be using Hardhat in the examples below. Here's the [Otoms repo](https://github.com/shape-network/assembly/tree/main/packages/contracts/contracts/items) if you'd prefer to take a look beforehand. - -#### Creating fungible items - -1. Fill in the following data (use this example data to get started) - -```jsx -const item = { - // name, description, & imageUri: used to generate the NFT metadata. - name: 'Jusonic Ore', - description: 'A ductile metal, known for its strength and lightweight', - imageUri: 'https://arweave.net/cBCEZ6bqtmdkS6Vj8dIAgXhl4O8oDSyAWuqCMlCDToU', - // blueprint: list of Otoms used to craft your Item - // (in our example we chose the Otom Ju2 with the an amount of 2). - blueprint: [ - { - componentType: 0, // ComponentType.OTOM - itemIdOrOtomTokenId: - '35159569680903626501449329353512578019171730918789714169601127546706358467814', // Ju2 - amount: 3, - criteria: [], - }, - ], - // traits: these are optional - traits: [ - { - typeName: 'Strength', - valueString: '70', - valueNumber: 70, - traitType: 0, // TraitType.NUMBER - }, - { - typeName: 'Weight', - valueString: '10', - valueNumber: 10, - traitType: 0, // TraitType.NUMBER - }, - { - typeName: 'Build Materials', - valueString: 'Three Ju2', - valueNumber: 0, - traitType: 1, // TraitType.STRING - }, - ], - // costInWei: what you want to charge for the item - costInWei: 0, - // feeRecipient: who should get the fees generated from by item - feeRecipient: '0x0000000000000000000000000000000000000000', -}; -``` - -1. Call the `createFungibleItem` function on the `OtomItemsCore` contract - -```jsx -const core = await ethers.getContractAt( - 'OtomItemsCore', - '0xe8af571878D33CfecA4eA11caEf124E5ef105a30' // Shape Mainnet -); - -await core.createFungibleItem( - item.name, - item.description, - item.imageUri, - item.blueprint, - item.traits, - item.costInWei, - item.feeRecipient -); -``` - -And that's all you need to create your first fungible Assembly item. - -#### Creating non-fungible items - -1. Fill in the following data - 1. **Note: this example data is different than the previous example data** - -```jsx -const testPick = { - // name, description, & imageUri: used to generate the NFT metadata. - name: 'Invisibility Cloak', - description: 'A mythical cloak that grants invisibility', - imageUri: 'https://arweave.net/D3uuvnLDY48wmJ_Qic5l3AUrQ1pfOaUYn79t9PJYG18', - // tieredImageUris: used for tiered items; optionally leave empty. - tieredImageUris: ['', '', '', '', '', '', ''], - // blueprint: list of Otoms used to craft your Item - // (in our example we chose the Otom Ju3 with the an amount of 1). - blueprint: [ - { - componentType: 0, // ComponentType.OTOM - itemIdOrOtomTokenId: - '59556967404187678662646267921069430003902119556859655597906602022599940926148', // T15 - amount: 1, - criteria: [], - }, - { - componentType: 0, // ComponentType.OTOM - itemIdOrOtomTokenId: - '103207475906385737307003328874764609497044818069100475897999853498353983732479', // Sr2 - amount: 2, - criteria: [], - }, - ], - // traits: these are optional, - // but become useful when paired with a mutator contract (more on that later). - traits: [ - { - typeName: 'Ability', - valueString: 'Invisibility', - valueNumber: 0, - traitType: 1, // TraitType.STRING - }, - { - typeName: 'Build Materials', - valueString: 'T15 and two Sr2', - valueNumber: 0, - traitType: 1, // TraitType.STRING - }, - ], - // costInWei: what you want to charge for the item - costInWei: 0, - // feeRecipient: who should get the fee - feeRecipient: '0x0000000000000000000000000000000000000000', -}; -``` - -1. Call the `createNonFungibleItem` function on the `OtomItemsCore` contract - -```jsx -const core = await ethers.getContractAt( - 'OtomItemsCore', - '0xe8af571878D33CfecA4eA11caEf124E5ef105a30' // Shape Mainnet -); - -await core.createNonFungibleItem( - item.name, - item.description, - item.imageUri, - item.tieredImageUris, - item.blueprint, - item.traits, - '0x0000000000000000000000000000000000000000', - // ^this is where you mutator address would go - item.costInWei, - item.feeRecipient -); -``` - -Now you can create non-fungible items for Assembly. - -#### Creating non-fungible items (with a mutator) - -1. Create your mutator contract and implement the `IOtomItemMutator` hooks for custom item logic (`calculateTier`, `onCraft`, `onItemUse`, `onTransfer`) - 1. **Here is the [interface](https://github.com/shape-network/assembly/blob/main/packages/contracts/contracts/interfaces/IOtomItemMutator.sol) you will need, and here is an example of a [generic mutator](https://github.com/shape-network/assembly/blob/main/packages/contracts/contracts/items/mutators/GenericMutator.sol)** -2. Once you've deployed your mutator contract, follow step #1 of the previous tutorial - 1. **Note: If you handle tiers inside your mutator contract, try adding `tieredImageUris`** -3. Now we will call the `createNonFungibleItem` function on the `OtomItemsCore` contract, this time we pass in our mutator address - -```jsx -const core = await ethers.getContractAt( - 'OtomItemsCore', - '0xe8af571878D33CfecA4eA11caEf124E5ef105a30' // Shape Mainnet -); - -const mutatorAddress = '0xYourContractAddressHere'; - -await core.createNonFungibleItem( - item.name, - item.description, - item.imageUri, - item.tieredImageUris, - item.blueprint, - item.traits, - mutatorAddress, - // ^this is the only difference - item.costInWei, - item.feeRecipient -); -``` - -Now you've created an Assembly item with a custom mutator contract. - ---- - -Canonical page: https://docs.shape.network/building-on-shape/onchain-compatible -Markdown page: https://docs.shape.network/building-on-shape/onchain-compatible/index.md - -# Onchain Compatible Projects - -A collection of projects made with interoperability in mind - -- [Assembly](https://docs.shape.network/building-on-shape/onchain-compatible/assembly.md): A flexible ERC1155 system for creating and crafting composable items - -- [OTOM by Kjetil Golid](https://docs.shape.network/building-on-shape/onchain-compatible/otom.md): Create and experiment with particles called otoms - -- [Moveable Type by DEAFBEEF](https://moveabletype.deafbeef.com/) - ---- - -Canonical page: https://docs.shape.network/building-on-shape/onchain-compatible/otom -Markdown page: https://docs.shape.network/building-on-shape/onchain-compatible/otom.md - -# OTOM by Kjetil Golid - -Create and experiment with particles called otoms - -**Website**: [otom.xyz](https://otom.xyz/) - -**Repo:** [github.com/shape-network/otom-contracts](https://github.com/shape-network/otom-contracts) - -There are four main actions a chemist can take within the otoms universe. - -1. **Mine for Otoms** -2. **Annihilate said Otoms and receive Energy (ERC20)** -3. **Use Energy along with multiple Otoms to initiate a reaction** -4. **Analyze reactions and receive molecules (Chemists can analyze multiple unanalyzed reactions in a single transaction)** - -## Contracts - -### Shape Mainnet - -| Link | Description | Address | -| ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | -| [**Otoms**](https://shapescan.xyz/address/0x2f9810789aebBB6cdC6c0332948fF3B6D11121E3?tab=contract) | Main NFT contract for minting otoms | `0x2f9810789aebBB6cdC6c0332948fF3B6D11121E3` | -| [**OtomsDatabase**](https://shapescan.xyz/address/0x953761a771d6Ad9F888e41b3E7c9338a32b1A346?tab=contract) | DB used for storing information related to things like; tokenURI, Molecules, Who first discovered a Molecule, Universes | `0x953761a771d6Ad9F888e41b3E7c9338a32b1A346` | -| [**OtomsReactionOutputs**](https://shapescan.xyz/address/0x7d5A370F277e1847E4f768a88758237c6E3456eD?tab=contract) | Secondary NFT contract of unextracted Molecules | `0x7d5A370F277e1847E4f768a88758237c6E3456eD` | -| [**Energy**](https://shapescan.xyz/address/0x42276dF82BAb34c3CCcA9e5c058b6ff7EA4d07e3?tab=contract) | Fungible token used in reactions | `0x42276dF82BAb34c3CCcA9e5c058b6ff7EA4d07e3` | -| [**Reactor**](https://shapescan.xyz/address/0xB8874fCE9b702B191C306A21c7A4a101FB14a0fc?tab=contract) | Main reactor contract, used to initialize and analyze reactions | `0xB8874fCE9b702B191C306A21c7A4a101FB14a0fc` | -| [**Annihilator**](https://shapescan.xyz/address/0xca3088aedaAB138cAB3F0c135ceD77aF1a8b9063?tab=contract) | Used to convert NFT Otoms into fungible Energy | `0xca3088aedaAB138cAB3F0c135ceD77aF1a8b9063` | - -### Shape Sepolia - -| Link | Description | Address | -| ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | -| [**Otoms**](https://sepolia.shapescan.xyz/address/0xc709F59f1356230025d4fdFDCeD92341A14FF2F8?tab=contract) | Main NFT contract for minting otoms | `0xc709F59f1356230025d4fdFDCeD92341A14FF2F8` | -| [**OtomsDatabase**](https://sepolia.shapescan.xyz/address/0xC6E01938846D3d62EafD7FF485afeE416f6D8A40?tab=contract) | DB used for storing information related to things like; tokenURI, Molecules, Who first discovered a Molecule, Universes | `0xC6E01938846D3d62EafD7FF485afeE416f6D8A40` | -| [**OtomsReactionOutputs**](https://sepolia.shapescan.xyz/address/0x042125947523dD14dc64e3093a53DfCcdF07d979?tab=contract) | Secondary NFT contract of unextracted Molecules | `0x042125947523dD14dc64e3093a53DfCcdF07d979` | -| [**Energy**](https://sepolia.shapescan.xyz/address/0xe59D1719d3F8c149B009cB05a7679ce1dC074787?tab=contract) | Fungible token used in reactions | `0xe59D1719d3F8c149B009cB05a7679ce1dC074787` | -| [**Reactor**](https://sepolia.shapescan.xyz/address/0x62C87dd718E60c31993cf1a5EB32EE472C7eD144?tab=contract) | Main reactor contract, used to initialize and analyze reactions | `0x62C87dd718E60c31993cf1a5EB32EE472C7eD144` | -| [**Annihilator**](https://sepolia.shapescan.xyz/address/0xC998b6604aA50F71dd1b52884544c9107cf267E9?tab=contract) | Used to convert NFT Otoms into fungible Energy | `0xC998b6604aA50F71dd1b52884544c9107cf267E9` | - -## Functionality - -### Mining Otoms - -```solidity filename="Otoms.sol" -/** - * @dev Mines atoms based on the provided payloads. - * @param _payloads The payloads to mine atoms from. - * @return The token IDs of the mined atoms. - */ -function mine( - MiningPayload[] calldata payloads -) external returns (uint256[] memory); -``` - -### Mining Payload - -```solidity filename="IOtoms.sol" -struct MiningPayload { - Molecule minedMolecule; - bytes32 miningHash; - string tokenUri; - bytes32 universeHash; - uint256 expiry; - bytes signature; -} -``` - -### Reacting with Otoms - -```solidity filename="Reactor.sol" -/** - * @dev Initiates a reaction with the provided atom IDs and energy amount. - * @param atomIds The token IDs of the atoms to be used in the reaction. - * @param energyAmount The amount of energy to be used in the reaction. - * @return The token ID of the output of the reaction. - */ -function initiateReaction( - uint256[] memory atomIds, - uint256 energyAmount -) external returns (uint256); - -/** - * @dev Analyses the provided reaction results and returns - * the output of the reaction. - * @param reactionResults The results of the reaction. - * @param expiry The expiry time of the reaction. - * @param signature The signature of the reaction. - * @return The output of the reaction. - */ -function analyseReactions( - ReactionResult[] memory reactionResults, - uint256 expiry, - bytes memory signature -) external; -``` - -### Annihilating Otoms - -```solidity filename="Annihilator.sol" -/** - * @dev Annihilates the provided atom IDs. - * @param atomIds The token IDs of the atoms to be annihilated. - * @return The amount of energy produced by the annihilations. - */ -function annihilate( - uint256[] memory atomIds -) external nonReentrant returns (uint256) -``` - -## Structs - -```solidity filename="IOtomsDatabase.sol" -struct Molecule { - string id; - string name; - bytes32 universeHash; - uint256 activationEnergy; - uint256 radius; - Bond bond; - Atom[] givingAtoms; - Atom[] receivingAtoms; - uint256 electricalConductivity; - uint256 thermalConductivity; - uint256 toughness; - uint256 hardness; - uint256 ductility; -} - -struct Atom { - uint256 radius; - uint256 volume; - uint256 mass; - uint256 density; - uint256 electronegativity; - bool metallic; - string name; - string series; - uint256 periodicTableX; - uint256 periodicTableY; - AtomStructure structure; - Nucleus nucleus; -} -``` - -> We've included the three main structs used for mining otoms. Check out `IOtoms.sol` and -> `IOtomsDatabase.sol` for more info. - -## Data - -```solidity filename="OtomsDatabase.sol" -function getMoleculeByTokenId( - uint256 tokenId -) external view returns (Molecule memory); - -function getUniverseInformation( - bytes32 universeHash -) external view returns (UniverseInformation memory); - -function getMoleculesDiscovered( - bytes32 universeHash -) external view returns (Molecule[] memory); - -function getMoleculesDiscoveredPaginated( - bytes32 universeHash, - uint256 offset, - uint256 limit -) external view returns (Molecule[] memory molecules, uint256 total); - -function activeUniverses() external view returns (bytes32[] memory); -``` - -### Otoms - -```solidity filename="Otoms.sol" -function moleculeIsAtom( - Molecule memory _molecule -) external pure returns (bool); -``` - -### ReactionOutputs - -```solidity filename="OtomsReactionOutputs.sol" -function getReactionOutputData( - uint256 tokenId -) external view returns (ReactionOutputData memory); -``` - -## Encoding Utilities - -```solidity filename="IOtomsEncoder.sol" -function encodeMolecule( - Molecule memory _newMolecule -) external pure returns (bytes32); - -function encodeAtom( - Atom memory _newAtom -) external pure returns (bytes32); - -function encodeStructure( - AtomStructure memory _newStructure -) external pure returns (bytes32); - -function encodeNucleus( - Nucleus memory _newNucleus -) external pure returns (bytes32); - -function encodeUniverseInformation( - UniverseInformation memory _universeInformation -) external pure returns (bytes32); - -function getSeedUniverseMessageHash( - UniverseInformation memory _universeInformation, - uint256 expiry, - address sender -) external view returns (bytes32); - -function getMiningMessageHash( - Molecule memory _newAtom, - bytes32 _miningHash, - string memory _tokenUri, - bytes32 _universeHash, - uint256 expiry, - address sender -) external view returns (bytes32); - -function getMiningHash( - address _chemist, - bytes32 _universeHash, - uint256 _nonce -) external pure returns (bytes32); - -function getMultipleMiningHashes( - address _chemist, - bytes32 _universeHash, - uint256 _startingNonce, - uint256 _count -) external pure returns (bytes32[] memory); -``` - ---- - -Canonical page: https://docs.shape.network/building-on-shape/superchain-incentives -Markdown page: https://docs.shape.network/building-on-shape/superchain-incentives.md - -# Superchain incentives - -Learn about the Superchain incentives available to you as a Shape builder. - -Shape is a part of the [Superchain](https://app.optimism.io/superchain/). This means when you build on Shape, you become eligible for additional incentives, including: - -- [RetroPGF](https://app.optimism.io/retropgf): Rewarding your onchain impact - -- [Free contract deployment](https://docs.optimism.io/builders/app-developers/tutorials/deploy-for-free): Claim deployment rebates - -- [Gas sponsorship](https://console.optimism.io/): For your early users - -- [Launch support](https://console.optimism.io/): Amplified marketing through Superchain channels - ---- - -Canonical page: https://docs.shape.network/building-on-shape/transaction-fees -Markdown page: https://docs.shape.network/building-on-shape/transaction-fees.md - -# Transaction Fees - -Learn how network fees work on Shape, what changes them, where they go, and how to estimate them. - -## How do network fees on Shape work? - -Shape transaction fees are paid in **Ether** ("ETH"). - -Every Shape transaction involves two separate costs: - -- **L1 Fee**: the security fee for publishing transaction data to Ethereum. -- **L2 Fee**: the execution fee for running the transaction on Shape. - -Fees on Shape are much cheaper than what you'd pay for an equivalent transaction on Ethereum. The total cost can still vary based on Ethereum network activity, Shape network activity, transaction size, and any priority fee you choose to include. - -## L1 Fee - -The L1 Fee is paid to ensure your transaction's data is published to Ethereum, guaranteeing its availability for nodes to download and execute. This is crucial for maintaining the security properties of Shape. - -This fee varies depending on the current base fee on Ethereum and the amount of transaction data that needs to be published. If the timing of your transaction is flexible, submitting during periods of lower Ethereum gas can reduce the L1 Fee. - -L1 Fees are used to cover costs paid to Ethereum validators. - -## L2 Fee - -The L2 Fee is paid to execute your transaction on Shape. It has two components: a base fee and a priority fee. - -The **base fee** is the minimum required for your transaction to be included in a block. - -The **priority fee** is _optional_, and you decide how much to pay if you choose to include it. - -> Shape executes transactions in descending priority order - with higher priority fees taking -> precedence over lower priority fees - so the priority fee allows you to efficiently express -> the urgency of your transaction. - -The L2 Fee is also known as the **Sequencer Fee**. You can find more information about transaction fee calculation in the [OP Stack transaction fee documentation](https://docs.optimism.io/op-stack/transactions/fees). - -## Where do fees go? - -L1 Fees are used to cover the cost of publishing transaction data to Ethereum. - -**Shape directs 80% of ETH collected from L2 Fees back to the contracts that generated the activity**, ensuring the creators and platforms that thrive on the network share in its success. - -> Learn more about how this works in [Gasback](https://docs.shape.network/gasback.md). - -For the remaining 20%: - -- 15% goes to the Optimism Collective to fund public goods -- 5% goes to infrastructure and the Shape Foundation during the early stages of the network - -## Minimum Base Fee - -Shape uses a minimum L2 base fee to keep execution fees from falling to near-zero during quiet periods. This floor keeps blockspace predictably priced while preserving low transaction costs for apps, creators, and users. - -The minimum L2 base fee on Shape Mainnet is 10,000,000 wei (0.01 gwei). Shape may adjust this value as network usage evolves. At 0.01 gwei, a transaction using 200,000 L2 gas costs about $0.004 in L2 base fee when ETH is $2,000, before priority fees and the separate L1 data fee. - -### Why it matters - -- **Gasback alignment**: The minimum applies to L2 execution fees, which are the fees Shape shares with registered contracts through Gasback. -- **More reliable inclusion**: A nonzero floor helps the fee market respond when demand increases after quiet periods, reducing the chance that transactions wait while fees catch up. -- **Predictable app costs**: During normal demand, the L2 base fee should remain close to the floor. During congestion, it can rise with network usage. -- **Healthier blockspace pricing**: The floor discourages low-value spam while keeping normal Shape transactions inexpensive. - -## EIP-1559 fee behavior - -Shape uses the OP Stack's implementation of EIP-1559 for L2 execution fees. The L2 base fee adjusts in response to network demand, while the priority fee lets users express transaction urgency. - -When Shape is less busy, the L2 base fee can decrease. When blocks are more heavily used, the L2 base fee can increase. This is separate from the L1 Fee, which varies with Ethereum gas costs and the size of the transaction data being posted. - -OP Stack chains can tune fee behavior with parameters such as EIP-1559 elasticity, EIP-1559 denominator, gas limit, and minimum base fee. Shape-specific values are not listed here unless published or verified from the live network configuration. For the underlying OP Stack parameter model, see the [OP Stack fee parameter documentation](https://docs.optimism.io/chain-operators/guides/management/transaction-fees-101). - -## Querying the L1 fee - -The **GasPriceOracle** predeploy at `0x420000000000000000000000000000000000000F` lets you programmatically estimate the L1 Fee component before signing and submitting a transaction. - -| Method | Returns | -| ------------------------------------ | -------------------------------------------------------------------- | -| `getL1Fee(bytes)` | Exact L1 fee for a fully serialized transaction | -| `getL1FeeUpperBound(uint256 txSize)` | Upper-bound L1 fee estimate from approximate transaction byte length | -| `l1BaseFee()` | Current Ethereum L1 base fee as seen by Shape | -| `blobBaseFee()` | Current EIP-4844 blob base fee | -| `baseFeeScalar()` | Scalar applied to the L1 base fee component | -| `blobBaseFeeScalar()` | Scalar applied to the blob base fee component | - -Use `getL1FeeUpperBound` when you need a quick estimate before the transaction is fully constructed. Use `getL1Fee` with the complete serialized transaction for an exact estimate before signing. - -The GasPriceOracle address is also listed in [Contract Addresses](https://docs.shape.network/technical-details/contract-addresses.md). - -## Related resources - -- [Gasback](https://docs.shape.network/gasback.md) -- [Network Information](https://docs.shape.network/technical-details/network-information.md) -- [Contract Addresses](https://docs.shape.network/technical-details/contract-addresses.md) -- [OP Stack transaction fees](https://docs.optimism.io/op-stack/transactions/fees) - ---- - -Canonical page: https://docs.shape.network/gasback -Markdown page: https://docs.shape.network/gasback.md - -# Gasback - -Claim back 80% of the sequencer fees that users spend interacting with your contracts on Shape. - -## What is Gasback? - -Shape redistributes the **majority of sequencer fees spent by users to execute transactions** back to the contracts they interacted with, ensuring the creators and platforms that thrive on the network share in its success. This concept is called **Gasback**. - -### I own a contract on Shape. How much gas do I get back? - -All contract owners can claim back **80%** of the [L2 Fees](https://docs.shape.network/building-on-shape/transaction-fees.md) generated from users interacting with their contracts on Shape. - -### How do I take part in Gasback? - -**Gasback** is open to all smart contract owners on Shape. There are two ways to register your contracts: - -1. [Register via the Dashboard](https://docs.shape.network/tutorials/registering-contract-gasback/dashboard.md) -2. [Register programmatically](https://docs.shape.network/tutorials/registering-contract-gasback/programmatically.md) - -Once registered, you'll be able to claim your share of the sequencer fees generated by your contracts' activity. - -> Learn how to -> [register your contracts for Gasback here](https://docs.shape.network/tutorials/registering-contract-gasback/index.md) -> . - ---- - -Canonical page: https://docs.shape.network/ -Markdown page: https://docs.shape.network/index.md - -# Welcome - -Shape is the culture-first L2 built on top of Ethereum to power the new NFT economy. - -The network is an open space where everyone is free to create whatever they want - from fine art, to weird experiments, to whole new ideas - making it the place for culture to take root. - -## Why create on Shape? - -### Shape Culture. Get Gasback. - -As a creator on Shape, you can claim back 80% of sequencer fees users spend interacting with your contracts. This includes contracts you build yourself, contracts you acquire ownership of, and contracts that you deploy through other platforms. - -> Learn more about how this works in [Gasback](https://docs.shape.network/gasback.md). - -### The best of Ethereum. - -Shape is [EVM equivalent](https://docs.shape.network/building-on-shape/differences-ethereum-shape.md). This means your creator experience is the same as on Ethereum, just at a fraction of the cost. - -### Secure, stable & scalable. - -Shape inherits its security directly from Ethereum, keeping the networks intrinsically linked forever. - -Shape also prioritizes stability and scalability, utilizing [Alchemy](https://docs.shape.network/building-on-shape/alchemy-api.md) and [Optimism](https://www.optimism.io/) as key infrastructure partners to help achieve and maintain these states. - -### Shape the Superchain. - -Shape is a member of the [Superchain](https://docs.optimism.io/stack/explainer), which unlocks a range of further benefits for the entire ecosystem - including ongoing network-level cooperation, funding of public goods, and additional builder incentives on Shape. - -### Home for unique NFT experiments - -Shape is the proof that NFTs aren't just static images that people can buy and sell. - -- Deep dive into the rabbit hole of onchain chemistry with [OTOM](https://docs.shape.network/building-on-shape/onchain-compatible/otom.md) by Kjetil Golid. -- Wander in Leander Herzog's [Infinite Garden](https://infinite-garden.xyz/) -- Create & craft your own [Assembly Items](https://docs.shape.network/building-on-shape/onchain-compatible/assembly.md) -- And [many more...](https://shape.network/) - ---- - -Canonical page: https://docs.shape.network/quick-start/connect-to-shape -Markdown page: https://docs.shape.network/quick-start/connect-to-shape.md - -# Connect to Shape - -Shape Mainnet runs on chain ID `360`. Shape Sepolia (testnet) runs on chain ID `11011`. - -> The public RPCs are rate-limited. For production apps, use [Alchemy](https://www.alchemy.com/rpc/shape) (`https://shape-mainnet.g.alchemy.com/v2/YOUR_KEY`). Free tier available. - -The examples below use viem v2+ and wagmi v2+. Both export `shape` and `shapeSepolia` chain definitions. - -## viem - -```ts -import { createPublicClient, http } from 'viem'; -import { shape } from 'viem/chains'; - -const client = createPublicClient({ - chain: shape, - transport: http('https://mainnet.shape.network'), -}); -``` - -For Shape Sepolia, use `shapeSepolia` and the testnet RPC: - -```ts -import { createPublicClient, http } from 'viem'; -import { shapeSepolia } from 'viem/chains'; - -const client = createPublicClient({ - chain: shapeSepolia, - transport: http('https://sepolia.shape.network'), -}); -``` - -## wagmi - -```ts -import { http, createConfig } from 'wagmi'; -import { shape, shapeSepolia } from 'wagmi/chains'; - -export const config = createConfig({ - chains: [shape, shapeSepolia], - transports: { - [shape.id]: http('https://mainnet.shape.network'), - [shapeSepolia.id]: http('https://sepolia.shape.network'), - }, -}); -``` - -## Foundry - -Add a profile to `foundry.toml`: - -```toml -# foundry.toml -[profile.shape-sepolia] -eth_rpc_url = "https://sepolia.shape.network" -chain_id = 11011 -``` - -## ethers.js v6 - -```ts -import { JsonRpcProvider } from 'ethers'; - -const provider = new JsonRpcProvider('https://mainnet.shape.network'); -``` - -## Network Reference - -| | Mainnet | Sepolia | -| --- | --- | --- | -| Chain ID | `360` | `11011` | -| RPC | `https://mainnet.shape.network` | `https://sepolia.shape.network` | -| Explorer | [shapescan.xyz](https://shapescan.xyz/) | [sepolia.shapescan.xyz](https://sepolia.shapescan.xyz/) | -| Currency | ETH | ETH | - -See [Network Information](https://docs.shape.network/technical-details/network-information.md) for the full reference. - ---- - -Canonical page: https://docs.shape.network/quick-start/deploy-a-contract -Markdown page: https://docs.shape.network/quick-start/deploy-a-contract.md - -# Deploy a Contract on Shape - -Deploy a smart contract to Shape Sepolia and verify it on the block explorer using Foundry. - -## Prerequisites - -- [Foundry](https://book.getfoundry.sh/getting-started/installation) installed -- Shape Sepolia ETH from the [Alchemy Faucet](https://www.alchemy.com/faucets/shape-sepolia) -- A wallet private key funded with testnet ETH - -## 1. Create a Project - -```bash -forge init my-shape-contract -cd my-shape-contract -``` - -This scaffolds a project with a `Counter.sol` contract in `src/`. - -## 2. Deploy - -```bash -forge create src/Counter.sol:Counter \ - --rpc-url https://sepolia.shape.network \ - --private-key $PRIVATE_KEY -``` - -Save the `Deployed to` address from the output. - -## 3. Verify on the Explorer - -```bash -forge verify-contract src/Counter.sol:Counter \ - --verifier blockscout \ - --verifier-url https://sepolia.shapescan.xyz/api/ -``` - -Replace `` with the address from step 2. - -## 4. Deploy to Mainnet - -When ready for mainnet, use the mainnet RPC and verify against the mainnet explorer: - -```bash -forge create src/Counter.sol:Counter \ - --rpc-url https://mainnet.shape.network \ - --private-key $PRIVATE_KEY -``` - -```bash -forge verify-contract src/Counter.sol:Counter \ - --verifier blockscout \ - --verifier-url https://shapescan.xyz/api/ -``` - -## 5. Register for Gasback - -Gasback returns 80% of sequencer fees to contract owners. Register your deployed contract to start earning. - -See [Registering Your Contract for Gasback](https://docs.shape.network/tutorials/registering-contract-gasback/index.md) for the full walkthrough. - -## Next Steps - -- [Build a dApp](https://docs.shape.network/building-on-shape/builder-kit.md) with the Shape Builder Kit -- [Connect to Shape](https://docs.shape.network/quick-start/connect-to-shape.md) from your frontend -- [Gasback](https://docs.shape.network/gasback.md) (how fee reclamation works) - ---- - -Canonical page: https://docs.shape.network/quick-start -Markdown page: https://docs.shape.network/quick-start/index.md - -# Start Building on Shape - -Shape is an EVM-compatible L2 on the [Optimism Superchain](https://www.optimism.io/superchain). Gasback returns 80% of sequencer fees to contract owners. - -- [Connect to Shape](https://docs.shape.network/quick-start/connect-to-shape.md): Configure viem, wagmi, Foundry, and ethers.js for Shape - -- [Deploy a Contract](https://docs.shape.network/quick-start/deploy-a-contract.md): Deploy and verify a smart contract with Foundry - -- [Build a dApp](https://docs.shape.network/building-on-shape/builder-kit.md): Scaffold a full-stack dApp with the Shape Builder Kit - -## Resources - -- [Shape Sepolia Faucet](https://www.alchemy.com/faucets/shape-sepolia) (testnet ETH) -- [Alchemy Dashboard](https://www.alchemy.com/dashboard) (API keys and enhanced RPCs) -- [Network Information](https://docs.shape.network/technical-details/network-information.md) (chain IDs, RPCs, explorers) -- [Shape Discord](https://discord.com/invite/shape-l2) (builder support) - ---- - -Canonical page: https://docs.shape.network/technical-details/contract-addresses -Markdown page: https://docs.shape.network/technical-details/contract-addresses.md - -# Contract Addresses - -## Mainnet - -### Ethereum (L1) - -| Name | Address | -| ----------------------------------- | -------------------------------------------- | -| `L2OutputOracleProxy` | `0x6Ef8c69CfE4635d866e3E02732068022c06e724D` | -| `OptimismPortalProxy` | `0xEB06fFa16011B5628BaB98E29776361c83741dd3` | -| `L1StandardBridgeProxy` | `0x62Edd5f4930Ea92dCa3fB81689bDD9b9d076b57B` | -| `AddressManager` | `0xcee78437aE9e15cee9c78E63757E0153c0FD7479` | -| `AnchorStateRegistryProxy` | `0x02987E7294379B9DDa99d593b0C94c68266222D1` | -| `DelayedWETHProxy` | `0xfEc7865DAc5139886585F03146Ff61D9b31c2d57` | -| `DisputeGameFactoryProxy` | `0x575Aecd84083f93877291901907698F7db0Bd8b0` | -| `L1CrossDomainMessengerProxy` | `0x2b18602877181C3cB72C687E2A771E123A3788E3` | -| `L1ERC721BridgeProxy` | `0xe9d3E49b0636016c5fE9eaA2347948D0bA9f15Af` | -| `Mips` | `0xD30c2Cd3cd6112E61FDfb03e4b232564d7e5C91f` | -| `OptimismMintableERC20FactoryProxy` | `0x319322906beAdf69dF5d4607169c63D692B1aDC1` | -| `PreimageOracle` | `0xDF6a16a71d0BC7a1Bbe8FffB33700eC3d9448A5B` | -| `ProtocolVersionsProxy` | `0xa77995E10b0A833CDD4fA414C26E869F7aa32DDd` | -| `ProxyAdmin` | `0x11B190Ae661c6d6884dFEE48E215691E0DdB842e` | -| `SuperchainConfigProxy` | `0x125664BEf08177ca43f6f301E63118b1e4cCDe09` | -| `SystemConfigProxy` | `0xfF11e41D5C4F522E423Ff6C064Ff8D55AF8f7355` | -| `SystemOwnerSafe` | `0xacAF178b5048CB56712dc59E95fBA72F7990A005` | - -### Shape Mainnet (L2) - -| Name | Address | -| ------------------------------- | -------------------------------------------- | -| `Gasback` | `0xf5e602c87d675E978F097503aedE4A766285a08B` | -| `RecipientValidator` | `0x12e50C2B9Dd2741bd07Df4E2E544f3412fd584cE` | -| `WETH9` | `0x4200000000000000000000000000000000000006` | -| `multicall3` | `0xca11bde05977b3631167028862be2a173976ca11` | -| `ImmutableCreate2Factory` | `0x0000000000ffe8b47b3e2130213b802212439497` | -| `Create2Deployer` | `0x13b0D85CcB8bf860b6b79AF3029fCA081AE9beF2` | -| `DeterministicDeploymentProxy` | `0x4e59b44847b379578588920ca78fbf26c0b4956c` | -| `Seaport 1.6` | `0x0000000000000068F116a894984e2DB1123eB395` | -| `ConduitController` | `0x00000000F9490004C11Cef243f5400493c00Ad63` | -| `GitcoinPassportDecoder` | `0x2443D22Db6d25D141A1138D80724e3Eee54FD4C2` | -| `GitcoinResolver` | `0x90E2C4472Df225e8D31f44725B75FFaA244d5D33` | -| `GitcoinVerifier` | `0x16db23c4b99bbC9A6Bf55dF7a787C9AEFD261185` | -| `GitcoinAttester` | `0xCc90105D4A2aa067ee768120AdA19886021dF422` | -| `L2CrossDomainMessenger` | `0x4200000000000000000000000000000000000007` | -| `L2StandardBridge` | `0x4200000000000000000000000000000000000010` | -| `SequencerFeeVault` | `0x4200000000000000000000000000000000000011` | -| `OptimismMintableERC20Factory` | `0x4200000000000000000000000000000000000012` | -| `GasPriceOracle` | `0x420000000000000000000000000000000000000F` | -| `GovernanceToken` | `0x4200000000000000000000000000000000000042` | -| `L1Block` | `0x4200000000000000000000000000000000000015` | -| `L2ToL1MessagePasser` | `0x4200000000000000000000000000000000000016` | -| `L2ERC721Bridge` | `0x4200000000000000000000000000000000000014` | -| `OptimismMintableERC721Factory` | `0x4200000000000000000000000000000000000017` | -| `ProxyAdmin` | `0x4200000000000000000000000000000000000018` | -| `BaseFeeVault` | `0x4200000000000000000000000000000000000019` | -| `L1FeeVault` | `0x420000000000000000000000000000000000001a` | -| `SchemaRegistry` | `0x4200000000000000000000000000000000000020` | -| `EAS` | `0x4200000000000000000000000000000000000021` | -| `BeaconBlockRoot` | `0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02` | -| `LegacyMessagePasser` | `0x4200000000000000000000000000000000000000` | -| `DeployerWhitelist` | `0x4200000000000000000000000000000000000002` | - -## Testnet (Sepolia) - -### Sepolia (L1) - -| Name | Address | -| ----------------------------------- | -------------------------------------------- | -| `AddressManager` | `0x42721d8512d62aA26B2Cfa1AE18bEEd5a9Ab1337` | -| `AnchorStateRegistryProxy` | `0x41ea3c370896632121Cdde1b94a4eCcf23DA4532` | -| `DelayedWETHProxy` | `0x7cc9cA91BA4f92F4C967E93a1AAd97beB18d3877` | -| `DisputeGameFactoryProxy` | `0x93eaa7A1E7d7af7eD9D612F9957988C8631c33e8` | -| `L1CrossDomainMessengerProxy` | `0xF9F730650e1AB4D23E2ac983934271ca7c5EF293` | -| `L1ERC721BridgeProxy` | `0x19f02c55254d2644eF94f30C74A932D64e1D4F86` | -| `L1StandardBridgeProxy` | `0x341ab1DAfdfB73b3D6D075ef10b29e3cACB2A653` | -| `L2OutputOracleProxy` | `0x532dDCed3440Eab81c529Ac8b0d7e429B5C05c52` | -| `Mips` | `0xaCf1Ed7357E41f652407ae6cFE1024705c758C38` | -| `OptimismMintableERC20FactoryProxy` | `0x46085E2e648488e49FBeaF6544b8e9Dc96df8BDd` | -| `OptimismPortalProxy` | `0xfF8Ca2B4d8122E41441F7ccDCf61b8692198Bd1E` | -| `PreimageOracle` | `0x8F3B1c59eD4439ebF564604aA4B93130DA4CD1D5` | -| `ProtocolVersionsProxy` | `0x8B901e6F6a49C950088d11C81166BCE2E3171C03` | -| `ProxyAdmin` | `0xd60a706Bf6108F090d055787B9B353FA7EEE1355` | -| `SuperchainConfigProxy` | `0xe5b3692266FF4Ab8A96A9C7Da6EeEe532CCc7916` | -| `SystemConfigProxy` | `0xa1aC91ED91EbE40E00d61E233c8026318b4da5fb` | -| `SystemOwnerSafe` | `0x4c4526C8C55c4e1a6F2aaf91e37f07c97786e0f5` | - -### Shape Sepolia (L2) - -| Name | Address | -| ------------------------------- | -------------------------------------------- | -| `Gasback` | `0xdF329d59bC797907703F7c198dDA2d770fC45034` | -| `WETH9` | `0x4200000000000000000000000000000000000006` | -| `L2CrossDomainMessenger` | `0x4200000000000000000000000000000000000007` | -| `L2StandardBridge` | `0x4200000000000000000000000000000000000010` | -| `SequencerFeeVault` | `0x4200000000000000000000000000000000000011` | -| `OptimismMintableERC20Factory` | `0x4200000000000000000000000000000000000012` | -| `GasPriceOracle` | `0x420000000000000000000000000000000000000F` | -| `GovernanceToken` | `0x4200000000000000000000000000000000000042` | -| `L1Block` | `0x4200000000000000000000000000000000000015` | -| `L2ToL1MessagePasser` | `0x4200000000000000000000000000000000000016` | -| `L2ERC721Bridge` | `0x4200000000000000000000000000000000000014` | -| `OptimismMintableERC721Factory` | `0x4200000000000000000000000000000000000017` | -| `ProxyAdmin` | `0x4200000000000000000000000000000000000018` | -| `BaseFeeVault` | `0x4200000000000000000000000000000000000019` | -| `L1FeeVault` | `0x420000000000000000000000000000000000001a` | -| `SchemaRegistry` | `0x4200000000000000000000000000000000000020` | -| `EAS` | `0x4200000000000000000000000000000000000021` | -| `BeaconBlockRoot` | `0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02` | -| `LegacyMessagePasser` | `0x4200000000000000000000000000000000000000` | -| `DeployerWhitelist` | `0x4200000000000000000000000000000000000002` | -| `LegacyERC20ETH` | `0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000` | - ---- - -Canonical page: https://docs.shape.network/technical-details/network-information -Markdown page: https://docs.shape.network/technical-details/network-information.md - -# Network Information - -## Mainnet - -| Network Name | Shape | -| --------------- | ----------------------------------------------- | -| Chain ID | `360` | -| Currency Symbol | `ETH` | -| RPC Endpoint | `https://mainnet.shape.network` | -| Block Explorer | [https://shapescan.xyz](https://shapescan.xyz/) | - -## Testnet - -| Network Name | Shape Sepolia | -| --------------- | --------------------------------------------------------------------------------- | -| Chain ID | `11011` | -| Currency Symbol | `ETH` | -| RPC Endpoint | `https://sepolia.shape.network` | -| Block Explorer | [https://sepolia.shapescan.xyz](https://sepolia.shapescan.xyz/) | - -> For production systems or high throughput testing, we recommend using a node from -> [Alchemy](https://www.alchemy.com/supernode), one of our node providers. - ---- - -Canonical page: https://docs.shape.network/technical-details/run-a-node -Markdown page: https://docs.shape.network/technical-details/run-a-node.md - -# Run a Node - -Shape is an [OP Stack](https://docs.optimism.io/stack/getting-started) rollup. Running a Shape node requires two clients that talk over the [Engine API](https://github.com/ethereum/execution-apis/blob/main/src/engine/common.md) and authenticate with a shared JWT secret: - -- **Execution client (op-geth)** runs the EVM and stores chain state. -- **Consensus client (op-node)** derives the L2 chain from L1 data and feeds blocks to the execution client. - -## Prerequisites - -### Hardware requirements - -| Component | Full node | Archive node | -| --------- | --------- | ------------ | -| CPU | Reasonably modern, multi-core | Same | -| RAM | 16 GB minimum | 16 GB minimum | -| Storage | 700 GB+ SSD (grows ~100 GB / 6 months) | 14 TB+ NVMe SSD (grows ~3.5 TB / 6 months) | - -Archive nodes should use NVMe SSDs. op-geth's `--datadir.ancient` flag can offload older data to a cheaper HDD. - -### Software dependencies - -- [Go](https://go.dev/dl/) 1.21+ -- [just](https://github.com/casey/just#installation) (op-node build tool) -- Make (op-geth build tool) -- Git -- An **L1 Ethereum RPC endpoint** (e.g., [Alchemy](https://www.alchemy.com/), Infura, or your own node) -- An **L1 Beacon (consensus) endpoint** (required since Ecotone for blob retrieval) - -### Network ports - -Expose the following ports for P2P sync: - -| Port | Protocol | Purpose | -| ----- | -------- | ------- | -| 30303 | TCP + UDP | op-geth peer discovery and block propagation | -| 9222 | TCP + UDP | op-node peer discovery | - -## Choose paths - -The commands below assume these shell variables: - -```bash -export OP_GETH_DIR=$HOME/op-geth -export OPTIMISM_DIR=$HOME/optimism -export OP_NODE_DIR=$OPTIMISM_DIR/op-node -export DATADIR=$HOME/.shape -export CONFIG_DIR=$HOME/.shape-config - -mkdir -p "$DATADIR/geth" "$CONFIG_DIR" -``` - -Adjust them if you want different locations. - -## Build the clients - -Build both binaries first. You need the same `op-geth` and `op-node` binaries whether you sync from a snapshot or from genesis. - -### 1. Build op-geth - -```bash -git clone https://github.com/ethereum-optimism/op-geth.git "$OP_GETH_DIR" -cd "$OP_GETH_DIR" -git checkout -make geth -``` - -Check [op-geth releases](https://github.com/ethereum-optimism/op-geth/releases) for the required release branch. - -### 2. Build op-node - -```bash -git clone https://github.com/ethereum-optimism/optimism.git "$OPTIMISM_DIR" -cd "$OPTIMISM_DIR" -git checkout -cd "$OP_NODE_DIR" -just -``` - -Check [optimism releases](https://github.com/ethereum-optimism/optimism/releases) for the required release branch. - -## Option A: Sync from snapshot (fastest) - -[Alchemy snapshots](https://www.alchemy.com/snapshots/shape) let you skip the full sync by downloading a compressed chaindata archive and starting near the chain tip. - -### 1. Download the snapshot - -Visit [alchemy.com/snapshots/shape](https://www.alchemy.com/snapshots/shape) and download the latest `.tar.lz4` snapshot for your network (mainnet or Sepolia). - -### 2. Install lz4 and decompress - -```bash -# macOS -brew install lz4 - -# Ubuntu/Debian -sudo apt-get install -y lz4 -``` - -If you have existing data, stop your node and clear the old chaindata first: - -```bash -rm -rf "$DATADIR/geth/chaindata" -rm -rf "$DATADIR/geth/lightchaindata" -``` - -Decompress the snapshot: - -```bash -lz4 -c -d .tar.lz4 | tar -x -C "$DATADIR/geth/" -``` - -### 3. Download the rollup config - -Save the `rollup.json` for your network to `$CONFIG_DIR/rollup.json`: - -**Shape Mainnet:** -- [rollup.json](https://arweave.net/Lh9vjNsHKHOKzGwWwlvVz2tsxcL_h5Wc-Ga0udO3Xm0) - -**Shape Sepolia:** -- [rollup.json](https://arweave.net/gSb3hOzLaBIBy-AyWA2O2_03sfXJ-IwPqmV6Mhstmj8) - -### 4. Continue to [Configure and run](#configure-and-run) - -Your node should be in sync within minutes of starting. - -## Option B: Sync from genesis - -### 1. Download genesis and rollup configs - -Save the files for your network to `$CONFIG_DIR/rollup.json` and `$CONFIG_DIR/genesis.json`: - -**Shape Mainnet:** -- [rollup.json](https://arweave.net/Lh9vjNsHKHOKzGwWwlvVz2tsxcL_h5Wc-Ga0udO3Xm0) -- [genesis.json](https://arweave.net/LrSrsEJsUtSWNAzkpKqkwE9RG3JZP1SmlOQNlTu8Nxk) - -**Shape Sepolia:** -- [rollup.json](https://arweave.net/gSb3hOzLaBIBy-AyWA2O2_03sfXJ-IwPqmV6Mhstmj8) -- [genesis.json](https://arweave.net/nw6opum2ALT9T39TSAAK_Wq0Z75aZJWd6J2RmiWHm_s) - -### 2. Initialize the datadir - -```bash -"$OP_GETH_DIR/build/bin/geth" init --datadir="$DATADIR" "$CONFIG_DIR/genesis.json" -``` - -### 3. Continue to [Configure and run](#configure-and-run) - -## Configure and run - -### 1. Generate a JWT secret - -op-geth and op-node authenticate over the Engine API with a shared secret. Save it to `$CONFIG_DIR/jwt.txt`: - -```bash -openssl rand -hex 32 > "$CONFIG_DIR/jwt.txt" -``` - -### 2. Start op-geth - -**Shape Mainnet:** - -```bash -"$OP_GETH_DIR/build/bin/geth" \ - --datadir="$DATADIR" \ - --http \ - --http.port=8545 \ - --http.addr=0.0.0.0 \ - --http.api=eth,net,web3 \ - --ws \ - --ws.port=8546 \ - --ws.addr=0.0.0.0 \ - --ws.api=eth,net,web3 \ - --authrpc.addr=localhost \ - --authrpc.port=8551 \ - --authrpc.jwtsecret="$CONFIG_DIR/jwt.txt" \ - --authrpc.vhosts=* \ - --verbosity=3 \ - --rollup.sequencerhttp=https://mainnet.shape.network \ - --rollup.disabletxpoolgossip=true \ - --syncmode=snap -``` - -**Shape Sepolia:** Replace `--rollup.sequencerhttp` with `https://sepolia.shape.network`. - -**For archive mode:** Add `--gcmode=archive` and change `--syncmode=full`. - -### 3. Start op-node - -Set your L1 endpoints: - -```bash -export L1_RPC_URL= # e.g., https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY -export L1_RPC_KIND= # alchemy, quicknode, infura, basic, etc. -export L1_BEACON_URL= # e.g., https://ethereum-beacon-api.publicnode.com -``` - -**Shape Mainnet:** - -```bash -"$OP_NODE_DIR/bin/op-node" \ - --l1=$L1_RPC_URL \ - --l1.rpckind=$L1_RPC_KIND \ - --l1.beacon=$L1_BEACON_URL \ - --l2=ws://localhost:8551 \ - --l2.jwt-secret="$CONFIG_DIR/jwt.txt" \ - --rollup.config="$CONFIG_DIR/rollup.json" \ - --l2.enginekind=geth \ - --syncmode=execution-layer \ - --override.granite=1727370000 \ - --override.holocene=1739880000 \ - --override.isthmus=1774530000 \ - --p2p.listen.tcp=9222 \ - --p2p.listen.udp=9222 \ - --rpc.addr=127.0.0.1 \ - --rpc.port=9545 \ - --metrics.enabled \ - --metrics.port=7300 -``` - -**Shape Sepolia:** - -```bash -"$OP_NODE_DIR/bin/op-node" \ - --l1=$L1_RPC_URL \ - --l1.rpckind=$L1_RPC_KIND \ - --l1.beacon=$L1_BEACON_URL \ - --l2=ws://localhost:8551 \ - --l2.jwt-secret="$CONFIG_DIR/jwt.txt" \ - --rollup.config="$CONFIG_DIR/rollup.json" \ - --l2.enginekind=geth \ - --syncmode=execution-layer \ - --override.ecotone=0 \ - --override.fjord=1721732400 \ - --override.granite=1727197200 \ - --override.holocene=1739880000 \ - --override.isthmus=1763650800 \ - --p2p.listen.tcp=9222 \ - --p2p.listen.udp=9222 \ - --rpc.addr=127.0.0.1 \ - --rpc.port=9545 \ - --metrics.enabled \ - --metrics.port=7300 -``` - -For Sepolia, use a Sepolia L1 RPC for `L1_RPC_URL`. - -> **Do not expose the op-node RPC publicly.** The `--rpc.addr` should be `127.0.0.1` (localhost) unless you have a specific reason and a firewall in place. - -### Sync modes - -| Mode | op-node flag | op-geth flag | Use case | -| ---- | ------------ | ------------ | -------- | -| Snap sync | `--syncmode=execution-layer` | `--syncmode=snap` (default) | Downloads state at chain tip via P2P. Fastest for full nodes. | -| Full sync | `--syncmode=execution-layer` | `--syncmode=full` | Executes every block. Required for archive nodes. | - -## Verifying your node - -After startup, look for: - -1. op-geth logs showing `Syncing beacon headers` as it downloads headers from peers. -2. op-geth logs showing state download progress (percentage and data volumes). -3. Once caught up, both clients log new blocks every 2 seconds. - -Check sync status via JSON-RPC: - -```bash -curl -s -X POST http://localhost:8545 \ - -H "Content-Type: application/json" \ - -d '{"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}' -``` - -Returns `false` when fully synced. - -## Monitoring - -op-node exposes Prometheus metrics at `http://localhost:7300/metrics` when started with `--metrics.enabled`. - -| Metric | What it tells you | -| ------ | ----------------- | -| `op_node_default_refs_number` | Current L1/L2 block heights. If these stall, sync has stopped. | -| `op_node_default_p2p_peer_count` | Connected peers. Zero means the node falls back to slow L1-only derivation. | -| `op_node_default_rpc_client_request_duration_seconds` | RPC call latency. Spikes usually point to your L1 provider. | - -## Blob archiver - -Since Ecotone, batch data is posted as [EIP-4844 blobs](https://eips.ethereum.org/EIPS/eip-4844). Standard beacon nodes prune blobs after ~18 days. - -You need a blob archiver if your node may go offline for 18+ days or you are syncing from genesis without a recent snapshot. - -Options: -1. Run an L1 beacon node with pruning disabled (e.g., Lighthouse with `--prune-blobs=false`) -2. Use a third-party beacon endpoint that retains blobs beyond the 18-day window - -Point op-node at a fallback endpoint that has the old blobs: - -```bash ---l1.beacon-fallbacks= -``` - -## Troubleshooting - -### Node stalling or can't find peers - -Pass the bootnode enodes directly to op-node with `--p2p.bootnodes`: - -**Shape Mainnet:** - -``` ---p2p.bootnodes=enode://ae31be7c6596f4bc3657f90b65a1569c7b0db10c976649f06fe5cfb26139064d78d22b41aede293aa7358fc336d086051ac7fce78f063dce89e1da19c7b88aee@34.228.226.23:0?discport=30301,enode://0bea78f02c9bee58326b3a612dae63dc5a0193fb3dfc9be687c9757d25606405ef9f87810157598fce35688bdb5b3834dc6283afab6dc5774abbd6c5a7b17cea@3.85.27.162:0?discport=30301 -``` - -**Shape Sepolia:** - -``` ---p2p.bootnodes=enode://34fc07c447b843f3915f72cae27daeda7f2f8c3ea4b9132aed188387d3208d1d5cd7eeea58d30d038c14f985a5b108ad6b2172815ed8b757c9de9f609741b2a6@34.228.9.78:0?discport=30301,enode://61841b7682f808f5ce8222f15d7de7f118a2c2c3e342fe42ea41e987ae22fb90e49ef2b5f394897e791c33c6fc59d7ad064851ee653badb2d6ece7a94040944b@54.91.75.177:0?discport=30301 -``` - -### 401 Unauthorized: signature invalid - -The JWT secret doesn't match between op-node and op-geth. Ensure both point to the same `jwt.txt` file. - -### 403 Forbidden: invalid host specified - -Add `--authrpc.vhosts=*` to op-geth, or set it to the specific hostname op-node uses to connect. - -### P2P directory permission denied - -op-node can't write to its P2P discovery directory. Either grant write access or redirect with: - -```bash ---p2p.discovery.path=/path/with/write/access ---p2p.peerstore.path=/path/with/write/access -``` - -### Wrong chain / mismatched genesis - -Verify that: -- `L1_RPC_URL` points to the correct L1 network (Ethereum mainnet for Shape, Sepolia for Shape Sepolia) -- `rollup.json` matches the network you intend to run -- op-geth was initialized with the correct `genesis.json` - -### Unclean shutdown detected - -op-geth prints this warning on startup after a crash or kill. It usually recovers on its own. If the database is unrecoverable, re-initialize from genesis or restore from a [snapshot](https://www.alchemy.com/snapshots/shape). - -## References - -- [Optimism node operator docs](https://docs.optimism.io/node-operators/overview) -- [Run a node from source (OP docs)](https://docs.optimism.io/node-operators/tutorials/run-node-from-source) -- [Build from source (OP docs)](https://docs.optimism.io/node-operators/tutorials/node-from-source) -- [Alchemy Shape snapshots](https://www.alchemy.com/snapshots/shape) -- [op-node configuration reference](https://docs.optimism.io/node-operators/reference/op-node-config) -- [op-geth configuration reference](https://docs.optimism.io/node-operators/reference/op-geth-config) -- [OP Stack troubleshooting](https://docs.optimism.io/node-operators/guides/troubleshooting) - ---- - -Canonical page: https://docs.shape.network/the-stack -Markdown page: https://docs.shape.network/the-stack.md - -# The Stack - -The **Stack** is a dynamic NFT that serves as a living record of your achievements and contributions across the Shape ecosystem. - -By engaging with projects on Shape, you earn medals that showcase your journey and build your reputation in the community. - -## Getting Started - -### 1. Mint Your Stack - -Start by minting your Stack at [stack.shape.network](https://stack.shape.network/) - -### 2. Engage with Projects - -Engage with different projects in various ways on Shape. Interactions include: - -- Collecting NFTs -- Minting new creations -- Bidding on artwork auctions -- Exploring apps, games, and experiments - -### 3. Earn Medals - -As you engage, you'll earn medals issued by the community projects you interact with. There are 4 types of medals: - -- **Bronze (🟤):** Awarded for initial interactions -- **Silver (⚪):** Awarded for deeper involvement -- **Gold (🟡):** Awarded for significant contributions -- **Special (⚫):** Awarded for exceptional achievements - -### 4. Claim Medals - -Once a medal has been earned, you can claim it via your Stack dashboard. - -Your Stack NFT will dynamically update as you claim medals. - -### 5. Climb Ranks - -As you earn medals, you climb ranks in the [Leaderboard](https://stack.shape.network/leaderboard). - -Higher ranks may grant access to exclusive opportunities, such as allowlist spots for future Stack projects. - -## The Stack Keeps Stacking - -New projects and medals are added regularly. - -Stay up to date by following [@shape](https://twitter.com/shape) for the latest news. - -> Do you have a project you'd like to make part of the Stack? -> -> Reach out on [Twitter/X](https://x.com/shape) or in -> [Discord](https://discord.com/invite/shape-l2) to let us know. - ---- - -Canonical page: https://docs.shape.network/tools/account-abstraction -Markdown page: https://docs.shape.network/tools/account-abstraction.md - -# Account Abstraction - -On Shape, combine AA with [Gasback](https://docs.shape.network/gasback.md) to subsidize your users and recoup 80% of sequencer fees. - -| Tool | Use case | -| --- | --- | -| Alchemy Bundler + Gas Manager | Full AA stack: bundled UserOps, gas sponsorship | -| Alchemy Embedded Accounts | Email/social login, no seed phrase | -| Alchemy Smart Accounts | Programmable accounts with custom validation | -| Crossmint NFT Checkout | Credit card NFT purchases, no wallet needed | -| Crossmint WaaS | Invisible wallets embedded in your app | - -See [Alchemy's AA overview](https://www.alchemy.com/learn/account-abstraction) for background. - -- [Alchemy Bundler](https://www.alchemy.com/account-abstraction-infrastructure): A highly reliable ERC-4337 bundler - -- [Alchemy Gas Manager](https://www.alchemy.com/gas-manager): Sponsor gas for your users - -- [Alchemy Embedded Accounts](https://www.alchemy.com/embedded-accounts): Bring users onchain in seconds. No seed phrase, no gas - -- [Alchemy Smart Accounts](https://www.alchemy.com/account-contracts): Fully abstract the user experience with secure & extensible smart accounts - -- [Crossmint NFT Checkout](https://www.crossmint.com/products/nft-checkout): Sell NFTs via credit cards and cross-chain payments - -- [Crossmint Wallet-as-a-Service](https://www.crossmint.com/): Invisible wallets, embedded in your app - ---- - -Canonical page: https://docs.shape.network/tools/bridges -Markdown page: https://docs.shape.network/tools/bridges.md - -# Bridges - -Bridge ETH and tokens between Ethereum and Shape. - -## Mainnet - -- [Relay](https://relay.link/shape): Instant bridging & cross-chain execution - -- [Superbridge](https://superbridge.app/shape-mainnet): Fast and secure native bridging - -- [Alchemy](https://shape-mainnet.bridge.alchemy.com/) - -## Sepolia - -- [Relay (Sepolia)](https://testnets.relay.link/bridge/shape-sepolia) - -- [Superbridge (Sepolia)](https://superbridge.app/shape-testnet) - ---- - -Canonical page: https://docs.shape.network/tools/data-indexers -Markdown page: https://docs.shape.network/tools/data-indexers.md - -# Data Indexers - -| Service | Best for | -| --- | --- | -| Alchemy NFT/Token/Transfers APIs | General-purpose queries, NFT metadata, token balances | -| Alchemy Subgraphs | Custom GraphQL queries on indexed contract events | -| Alchemy Webhooks | Real-time notifications (transfers, mints, contract events) | -| Goldsky | Streaming onchain data to your database (Postgres, Kafka) | -| Reservoir | NFT marketplace data (listings, sales, collection stats) | -| SimpleHash | Cross-chain NFT and token metadata aggregation | - -Fetch NFTs owned by an address using the Alchemy NFT API: - -```ts -const res = await fetch( - `https://shape-mainnet.g.alchemy.com/nft/v3/${ALCHEMY_KEY}/getNFTsForOwner?owner=${address}` -); -const { ownedNfts } = await res.json(); -``` - -- [Alchemy NFT API](https://www.alchemy.com/nft-api): An API to launch, verify, analyze, trade & display NFTs - -- [Alchemy Subgraphs](https://www.alchemy.com/subgraphs): A fast & reliable GraphQL API - -- [Alchemy Token API](https://www.alchemy.com/token-api): Complete token data, no token list required - -- [Alchemy Transfers API](https://www.alchemy.com/transfers-api): Retrieve all historical transaction activity, including internal transfers - -- [Alchemy Webhooks](https://www.alchemy.com/webhooks): Realtime notifications for your users - -- [Goldsky](https://goldsky.com/): Livestream onchain data to your database - -- [Reservoir](https://reservoir.tools/): From market data to metadata, Reservoir APIs provide all-in-one endpoints - -- [SimpleHash](https://simplehash.com/): Instant access to Token & NFT market prices, metadata and media - ---- - -Canonical page: https://docs.shape.network/tools/explorers -Markdown page: https://docs.shape.network/tools/explorers.md - -# Explorers - -| Explorer | Focus | -| --- | --- | -| Shapescan | Block explorer: transactions, contracts, verification | -| Shapescan Sepolia | Testnet block explorer | -| Deca | NFT explorer: collections, metadata, floor prices | -| Zapper | Portfolio and activity feed in a human-readable format | - -Verify your contracts on Shapescan to make them readable. See [Deploy a Contract](https://docs.shape.network/quick-start/deploy-a-contract.md) for verification steps. - -- [Shape Mainnet Explorer](https://shapescan.xyz/) - -- [Shape Sepolia Testnet Explorer](https://explorer-sepolia.shape.network/) - -- [Deca](https://deca.art/): See all NFTs on Shape in one place - -- [Zapper](https://zapper.xyz/): See what's happening onchain in a human readable way - ---- - -Canonical page: https://docs.shape.network/tools/faucets -Markdown page: https://docs.shape.network/tools/faucets.md - -# Faucets - -Get free testnet ETH on Shape Sepolia for development. - -1. Go to the Alchemy or Optimism faucet -2. Sign in with an account (free tier works) -3. Enter your wallet address -4. Receive testnet ETH (usually within seconds) - -- [Alchemy Faucet](https://www.alchemy.com/faucets/shape-sepolia) - -- [Optimism Faucet](https://console.optimism.io/faucet) - -> You can also [bridge Sepolia ETH](https://docs.shape.network/tools/bridges.md) to get started. - ---- - -Canonical page: https://docs.shape.network/tools/node-providers -Markdown page: https://docs.shape.network/tools/node-providers.md - -# Node Providers - -| Provider | Endpoint | Notes | -| --- | --- | --- | -| Public RPC | `https://mainnet.shape.network` | Rate-limited, not for production | -| Alchemy | `https://shape-mainnet.g.alchemy.com/v2/YOUR_KEY` | Higher limits, WebSocket, enhanced APIs | - -Sepolia: `https://sepolia.shape.network` (public) or `https://shape-sepolia.g.alchemy.com/v2/YOUR_KEY` (Alchemy). - -WebSocket: `wss://shape-mainnet.g.alchemy.com/v2/YOUR_KEY` - -The public RPC is rate-limited and not suitable for production. Use [Alchemy](https://www.alchemy.com/rpc/shape) (free tier available). - -- [Alchemy Supernode](https://www.alchemy.com/rpc/shape): A highly reliable RPC - ---- - -Canonical page: https://docs.shape.network/tools/oracles/gelato-vrf -Markdown page: https://docs.shape.network/tools/oracles/gelato-vrf.md - -# Gelato VRF - -- **Mechanism**: Uses [Drand](https://drand.love/), a decentralized source for random numbers. -- **Benefits**: Provides genuine, verifiable random values for blockchain applications. - -## Applications of Gelato VRF - -- **Gaming and Gambling**: For fair outcomes in online games and decentralized gambling. -- **Decentralized Finance (DeFi)**: Random selections for lotteries in DeFi protocols. -- **NFT Generation**: Random trait generation for unique digital assets. -- **Protocol Decision Making**: Randomized selections for validators or jurors. - -## Steps to Set Up Gelato VRF - -1. **Set Up Development Environment**: Install either Foundry or Hardhat. -2. **Install Gelato VRF Contracts**: Use specific commands for Hardhat or Foundry. -3. **Inherit** `GelatoVRFConsumerBase` **Contract**: Incorporate it into your contract. -4. **Request Randomness**: Call `_requestRandomness()` function. -5. **Implement Callback Function**: Define how your contract handles the randomness response. -6. **Include** `dedicated msg.sender`: Essential for contract security and function. - -## Quick Start - -### Step 1: Set Up Your Development Environment - -Make sure you have Hardhat or Foundry ready for use. - -### Step 2: Install Gelato VRF Contracts - -For Hardhat, clone the repository and set up the environment. For Foundry, use the `forge install` command. - -### Step 3: Inherit GelatoVRFConsumerBase Contract - -Create a contract that inherits from **GelatoVRFConsumerBase**. - -```solidity -// SPDX-License-Identifier: MIT -pragma solidity 0.8.18; - -import {GelatoVRFConsumerBase} from "./GelatoVRFConsumerBase.sol"; - -contract YourContract is GelatoVRFConsumerBase { - // Your contract's code -} -``` - -### Step 4: Request Randomness - -To request randomness, call the \_requestRandomness() function. You should protect the call since it will take from your 1Balance. The data argument will be passed back to you by the W3F. - -```solidity -function requestRandomness(bytes memory data) external { - require(msg.sender == ...); - uint64 requestId = _requestRandomness(data); -} -``` - -### Step 5: Implement Callback Function - -```solidity -function _fulfillRandomness( - bytes32 randomness, - uint64 requestId, - bytes memory data -) internal override { - // Your implementation here -} -``` - -### Step 6: Include Dedicated msg.sender - -When you're ready to deploy your Gelato VRF-compatible contract, an important step is to include the dedicated msg.sender as a constructor parameter. This ensures that your contract is set up to work with the correct operator for fulfilling the randomness requests. It's crucial for ensuring that only authorized requests are processed. - -```solidity -// SPDX-License-Identifier: MIT -pragma solidity 0.8.18; - -import {GelatoVRFConsumerBase} from "./GelatoVRFConsumerBase.sol"; - -contract YourContract is GelatoVRFConsumerBase { - constructor(address operator) - GelatoVRFConsumerBase(operator) { - // Additional initializations - } - - // The rest of your contract code -} -``` - -## Task Creation - -Upon deploying your contract, you will need to create a Gelato Task. This can be done via the [Gelato UI](https://app.gelato.network/). Next, you will be prompted to provide the address of the Request Contract to which the Gelato nodes should respond. Enter the address of your contract, and once all details have been correctly entered, proceed with launching your Gelato VRF instance. - -Now everytime you call the `_requestRandomness()` function, the Gelato nodes will respond with a random number that you can use in your contract. - -For more detailed information, refer to the [Gelato VRF documentation](https://docs.gelato.network/web3-services/vrf). - -![Gelato VRF 1](https://docs.shape.network/gelato-gui-1.webp) - -![Gelato VRF 2](https://docs.shape.network/gelato-gui-2.webp) - ---- - -Canonical page: https://docs.shape.network/tools/safes-asset-security -Markdown page: https://docs.shape.network/tools/safes-asset-security.md - -# Safes & Asset Security - -Manage high-value assets and team operations securely on Shape. - -- **Safe**: Multi-signature wallet for team treasuries, protocol governance, or any operation requiring multiple approvals. Shape's Safe is at [safe.shape.network](https://safe.shape.network/). -- **Delegate**: Prove NFT ownership or claim airdrops from a hot wallet without moving assets from cold storage. - -- [Safe](https://safe.shape.network/): A decentralized custody protocol and collective asset management platform - -- [Delegate](https://delegate.xyz/): Claim airdrops, mint NFTs, and prove ownership via your hot wallet - ---- - -Canonical page: https://docs.shape.network/tools/sybil-resistance -Markdown page: https://docs.shape.network/tools/sybil-resistance.md - -# Sybil Resistance - -Protect your app from bots and sybil attacks while preserving user privacy. - -- **Passport**: Privacy-preserving identity scoring. Good for gating access, weighting rewards, detecting bots. -- **Premint**: Allowlist management for mints. Good for curated drops, community-first launches. -- **Crossmint Verifiable Credentials**: Issue and verify credentials at scale. Good for KYC-lite, compliance, loyalty programs. - -- [Passport](https://app.passport.xyz/#/shape/): A tool for dApps to defend against sybils while preserving user privacy - -- [Premint](https://www.premint.xyz/): Create allowlists tailored to your requirements - -- [Crossmint Verifiable Credentials](https://www.crossmint.com/products/verifiable-credentials): Issue and verify credentials at scale - ---- - -Canonical page: https://docs.shape.network/tutorials/mint-nft-collection -Markdown page: https://docs.shape.network/tutorials/mint-nft-collection.md - -# Launch an NFT Collection on Shape - -Deploy an ERC-721 contract to Shape Sepolia, mint an NFT, and verify it on the block explorer. - -## Prerequisites - -- [Foundry](https://book.getfoundry.sh/getting-started/installation) installed -- Shape Sepolia ETH from the [Alchemy Faucet](https://www.alchemy.com/faucets/shape-sepolia) -- A wallet private key funded with testnet ETH - -## 1. Set Up the Project - -```bash -forge init my-nft && cd my-nft -rm src/Counter.sol test/Counter.t.sol script/Counter.s.sol -forge install OpenZeppelin/openzeppelin-contracts --no-commit -``` - -Add the `remappings` line to `foundry.toml`: - -```toml -[profile.default] -src = "src" -out = "out" -libs = ["lib"] -remappings = ["@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/"] -``` - -## 2. Write the Contract - -Create `src/MyNFT.sol`: - -```solidity -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.20; - -import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; - -contract MyNFT is ERC721, Ownable { - uint256 public totalSupply; - uint256 public constant MAX_SUPPLY = 1000; - string private _baseTokenURI; - - constructor() ERC721("MyNFT", "MNFT") Ownable(msg.sender) {} - - function mint(address to) external onlyOwner { - require(totalSupply < MAX_SUPPLY, "Max supply reached"); - _mint(to, totalSupply); - totalSupply++; - } - - function setBaseURI(string calldata baseURI) external onlyOwner { - _baseTokenURI = baseURI; - } - - function _baseURI() internal view override returns (string memory) { - return _baseTokenURI; - } -} -``` - -## 3. Test - -Create `test/MyNFT.t.sol`: - -```solidity -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.20; - -import {Test} from "forge-std/Test.sol"; -import {MyNFT} from "../src/MyNFT.sol"; - -contract MyNFTTest is Test { - MyNFT nft; - - function setUp() public { - nft = new MyNFT(); - } - - function test_mint() public { - nft.mint(address(this)); - assertEq(nft.ownerOf(0), address(this)); - assertEq(nft.totalSupply(), 1); - } -} -``` - -```bash -forge test -``` - -## 4. Deploy to Shape Sepolia - -```bash -export PRIVATE_KEY= - -forge create src/MyNFT.sol:MyNFT \ - --rpc-url https://sepolia.shape.network \ - --private-key $PRIVATE_KEY -``` - -Save the `Deployed to` address from the output. - -## 5. Mint an NFT - -```bash -cast send "mint(address)" \ - --rpc-url https://sepolia.shape.network \ - --private-key $PRIVATE_KEY -``` - -Confirm the mint: - -```bash -cast call "ownerOf(uint256)" 0 \ - --rpc-url https://sepolia.shape.network -``` - -This returns your address (ABI-encoded, zero-padded to 32 bytes). - -## 6. Optional: Let Users Mint From Another Chain - -If your mint UI should let users start from Ethereum, Base, Arbitrum, or another supported chain, use Relay cross-chain call execution. The UI can let the user pay from an origin-chain balance while Relay executes the NFT mint call on Shape. - -The most important contract detail is to mint to an explicit recipient, like `mint(address to)`, instead of relying only on `msg.sender`. Relay's Shape-side address executes the destination call, so your UI should encode the buyer's address into the mint calldata and your contract should allow the Relay address to call that mint path. Treat this as a narrow exception: most arbitrary addresses should still be blocked from minting this way, but the Relay executor or relayer address you configure for Shape needs permission to call the function and mint the NFT to the recipient. - -```ts -import { getClient } from '@relayprotocol/relay-sdk'; -import { encodeFunctionData, parseEther, zeroAddress } from 'viem'; - -const relayClient = getClient(); -const shapeSepoliaChainId = 11011; // Use 360 for Shape mainnet. -const mintPrice = parseEther('0.01'); - -const callData = encodeFunctionData({ - abi: nftAbi, - functionName: 'mint', - args: [userAddress], -}); - -const quote = await relayClient.actions.getQuote({ - wallet, - chainId: originChainId, - toChainId: shapeSepoliaChainId, - currency: zeroAddress, - toCurrency: zeroAddress, - user: userAddress, - recipient: userAddress, - amount: mintPrice.toString(), - tradeType: 'EXACT_OUTPUT', - txs: [ - { - to: nftContractAddress, - value: mintPrice.toString(), - data: callData, - }, - ], -}); - -await relayClient.actions.execute({ - quote, - wallet, - onProgress: (progress) => { - // Use this to show states like: - // confirm in wallet -> origin transaction submitted -> relaying -> minted - }, -}); -``` - -For a free mint, set the mint transaction `value` and quote `amount` to `"0"`. For a paid mint, use `EXACT_OUTPUT` with the exact ETH value your mint call requires on Shape. Keep quotes fresh, check the user's origin-chain balance before enabling the mint button, and show a clear error if Relay has insufficient liquidity or the user lacks enough ETH for the amount, Relay fees, and origin-chain gas. - -The Stack mint UI uses the same pattern, with one extra convenience: users can optionally send additional ETH to themselves on Shape in the same Relay execution. That is just a second transaction in `txs` and is useful for onboarding, but most mint UIs only need the Shape contract call. - -See Relay's [Call Execution Integration Guide](https://docs.relay.link/references/api/api_guides/calling-integration-guide#common-use-cases) for the full quote, execution, and status flow. - -## 7. Verify on Shapescan - -```bash -forge verify-contract src/MyNFT.sol:MyNFT \ - --verifier blockscout \ - --verifier-url https://sepolia.shapescan.xyz/api/ -``` - -Once verified, view your contract at `https://sepolia.shapescan.xyz/address/`. - -## 8. Register for Gasback - -Register your contract for [Gasback](https://docs.shape.network/tutorials/registering-contract-gasback/index.md) to reclaim 80% of sequencer fees users spend interacting with it. - -## Next Steps - -- **Deploy to mainnet**: Use `--rpc-url https://mainnet.shape.network` and verify against `https://shapescan.xyz/api/` -- **View on Deca**: Once on mainnet, see your collection at `https://deca.art/token/shape//` -- **Add metadata**: Upload JSON metadata to IPFS with [Pinata](https://pinata.cloud/), then call `setBaseURI` to point your tokens at it -- [Build a dApp](https://docs.shape.network/building-on-shape/builder-kit.md) with the Shape Builder Kit - ---- - -Canonical page: https://docs.shape.network/tutorials/registering-contract-gasback/dashboard -Markdown page: https://docs.shape.network/tutorials/registering-contract-gasback/dashboard.md - -# Registering via the Dashboard - -This tutorial will guide you through the process of registering your smart contract for gasback using the Gasback Dashboard UI. - -## Prerequisites - -1. Your smart contract must be deployed on Shape. -2. You need access to a Web3 wallet (like MetaMask) with the account that owns the smart contract you want to register. -3. Your smart contract must have an owner() function which returns the address of the account you will connect to the dashboard - -## Step 1: Access the Dashboard - -Open your web browser and navigate to the [Gasback dashboard](https://gasback.shape.network/). - -![Gasback Dashboard](https://docs.shape.network/gasback-dashboard-1.webp) - -## Step 2: Connect Your Wallet - -1. Click the "Connect Wallet" button in the top right corner of the page. -2. A popup will appear with various wallet options. Select your preferred wallet (e.g., MetaMask). -3. Follow the prompts in your wallet to connect to the site and select the account you want to use. - -![Connect Wallet](https://docs.shape.network/gasback-dashboard-2.webp) - -## Step 3: View Your Gasback Dashboard - -1. Once connected, you'll see your Gasback dashboard. -2. If you haven't registered any contracts yet, you'll see a hero banner explaining that you don't have a gasback NFT yet. - -![Gasback Dashboard](https://docs.shape.network/gasback-dashboard-3.webp) - -## Step 4: Initiate registration and enter contract details - -1. Click the "Register" button in the hero banner or the header. and a popup window titled "Register a new smart contract" will appear. -2. In the "Contract Address" field, enter the address of the smart contract you want to register for gasback. -3. The "NFT Recipient" field should automatically populate with your connected wallet address. This is the address that will receive the gasback NFT. You can change this if you want the NFT to go to a different address. -4. Click “Register” - -![Register Contract](https://docs.shape.network/gasback-dashboard-4.webp) - -## Step 5: Confirm Registration - -1. Read the warning message and double-check that all the information is correct. -2. Click the "Confirm" button. -3. Your wallet will prompt you to confirm the transaction. Review the details and confirm the transaction. -4. Wait for the transaction to be processed and confirmed on the blockchain. - -![Confirm Registration](https://docs.shape.network/gasback-dashboard-5.webp) - -## Step 6: Verify Registration - -1. After the transaction is confirmed, the dashboard should update to reflect your newly registered contract. -2. You did it! You should see your unique gasback NFT that was generated onchain. The art on your NFT will evolve as your token accrues gasback. - -![Verify Registration](https://docs.shape.network/gasback-dashboard-6.webp) - -## Step 7: Managing Your Gasback - -Your dashboard will now display any gasback activity related to your registered contract. Activity can take up to 10 minutes to show up here. Registration itself earns you gasback, so you've already started your journey! - -If you have more contracts you want to register for Gasback, you can click the “manage” button and add their contract addresses to the field, and all the gasback earned by those contracts will be claimable with a single NFT. - -![Manage Gasback](https://docs.shape.network/gasback-dashboard-7.webp) - -That's it! If you're less of a UI person, check out the next section to see how to do this programmatically. - ---- - -Canonical page: https://docs.shape.network/tutorials/registering-contract-gasback -Markdown page: https://docs.shape.network/tutorials/registering-contract-gasback/index.md - -# Registering Your Contract for Gasback - -There are two different methods to register your contract for Gasback registration. You can either use the UI, or register programmatically from the contract you wish to register. This section has tutorials on how to do each approach. - -- [Using the dashboard](https://docs.shape.network/tutorials/registering-contract-gasback/dashboard.md) - -- [Programmatically](https://docs.shape.network/tutorials/registering-contract-gasback/programmatically.md) - ---- - -Canonical page: https://docs.shape.network/tutorials/registering-contract-gasback/programmatically -Markdown page: https://docs.shape.network/tutorials/registering-contract-gasback/programmatically.md - -# Registering Programmatically - -This tutorial will guide you through the process of registering your smart contract for gasback programmatically. The tutorial walks through 3 different approaches you can use, with full example contracts. - -## Prerequisites - -1. Some familiarity with Solidity and Node JS. -2. If you want to actually deploy the contracts we'll go through so that you can get hands on, download the example repo [here](https://github.com/shape-network/gasback-tutorial). -3. (Optional) If you do decide to deploy the contracts and register, you'll need some Shape Sepolia ETH which you can get from the [Alchemy faucet](https://www.alchemy.com/faucets/shape-sepolia) or the [Superchain faucet](https://console.optimism.io/faucet). You will then need to create a `.env` file according to the `.env.example` file in the repo. - -## Example A: Registering inside the contract and sending the Gasback NFT to the contract owner to hold - -The code snippet below is the complete implementation of a contract called ExampleA, that we'll use for the first example. - -A is an Ownable contract, which means external callers can call an `owner()` method to determine which address has control over the contract. - -```solidity filename="ExampleA.sol" -pragma solidity 0.8.20; - -import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; -import {IGasback} from "./interfaces/IGasback.sol"; - -contract ExampleA is Ownable { - IGasback public gasback; - - constructor(address _gasback) Ownable(msg.sender) { - gasback = IGasback(_gasback); - } - - function registerForGasback() public onlyOwner { - gasback.register(owner(), address(this)); - } -} -``` - -As you can see, registration happens in one line, on line 14: `gasback.register(owner(), address(this));`. This says, register this address for gasback, and send the NFT to the owner of this contract. - -Inside the Gasback.sol contract (not shown), the `owner()` function of the contract that is registering gets called, so that the Gasback contract knows that the person due to receive the Gasback NFT is the person who controls the registering contract. - -> Warning: -> -> If your contract tries to register in the constructor, the call will fail. Registration must -> happen after contract construction. - -To deploy the contract above run: - -```bash -npx hardhat deployA --network shapeSepolia -``` - -You'll then see the deployed address in the console. - -To run the registration function, run: - -```bash -npx hardhat registerA --network shapeSepolia -``` - -Where the deployed address is the address printed in the deployment command. - -Once that's done, you can actually visit the [Gasback dashboard](https://gasback.shape.network/) and see your new Gasback NFT! - -## Example B: Registering inside a contract without requiring an owner - -```solidity filename="ExampleB.sol" -pragma solidity 0.8.20; - -import {IGasback} from "./interfaces/IGasback.sol"; -import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; - -contract ExampleB is IERC721Receiver { - IGasback public gasback; - - constructor(address _gasback) { - gasback = IGasback(_gasback); - } - - function registerForGasback() public { - address me = address(this); - gasback.register(me, me); - } - - function onERC721Received( - address operator, - address from, - uint256 tokenId, - bytes calldata data - ) external override returns (bytes4) { - return IERC721Receiver.onERC721Received.selector; - } -} -``` - -Contract B differs from A in a couple of key ways. Firstly, you'll notice that ExampleB is not an Ownable contract. The reason it's still able to register despite this, is that the contract itself is going to be the recipient of the Gasback NFT. This means we don't have to check an owner, because it's clearly registering itself. - -The second key change is the addition of the `onERC721Received` function. This inclusion is needed because Gasback.sol uses `_safeMint` to mint the NFT, which requires that any contract that receives the NFT implements this function, so that we know the NFT won't be stuck forever inside the contract, and the contract is actually expecting to receive and handle NFTs. - -> Warning: -> -> When implementing this pattern a function protected by some form of access control that -> withdraws the NFT from your contract is a great fallback option. - -Similar to example A you can deploy and run the registration function yourself by doing: - -```bash -npx hardhat deployB --network shapeSepolia -``` - -and - -```bash -npx hardhat registerB --network shapeSepolia -``` - -However in this example you won't see the NFT in your dashboard yet because you aren't the owner of it, the contract is! We'll explain how you can still manage the NFT that one of your contracts holds in a later tutorial, when we discuss the concept of **Delegation**. - -## Example C: Registering outside of a contract - -```solidity filename="ExampleC.sol" -pragma solidity 0.8.20; - -import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; - -contract ExampleC is Ownable { - constructor() Ownable(msg.sender) {} -} -``` - -The final example is a tiny contract. It has no logic in it other than to make itself Ownable. But, we can still register it for Gasback! - -The registration logic happens outside of the contract. All you have to do is call the registration on the Gasback contract directly, entering your own address as the NFT recipient and the contract address. - -You can see how this is done in `scripts/register.ts` in the registerC task: - -```typescript -task('registerC', 'Registers the ExampleC contract for gasback') - .addPositionalParam('contractAddress', 'The address of the ExampleC contract to register') - .setAction(async (taskArgs, hre) => { - const { contractAddress } = taskArgs; - - const [address] = await hre.ethers.getSigners(); - - const gasback = await hre.ethers.getContractAt('Gasback', gasbackAddress); - - const tx = await gasback.register(address, contractAddress); - await tx.wait(1); - - console.log('ExampleC registered! Tx hash: ', tx.hash); - }); -``` - -Of course, as proof it works, you can deploy and register using similar commands as before: - -```bash -npx hardhat deployC --network shapeSepolia -``` - -and - -```bash -npx hardhat registerC --network shapeSepolia -``` - -If you want an easy way to do this method, you can simply use the Gasback dashboard UI, connect your wallet, and paste in the contract address. The UI will make the contract call for you. - -## Summary - -That's it! You have now learned 3 different ways to register your contract for Gasback. In the next tutorials, we'll discuss how to delegate gasback rights when your contract owns the NFT instead of you, and we'll learn how to withdraw claimed gasback. - ---- - -Canonical page: https://docs.shape.network/wallet-setup -Markdown page: https://docs.shape.network/wallet-setup.md - -# Wallet Setup - -Set up your wallet on Shape. - -## 1. Add Shape to Your Wallet - -1. Go to the [Shape website](https://shape.network/) -2. Scroll down to the "Get Started" section and click "Add Shape Mainnet" -3. You'll be prompted to switch to the Shape network - - If the network isn't listed, you can [add it manually](https://docs.shape.network/technical-details/network-information.md) - -## 2. Bridge to Shape - -1. Choose a [bridge](https://shape.network/bridge) to Shape -2. Send ETH over to Shape from another chain -3. Once complete, check your ETH balance on Shape - - If you don't see your balance, make sure your wallet is connected to the Shape network - -## 3. Mint Your Stack - -Build your onchain reputation on Shape by earning medals with the Stack. It's also the most effective way to claim more $SHAPE. - -[Mint your Stack](https://stack.shape.network/) - -More on the Stack in the next section. diff --git a/public/llms.txt b/public/llms.txt deleted file mode 100644 index 6e0278d..0000000 --- a/public/llms.txt +++ /dev/null @@ -1,58 +0,0 @@ -# Shape Documentation - -> Official technical documentation for Shape, an Ethereum L2 built on the OP Stack and part of the Optimism Superchain. - -Mainnet chain ID: 360. Shape Sepolia chain ID: 11011. Gas currency: ETH. Gasback shares 80% of L2 sequencer fees with registered contract owners, excluding L1 data fees. - -Links below lead to Markdown generated from the same source as the website. Follow the relevant pages for full context. For current $SHAPE token and governance information, see https://shape.network/token. - -## Start Here - -- [Welcome](https://docs.shape.network/index.md): Shape is the culture-first L2 built on top of Ethereum to power the new NFT economy. -- [Wallet Setup](https://docs.shape.network/wallet-setup.md): Set up your wallet on Shape. -- [Start Building on Shape](https://docs.shape.network/quick-start/index.md): Shape is an EVM-compatible L2 on the Optimism Superchain. Gasback returns 80% of sequencer fees to contract owners. -- [Network Information](https://docs.shape.network/technical-details/network-information.md): Mainnet and testnet chain IDs, ETH gas currency, RPC endpoints, and explorers. - -## Gasback and Fees - -- [Gasback](https://docs.shape.network/gasback.md): Claim back 80% of the sequencer fees that users spend interacting with your contracts on Shape. -- [Transaction Fees](https://docs.shape.network/building-on-shape/transaction-fees.md): Learn how network fees work on Shape, what changes them, where they go, and how to estimate them. -- [Registering Your Contract for Gasback](https://docs.shape.network/tutorials/registering-contract-gasback/index.md): Choose dashboard or programmatic contract registration for Gasback. - -## Build Applications - -- [Connect to Shape](https://docs.shape.network/quick-start/connect-to-shape.md): Shape Mainnet runs on chain ID 360. Shape Sepolia (testnet) runs on chain ID 11011. -- [Deploy a Contract on Shape](https://docs.shape.network/quick-start/deploy-a-contract.md): Deploy a smart contract to Shape Sepolia and verify it on the block explorer using Foundry. -- [Shape Builder Kit for Developers](https://docs.shape.network/building-on-shape/builder-kit.md): The Shape Builder Kit is your go-to starter for crafting dApps on the Shape ecosystem. It's a monorepo with a Next.js frontend (wagmi, viem) and a Hardhat smart contract package, all pre-wired with sensible defaults. -- [Launch an NFT Collection on Shape](https://docs.shape.network/tutorials/mint-nft-collection.md): Deploy an ERC-721 contract to Shape Sepolia, mint an NFT, and verify it on the block explorer. -- [AI Agents on Shape](https://docs.shape.network/building-on-shape/ai.md): Shape MCP, AI integration examples, and agent development guidance. - -## Explore and Operate - -- [The Stack](https://docs.shape.network/the-stack.md): Dynamic NFT achievements, participation, and medals across the Shape ecosystem. -- [Contract Addresses](https://docs.shape.network/technical-details/contract-addresses.md): Official network infrastructure contract addresses. -- [Run a Node](https://docs.shape.network/technical-details/run-a-node.md): Shape is an OP Stack rollup. Running a Shape node requires two clients that talk over the Engine API and authenticate with a shared JWT secret: -- [Differences between Ethereum and Shape](https://docs.shape.network/building-on-shape/differences-ethereum-shape.md): Shape is EVM equivalent, but has some minor differences. - -## Tools and Further Reading - -- [Alchemy API](https://docs.shape.network/building-on-shape/alchemy-api.md): Find out what Alchemy tools are available to use on Shape. -- [Assembly](https://docs.shape.network/building-on-shape/onchain-compatible/assembly.md): The Assembly system, built on top of Otoms, is a flexible ERC1155 implementation enabling the creation, crafting, and management of both fungible and non-fungible items on the blockchain. Built with upgradeability in... -- [Onchain Compatible Projects](https://docs.shape.network/building-on-shape/onchain-compatible/index.md): A collection of projects made with interoperability in mind -- [OTOM by Kjetil Golid](https://docs.shape.network/building-on-shape/onchain-compatible/otom.md): Create and experiment with particles called otoms -- [Superchain incentives](https://docs.shape.network/building-on-shape/superchain-incentives.md): Learn about the Superchain incentives available to you as a Shape builder. -- [Account Abstraction](https://docs.shape.network/tools/account-abstraction.md): On Shape, combine AA with Gasback to subsidize your users and recoup 80% of sequencer fees. -- [Bridges](https://docs.shape.network/tools/bridges.md): Bridge ETH and tokens between Ethereum and Shape. -- [Data Indexers](https://docs.shape.network/tools/data-indexers.md): NFT queries, indexing services, and data APIs. -- [Explorers](https://docs.shape.network/tools/explorers.md): Verify your contracts on Shapescan to make them readable. See Deploy a Contract for verification steps. -- [Faucets](https://docs.shape.network/tools/faucets.md): Get free testnet ETH on Shape Sepolia for development. -- [Node Providers](https://docs.shape.network/tools/node-providers.md): Public and provider RPC endpoints for mainnet and testnet. -- [Gelato VRF](https://docs.shape.network/tools/oracles/gelato-vrf.md): Request verifiable randomness from smart contracts using Gelato VRF. -- [Safes & Asset Security](https://docs.shape.network/tools/safes-asset-security.md): Manage high-value assets and team operations securely on Shape. -- [Sybil Resistance](https://docs.shape.network/tools/sybil-resistance.md): Protect your app from bots and sybil attacks while preserving user privacy. -- [Registering via the Dashboard](https://docs.shape.network/tutorials/registering-contract-gasback/dashboard.md): This tutorial will guide you through the process of registering your smart contract for gasback using the Gasback Dashboard UI. -- [Registering Programmatically](https://docs.shape.network/tutorials/registering-contract-gasback/programmatically.md): This tutorial will guide you through the process of registering your smart contract for gasback programmatically. The tutorial walks through 3 different approaches you can use, with full example contracts. - -## Optional - -- [All technical documentation](https://docs.shape.network/llms-full.txt): All generated pages in one file. Use individual pages for narrower questions. diff --git a/public/quick-start/connect-to-shape.md b/public/quick-start/connect-to-shape.md deleted file mode 100644 index bd6aeeb..0000000 --- a/public/quick-start/connect-to-shape.md +++ /dev/null @@ -1,76 +0,0 @@ -# Connect to Shape - -Shape Mainnet runs on chain ID `360`. Shape Sepolia (testnet) runs on chain ID `11011`. - -> The public RPCs are rate-limited. For production apps, use [Alchemy](https://www.alchemy.com/rpc/shape) (`https://shape-mainnet.g.alchemy.com/v2/YOUR_KEY`). Free tier available. - -The examples below use viem v2+ and wagmi v2+. Both export `shape` and `shapeSepolia` chain definitions. - -## viem - -```ts -import { createPublicClient, http } from 'viem'; -import { shape } from 'viem/chains'; - -const client = createPublicClient({ - chain: shape, - transport: http('https://mainnet.shape.network'), -}); -``` - -For Shape Sepolia, use `shapeSepolia` and the testnet RPC: - -```ts -import { createPublicClient, http } from 'viem'; -import { shapeSepolia } from 'viem/chains'; - -const client = createPublicClient({ - chain: shapeSepolia, - transport: http('https://sepolia.shape.network'), -}); -``` - -## wagmi - -```ts -import { http, createConfig } from 'wagmi'; -import { shape, shapeSepolia } from 'wagmi/chains'; - -export const config = createConfig({ - chains: [shape, shapeSepolia], - transports: { - [shape.id]: http('https://mainnet.shape.network'), - [shapeSepolia.id]: http('https://sepolia.shape.network'), - }, -}); -``` - -## Foundry - -Add a profile to `foundry.toml`: - -```toml -# foundry.toml -[profile.shape-sepolia] -eth_rpc_url = "https://sepolia.shape.network" -chain_id = 11011 -``` - -## ethers.js v6 - -```ts -import { JsonRpcProvider } from 'ethers'; - -const provider = new JsonRpcProvider('https://mainnet.shape.network'); -``` - -## Network Reference - -| | Mainnet | Sepolia | -| --- | --- | --- | -| Chain ID | `360` | `11011` | -| RPC | `https://mainnet.shape.network` | `https://sepolia.shape.network` | -| Explorer | [shapescan.xyz](https://shapescan.xyz/) | [sepolia.shapescan.xyz](https://sepolia.shapescan.xyz/) | -| Currency | ETH | ETH | - -See [Network Information](https://docs.shape.network/technical-details/network-information.md) for the full reference. diff --git a/public/quick-start/deploy-a-contract.md b/public/quick-start/deploy-a-contract.md deleted file mode 100644 index 7ce60d0..0000000 --- a/public/quick-start/deploy-a-contract.md +++ /dev/null @@ -1,66 +0,0 @@ -# Deploy a Contract on Shape - -Deploy a smart contract to Shape Sepolia and verify it on the block explorer using Foundry. - -## Prerequisites - -- [Foundry](https://book.getfoundry.sh/getting-started/installation) installed -- Shape Sepolia ETH from the [Alchemy Faucet](https://www.alchemy.com/faucets/shape-sepolia) -- A wallet private key funded with testnet ETH - -## 1. Create a Project - -```bash -forge init my-shape-contract -cd my-shape-contract -``` - -This scaffolds a project with a `Counter.sol` contract in `src/`. - -## 2. Deploy - -```bash -forge create src/Counter.sol:Counter \ - --rpc-url https://sepolia.shape.network \ - --private-key $PRIVATE_KEY -``` - -Save the `Deployed to` address from the output. - -## 3. Verify on the Explorer - -```bash -forge verify-contract src/Counter.sol:Counter \ - --verifier blockscout \ - --verifier-url https://sepolia.shapescan.xyz/api/ -``` - -Replace `` with the address from step 2. - -## 4. Deploy to Mainnet - -When ready for mainnet, use the mainnet RPC and verify against the mainnet explorer: - -```bash -forge create src/Counter.sol:Counter \ - --rpc-url https://mainnet.shape.network \ - --private-key $PRIVATE_KEY -``` - -```bash -forge verify-contract src/Counter.sol:Counter \ - --verifier blockscout \ - --verifier-url https://shapescan.xyz/api/ -``` - -## 5. Register for Gasback - -Gasback returns 80% of sequencer fees to contract owners. Register your deployed contract to start earning. - -See [Registering Your Contract for Gasback](https://docs.shape.network/tutorials/registering-contract-gasback/index.md) for the full walkthrough. - -## Next Steps - -- [Build a dApp](https://docs.shape.network/building-on-shape/builder-kit.md) with the Shape Builder Kit -- [Connect to Shape](https://docs.shape.network/quick-start/connect-to-shape.md) from your frontend -- [Gasback](https://docs.shape.network/gasback.md) (how fee reclamation works) diff --git a/public/quick-start/index.md b/public/quick-start/index.md deleted file mode 100644 index 34e4f51..0000000 --- a/public/quick-start/index.md +++ /dev/null @@ -1,16 +0,0 @@ -# Start Building on Shape - -Shape is an EVM-compatible L2 on the [Optimism Superchain](https://www.optimism.io/superchain). Gasback returns 80% of sequencer fees to contract owners. - -- [Connect to Shape](https://docs.shape.network/quick-start/connect-to-shape.md): Configure viem, wagmi, Foundry, and ethers.js for Shape - -- [Deploy a Contract](https://docs.shape.network/quick-start/deploy-a-contract.md): Deploy and verify a smart contract with Foundry - -- [Build a dApp](https://docs.shape.network/building-on-shape/builder-kit.md): Scaffold a full-stack dApp with the Shape Builder Kit - -## Resources - -- [Shape Sepolia Faucet](https://www.alchemy.com/faucets/shape-sepolia) (testnet ETH) -- [Alchemy Dashboard](https://www.alchemy.com/dashboard) (API keys and enhanced RPCs) -- [Network Information](https://docs.shape.network/technical-details/network-information.md) (chain IDs, RPCs, explorers) -- [Shape Discord](https://discord.com/invite/shape-l2) (builder support) diff --git a/public/technical-details/contract-addresses.md b/public/technical-details/contract-addresses.md deleted file mode 100644 index 6e24505..0000000 --- a/public/technical-details/contract-addresses.md +++ /dev/null @@ -1,111 +0,0 @@ -# Contract Addresses - -## Mainnet - -### Ethereum (L1) - -| Name | Address | -| ----------------------------------- | -------------------------------------------- | -| `L2OutputOracleProxy` | `0x6Ef8c69CfE4635d866e3E02732068022c06e724D` | -| `OptimismPortalProxy` | `0xEB06fFa16011B5628BaB98E29776361c83741dd3` | -| `L1StandardBridgeProxy` | `0x62Edd5f4930Ea92dCa3fB81689bDD9b9d076b57B` | -| `AddressManager` | `0xcee78437aE9e15cee9c78E63757E0153c0FD7479` | -| `AnchorStateRegistryProxy` | `0x02987E7294379B9DDa99d593b0C94c68266222D1` | -| `DelayedWETHProxy` | `0xfEc7865DAc5139886585F03146Ff61D9b31c2d57` | -| `DisputeGameFactoryProxy` | `0x575Aecd84083f93877291901907698F7db0Bd8b0` | -| `L1CrossDomainMessengerProxy` | `0x2b18602877181C3cB72C687E2A771E123A3788E3` | -| `L1ERC721BridgeProxy` | `0xe9d3E49b0636016c5fE9eaA2347948D0bA9f15Af` | -| `Mips` | `0xD30c2Cd3cd6112E61FDfb03e4b232564d7e5C91f` | -| `OptimismMintableERC20FactoryProxy` | `0x319322906beAdf69dF5d4607169c63D692B1aDC1` | -| `PreimageOracle` | `0xDF6a16a71d0BC7a1Bbe8FffB33700eC3d9448A5B` | -| `ProtocolVersionsProxy` | `0xa77995E10b0A833CDD4fA414C26E869F7aa32DDd` | -| `ProxyAdmin` | `0x11B190Ae661c6d6884dFEE48E215691E0DdB842e` | -| `SuperchainConfigProxy` | `0x125664BEf08177ca43f6f301E63118b1e4cCDe09` | -| `SystemConfigProxy` | `0xfF11e41D5C4F522E423Ff6C064Ff8D55AF8f7355` | -| `SystemOwnerSafe` | `0xacAF178b5048CB56712dc59E95fBA72F7990A005` | - -### Shape Mainnet (L2) - -| Name | Address | -| ------------------------------- | -------------------------------------------- | -| `Gasback` | `0xf5e602c87d675E978F097503aedE4A766285a08B` | -| `RecipientValidator` | `0x12e50C2B9Dd2741bd07Df4E2E544f3412fd584cE` | -| `WETH9` | `0x4200000000000000000000000000000000000006` | -| `multicall3` | `0xca11bde05977b3631167028862be2a173976ca11` | -| `ImmutableCreate2Factory` | `0x0000000000ffe8b47b3e2130213b802212439497` | -| `Create2Deployer` | `0x13b0D85CcB8bf860b6b79AF3029fCA081AE9beF2` | -| `DeterministicDeploymentProxy` | `0x4e59b44847b379578588920ca78fbf26c0b4956c` | -| `Seaport 1.6` | `0x0000000000000068F116a894984e2DB1123eB395` | -| `ConduitController` | `0x00000000F9490004C11Cef243f5400493c00Ad63` | -| `GitcoinPassportDecoder` | `0x2443D22Db6d25D141A1138D80724e3Eee54FD4C2` | -| `GitcoinResolver` | `0x90E2C4472Df225e8D31f44725B75FFaA244d5D33` | -| `GitcoinVerifier` | `0x16db23c4b99bbC9A6Bf55dF7a787C9AEFD261185` | -| `GitcoinAttester` | `0xCc90105D4A2aa067ee768120AdA19886021dF422` | -| `L2CrossDomainMessenger` | `0x4200000000000000000000000000000000000007` | -| `L2StandardBridge` | `0x4200000000000000000000000000000000000010` | -| `SequencerFeeVault` | `0x4200000000000000000000000000000000000011` | -| `OptimismMintableERC20Factory` | `0x4200000000000000000000000000000000000012` | -| `GasPriceOracle` | `0x420000000000000000000000000000000000000F` | -| `GovernanceToken` | `0x4200000000000000000000000000000000000042` | -| `L1Block` | `0x4200000000000000000000000000000000000015` | -| `L2ToL1MessagePasser` | `0x4200000000000000000000000000000000000016` | -| `L2ERC721Bridge` | `0x4200000000000000000000000000000000000014` | -| `OptimismMintableERC721Factory` | `0x4200000000000000000000000000000000000017` | -| `ProxyAdmin` | `0x4200000000000000000000000000000000000018` | -| `BaseFeeVault` | `0x4200000000000000000000000000000000000019` | -| `L1FeeVault` | `0x420000000000000000000000000000000000001a` | -| `SchemaRegistry` | `0x4200000000000000000000000000000000000020` | -| `EAS` | `0x4200000000000000000000000000000000000021` | -| `BeaconBlockRoot` | `0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02` | -| `LegacyMessagePasser` | `0x4200000000000000000000000000000000000000` | -| `DeployerWhitelist` | `0x4200000000000000000000000000000000000002` | - -## Testnet (Sepolia) - -### Sepolia (L1) - -| Name | Address | -| ----------------------------------- | -------------------------------------------- | -| `AddressManager` | `0x42721d8512d62aA26B2Cfa1AE18bEEd5a9Ab1337` | -| `AnchorStateRegistryProxy` | `0x41ea3c370896632121Cdde1b94a4eCcf23DA4532` | -| `DelayedWETHProxy` | `0x7cc9cA91BA4f92F4C967E93a1AAd97beB18d3877` | -| `DisputeGameFactoryProxy` | `0x93eaa7A1E7d7af7eD9D612F9957988C8631c33e8` | -| `L1CrossDomainMessengerProxy` | `0xF9F730650e1AB4D23E2ac983934271ca7c5EF293` | -| `L1ERC721BridgeProxy` | `0x19f02c55254d2644eF94f30C74A932D64e1D4F86` | -| `L1StandardBridgeProxy` | `0x341ab1DAfdfB73b3D6D075ef10b29e3cACB2A653` | -| `L2OutputOracleProxy` | `0x532dDCed3440Eab81c529Ac8b0d7e429B5C05c52` | -| `Mips` | `0xaCf1Ed7357E41f652407ae6cFE1024705c758C38` | -| `OptimismMintableERC20FactoryProxy` | `0x46085E2e648488e49FBeaF6544b8e9Dc96df8BDd` | -| `OptimismPortalProxy` | `0xfF8Ca2B4d8122E41441F7ccDCf61b8692198Bd1E` | -| `PreimageOracle` | `0x8F3B1c59eD4439ebF564604aA4B93130DA4CD1D5` | -| `ProtocolVersionsProxy` | `0x8B901e6F6a49C950088d11C81166BCE2E3171C03` | -| `ProxyAdmin` | `0xd60a706Bf6108F090d055787B9B353FA7EEE1355` | -| `SuperchainConfigProxy` | `0xe5b3692266FF4Ab8A96A9C7Da6EeEe532CCc7916` | -| `SystemConfigProxy` | `0xa1aC91ED91EbE40E00d61E233c8026318b4da5fb` | -| `SystemOwnerSafe` | `0x4c4526C8C55c4e1a6F2aaf91e37f07c97786e0f5` | - -### Shape Sepolia (L2) - -| Name | Address | -| ------------------------------- | -------------------------------------------- | -| `Gasback` | `0xdF329d59bC797907703F7c198dDA2d770fC45034` | -| `WETH9` | `0x4200000000000000000000000000000000000006` | -| `L2CrossDomainMessenger` | `0x4200000000000000000000000000000000000007` | -| `L2StandardBridge` | `0x4200000000000000000000000000000000000010` | -| `SequencerFeeVault` | `0x4200000000000000000000000000000000000011` | -| `OptimismMintableERC20Factory` | `0x4200000000000000000000000000000000000012` | -| `GasPriceOracle` | `0x420000000000000000000000000000000000000F` | -| `GovernanceToken` | `0x4200000000000000000000000000000000000042` | -| `L1Block` | `0x4200000000000000000000000000000000000015` | -| `L2ToL1MessagePasser` | `0x4200000000000000000000000000000000000016` | -| `L2ERC721Bridge` | `0x4200000000000000000000000000000000000014` | -| `OptimismMintableERC721Factory` | `0x4200000000000000000000000000000000000017` | -| `ProxyAdmin` | `0x4200000000000000000000000000000000000018` | -| `BaseFeeVault` | `0x4200000000000000000000000000000000000019` | -| `L1FeeVault` | `0x420000000000000000000000000000000000001a` | -| `SchemaRegistry` | `0x4200000000000000000000000000000000000020` | -| `EAS` | `0x4200000000000000000000000000000000000021` | -| `BeaconBlockRoot` | `0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02` | -| `LegacyMessagePasser` | `0x4200000000000000000000000000000000000000` | -| `DeployerWhitelist` | `0x4200000000000000000000000000000000000002` | -| `LegacyERC20ETH` | `0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000` | diff --git a/public/technical-details/network-information.md b/public/technical-details/network-information.md deleted file mode 100644 index 6842893..0000000 --- a/public/technical-details/network-information.md +++ /dev/null @@ -1,22 +0,0 @@ -# Network Information - -## Mainnet - -| Network Name | Shape | -| --------------- | ----------------------------------------------- | -| Chain ID | `360` | -| Currency Symbol | `ETH` | -| RPC Endpoint | `https://mainnet.shape.network` | -| Block Explorer | [https://shapescan.xyz](https://shapescan.xyz/) | - -## Testnet - -| Network Name | Shape Sepolia | -| --------------- | --------------------------------------------------------------------------------- | -| Chain ID | `11011` | -| Currency Symbol | `ETH` | -| RPC Endpoint | `https://sepolia.shape.network` | -| Block Explorer | [https://sepolia.shapescan.xyz](https://sepolia.shapescan.xyz/) | - -> For production systems or high throughput testing, we recommend using a node from -> [Alchemy](https://www.alchemy.com/supernode), one of our node providers. diff --git a/public/technical-details/run-a-node.md b/public/technical-details/run-a-node.md deleted file mode 100644 index 7d1cd93..0000000 --- a/public/technical-details/run-a-node.md +++ /dev/null @@ -1,354 +0,0 @@ -# Run a Node - -Shape is an [OP Stack](https://docs.optimism.io/stack/getting-started) rollup. Running a Shape node requires two clients that talk over the [Engine API](https://github.com/ethereum/execution-apis/blob/main/src/engine/common.md) and authenticate with a shared JWT secret: - -- **Execution client (op-geth)** runs the EVM and stores chain state. -- **Consensus client (op-node)** derives the L2 chain from L1 data and feeds blocks to the execution client. - -## Prerequisites - -### Hardware requirements - -| Component | Full node | Archive node | -| --------- | --------- | ------------ | -| CPU | Reasonably modern, multi-core | Same | -| RAM | 16 GB minimum | 16 GB minimum | -| Storage | 700 GB+ SSD (grows ~100 GB / 6 months) | 14 TB+ NVMe SSD (grows ~3.5 TB / 6 months) | - -Archive nodes should use NVMe SSDs. op-geth's `--datadir.ancient` flag can offload older data to a cheaper HDD. - -### Software dependencies - -- [Go](https://go.dev/dl/) 1.21+ -- [just](https://github.com/casey/just#installation) (op-node build tool) -- Make (op-geth build tool) -- Git -- An **L1 Ethereum RPC endpoint** (e.g., [Alchemy](https://www.alchemy.com/), Infura, or your own node) -- An **L1 Beacon (consensus) endpoint** (required since Ecotone for blob retrieval) - -### Network ports - -Expose the following ports for P2P sync: - -| Port | Protocol | Purpose | -| ----- | -------- | ------- | -| 30303 | TCP + UDP | op-geth peer discovery and block propagation | -| 9222 | TCP + UDP | op-node peer discovery | - -## Choose paths - -The commands below assume these shell variables: - -```bash -export OP_GETH_DIR=$HOME/op-geth -export OPTIMISM_DIR=$HOME/optimism -export OP_NODE_DIR=$OPTIMISM_DIR/op-node -export DATADIR=$HOME/.shape -export CONFIG_DIR=$HOME/.shape-config - -mkdir -p "$DATADIR/geth" "$CONFIG_DIR" -``` - -Adjust them if you want different locations. - -## Build the clients - -Build both binaries first. You need the same `op-geth` and `op-node` binaries whether you sync from a snapshot or from genesis. - -### 1. Build op-geth - -```bash -git clone https://github.com/ethereum-optimism/op-geth.git "$OP_GETH_DIR" -cd "$OP_GETH_DIR" -git checkout -make geth -``` - -Check [op-geth releases](https://github.com/ethereum-optimism/op-geth/releases) for the required release branch. - -### 2. Build op-node - -```bash -git clone https://github.com/ethereum-optimism/optimism.git "$OPTIMISM_DIR" -cd "$OPTIMISM_DIR" -git checkout -cd "$OP_NODE_DIR" -just -``` - -Check [optimism releases](https://github.com/ethereum-optimism/optimism/releases) for the required release branch. - -## Option A: Sync from snapshot (fastest) - -[Alchemy snapshots](https://www.alchemy.com/snapshots/shape) let you skip the full sync by downloading a compressed chaindata archive and starting near the chain tip. - -### 1. Download the snapshot - -Visit [alchemy.com/snapshots/shape](https://www.alchemy.com/snapshots/shape) and download the latest `.tar.lz4` snapshot for your network (mainnet or Sepolia). - -### 2. Install lz4 and decompress - -```bash -# macOS -brew install lz4 - -# Ubuntu/Debian -sudo apt-get install -y lz4 -``` - -If you have existing data, stop your node and clear the old chaindata first: - -```bash -rm -rf "$DATADIR/geth/chaindata" -rm -rf "$DATADIR/geth/lightchaindata" -``` - -Decompress the snapshot: - -```bash -lz4 -c -d .tar.lz4 | tar -x -C "$DATADIR/geth/" -``` - -### 3. Download the rollup config - -Save the `rollup.json` for your network to `$CONFIG_DIR/rollup.json`: - -**Shape Mainnet:** -- [rollup.json](https://arweave.net/Lh9vjNsHKHOKzGwWwlvVz2tsxcL_h5Wc-Ga0udO3Xm0) - -**Shape Sepolia:** -- [rollup.json](https://arweave.net/gSb3hOzLaBIBy-AyWA2O2_03sfXJ-IwPqmV6Mhstmj8) - -### 4. Continue to [Configure and run](#configure-and-run) - -Your node should be in sync within minutes of starting. - -## Option B: Sync from genesis - -### 1. Download genesis and rollup configs - -Save the files for your network to `$CONFIG_DIR/rollup.json` and `$CONFIG_DIR/genesis.json`: - -**Shape Mainnet:** -- [rollup.json](https://arweave.net/Lh9vjNsHKHOKzGwWwlvVz2tsxcL_h5Wc-Ga0udO3Xm0) -- [genesis.json](https://arweave.net/LrSrsEJsUtSWNAzkpKqkwE9RG3JZP1SmlOQNlTu8Nxk) - -**Shape Sepolia:** -- [rollup.json](https://arweave.net/gSb3hOzLaBIBy-AyWA2O2_03sfXJ-IwPqmV6Mhstmj8) -- [genesis.json](https://arweave.net/nw6opum2ALT9T39TSAAK_Wq0Z75aZJWd6J2RmiWHm_s) - -### 2. Initialize the datadir - -```bash -"$OP_GETH_DIR/build/bin/geth" init --datadir="$DATADIR" "$CONFIG_DIR/genesis.json" -``` - -### 3. Continue to [Configure and run](#configure-and-run) - -## Configure and run - -### 1. Generate a JWT secret - -op-geth and op-node authenticate over the Engine API with a shared secret. Save it to `$CONFIG_DIR/jwt.txt`: - -```bash -openssl rand -hex 32 > "$CONFIG_DIR/jwt.txt" -``` - -### 2. Start op-geth - -**Shape Mainnet:** - -```bash -"$OP_GETH_DIR/build/bin/geth" \ - --datadir="$DATADIR" \ - --http \ - --http.port=8545 \ - --http.addr=0.0.0.0 \ - --http.api=eth,net,web3 \ - --ws \ - --ws.port=8546 \ - --ws.addr=0.0.0.0 \ - --ws.api=eth,net,web3 \ - --authrpc.addr=localhost \ - --authrpc.port=8551 \ - --authrpc.jwtsecret="$CONFIG_DIR/jwt.txt" \ - --authrpc.vhosts=* \ - --verbosity=3 \ - --rollup.sequencerhttp=https://mainnet.shape.network \ - --rollup.disabletxpoolgossip=true \ - --syncmode=snap -``` - -**Shape Sepolia:** Replace `--rollup.sequencerhttp` with `https://sepolia.shape.network`. - -**For archive mode:** Add `--gcmode=archive` and change `--syncmode=full`. - -### 3. Start op-node - -Set your L1 endpoints: - -```bash -export L1_RPC_URL= # e.g., https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY -export L1_RPC_KIND= # alchemy, quicknode, infura, basic, etc. -export L1_BEACON_URL= # e.g., https://ethereum-beacon-api.publicnode.com -``` - -**Shape Mainnet:** - -```bash -"$OP_NODE_DIR/bin/op-node" \ - --l1=$L1_RPC_URL \ - --l1.rpckind=$L1_RPC_KIND \ - --l1.beacon=$L1_BEACON_URL \ - --l2=ws://localhost:8551 \ - --l2.jwt-secret="$CONFIG_DIR/jwt.txt" \ - --rollup.config="$CONFIG_DIR/rollup.json" \ - --l2.enginekind=geth \ - --syncmode=execution-layer \ - --override.granite=1727370000 \ - --override.holocene=1739880000 \ - --override.isthmus=1774530000 \ - --p2p.listen.tcp=9222 \ - --p2p.listen.udp=9222 \ - --rpc.addr=127.0.0.1 \ - --rpc.port=9545 \ - --metrics.enabled \ - --metrics.port=7300 -``` - -**Shape Sepolia:** - -```bash -"$OP_NODE_DIR/bin/op-node" \ - --l1=$L1_RPC_URL \ - --l1.rpckind=$L1_RPC_KIND \ - --l1.beacon=$L1_BEACON_URL \ - --l2=ws://localhost:8551 \ - --l2.jwt-secret="$CONFIG_DIR/jwt.txt" \ - --rollup.config="$CONFIG_DIR/rollup.json" \ - --l2.enginekind=geth \ - --syncmode=execution-layer \ - --override.ecotone=0 \ - --override.fjord=1721732400 \ - --override.granite=1727197200 \ - --override.holocene=1739880000 \ - --override.isthmus=1763650800 \ - --p2p.listen.tcp=9222 \ - --p2p.listen.udp=9222 \ - --rpc.addr=127.0.0.1 \ - --rpc.port=9545 \ - --metrics.enabled \ - --metrics.port=7300 -``` - -For Sepolia, use a Sepolia L1 RPC for `L1_RPC_URL`. - -> **Do not expose the op-node RPC publicly.** The `--rpc.addr` should be `127.0.0.1` (localhost) unless you have a specific reason and a firewall in place. - -### Sync modes - -| Mode | op-node flag | op-geth flag | Use case | -| ---- | ------------ | ------------ | -------- | -| Snap sync | `--syncmode=execution-layer` | `--syncmode=snap` (default) | Downloads state at chain tip via P2P. Fastest for full nodes. | -| Full sync | `--syncmode=execution-layer` | `--syncmode=full` | Executes every block. Required for archive nodes. | - -## Verifying your node - -After startup, look for: - -1. op-geth logs showing `Syncing beacon headers` as it downloads headers from peers. -2. op-geth logs showing state download progress (percentage and data volumes). -3. Once caught up, both clients log new blocks every 2 seconds. - -Check sync status via JSON-RPC: - -```bash -curl -s -X POST http://localhost:8545 \ - -H "Content-Type: application/json" \ - -d '{"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}' -``` - -Returns `false` when fully synced. - -## Monitoring - -op-node exposes Prometheus metrics at `http://localhost:7300/metrics` when started with `--metrics.enabled`. - -| Metric | What it tells you | -| ------ | ----------------- | -| `op_node_default_refs_number` | Current L1/L2 block heights. If these stall, sync has stopped. | -| `op_node_default_p2p_peer_count` | Connected peers. Zero means the node falls back to slow L1-only derivation. | -| `op_node_default_rpc_client_request_duration_seconds` | RPC call latency. Spikes usually point to your L1 provider. | - -## Blob archiver - -Since Ecotone, batch data is posted as [EIP-4844 blobs](https://eips.ethereum.org/EIPS/eip-4844). Standard beacon nodes prune blobs after ~18 days. - -You need a blob archiver if your node may go offline for 18+ days or you are syncing from genesis without a recent snapshot. - -Options: -1. Run an L1 beacon node with pruning disabled (e.g., Lighthouse with `--prune-blobs=false`) -2. Use a third-party beacon endpoint that retains blobs beyond the 18-day window - -Point op-node at a fallback endpoint that has the old blobs: - -```bash ---l1.beacon-fallbacks= -``` - -## Troubleshooting - -### Node stalling or can't find peers - -Pass the bootnode enodes directly to op-node with `--p2p.bootnodes`: - -**Shape Mainnet:** - -``` ---p2p.bootnodes=enode://ae31be7c6596f4bc3657f90b65a1569c7b0db10c976649f06fe5cfb26139064d78d22b41aede293aa7358fc336d086051ac7fce78f063dce89e1da19c7b88aee@34.228.226.23:0?discport=30301,enode://0bea78f02c9bee58326b3a612dae63dc5a0193fb3dfc9be687c9757d25606405ef9f87810157598fce35688bdb5b3834dc6283afab6dc5774abbd6c5a7b17cea@3.85.27.162:0?discport=30301 -``` - -**Shape Sepolia:** - -``` ---p2p.bootnodes=enode://34fc07c447b843f3915f72cae27daeda7f2f8c3ea4b9132aed188387d3208d1d5cd7eeea58d30d038c14f985a5b108ad6b2172815ed8b757c9de9f609741b2a6@34.228.9.78:0?discport=30301,enode://61841b7682f808f5ce8222f15d7de7f118a2c2c3e342fe42ea41e987ae22fb90e49ef2b5f394897e791c33c6fc59d7ad064851ee653badb2d6ece7a94040944b@54.91.75.177:0?discport=30301 -``` - -### 401 Unauthorized: signature invalid - -The JWT secret doesn't match between op-node and op-geth. Ensure both point to the same `jwt.txt` file. - -### 403 Forbidden: invalid host specified - -Add `--authrpc.vhosts=*` to op-geth, or set it to the specific hostname op-node uses to connect. - -### P2P directory permission denied - -op-node can't write to its P2P discovery directory. Either grant write access or redirect with: - -```bash ---p2p.discovery.path=/path/with/write/access ---p2p.peerstore.path=/path/with/write/access -``` - -### Wrong chain / mismatched genesis - -Verify that: -- `L1_RPC_URL` points to the correct L1 network (Ethereum mainnet for Shape, Sepolia for Shape Sepolia) -- `rollup.json` matches the network you intend to run -- op-geth was initialized with the correct `genesis.json` - -### Unclean shutdown detected - -op-geth prints this warning on startup after a crash or kill. It usually recovers on its own. If the database is unrecoverable, re-initialize from genesis or restore from a [snapshot](https://www.alchemy.com/snapshots/shape). - -## References - -- [Optimism node operator docs](https://docs.optimism.io/node-operators/overview) -- [Run a node from source (OP docs)](https://docs.optimism.io/node-operators/tutorials/run-node-from-source) -- [Build from source (OP docs)](https://docs.optimism.io/node-operators/tutorials/node-from-source) -- [Alchemy Shape snapshots](https://www.alchemy.com/snapshots/shape) -- [op-node configuration reference](https://docs.optimism.io/node-operators/reference/op-node-config) -- [op-geth configuration reference](https://docs.optimism.io/node-operators/reference/op-geth-config) -- [OP Stack troubleshooting](https://docs.optimism.io/node-operators/guides/troubleshooting) diff --git a/public/the-stack.md b/public/the-stack.md deleted file mode 100644 index a0dda25..0000000 --- a/public/the-stack.md +++ /dev/null @@ -1,52 +0,0 @@ -# The Stack - -The **Stack** is a dynamic NFT that serves as a living record of your achievements and contributions across the Shape ecosystem. - -By engaging with projects on Shape, you earn medals that showcase your journey and build your reputation in the community. - -## Getting Started - -### 1. Mint Your Stack - -Start by minting your Stack at [stack.shape.network](https://stack.shape.network/) - -### 2. Engage with Projects - -Engage with different projects in various ways on Shape. Interactions include: - -- Collecting NFTs -- Minting new creations -- Bidding on artwork auctions -- Exploring apps, games, and experiments - -### 3. Earn Medals - -As you engage, you'll earn medals issued by the community projects you interact with. There are 4 types of medals: - -- **Bronze (🟤):** Awarded for initial interactions -- **Silver (⚪):** Awarded for deeper involvement -- **Gold (🟡):** Awarded for significant contributions -- **Special (⚫):** Awarded for exceptional achievements - -### 4. Claim Medals - -Once a medal has been earned, you can claim it via your Stack dashboard. - -Your Stack NFT will dynamically update as you claim medals. - -### 5. Climb Ranks - -As you earn medals, you climb ranks in the [Leaderboard](https://stack.shape.network/leaderboard). - -Higher ranks may grant access to exclusive opportunities, such as allowlist spots for future Stack projects. - -## The Stack Keeps Stacking - -New projects and medals are added regularly. - -Stay up to date by following [@shape](https://twitter.com/shape) for the latest news. - -> Do you have a project you'd like to make part of the Stack? -> -> Reach out on [Twitter/X](https://x.com/shape) or in -> [Discord](https://discord.com/invite/shape-l2) to let us know. diff --git a/public/tools/account-abstraction.md b/public/tools/account-abstraction.md deleted file mode 100644 index 997358d..0000000 --- a/public/tools/account-abstraction.md +++ /dev/null @@ -1,25 +0,0 @@ -# Account Abstraction - -On Shape, combine AA with [Gasback](https://docs.shape.network/gasback.md) to subsidize your users and recoup 80% of sequencer fees. - -| Tool | Use case | -| --- | --- | -| Alchemy Bundler + Gas Manager | Full AA stack: bundled UserOps, gas sponsorship | -| Alchemy Embedded Accounts | Email/social login, no seed phrase | -| Alchemy Smart Accounts | Programmable accounts with custom validation | -| Crossmint NFT Checkout | Credit card NFT purchases, no wallet needed | -| Crossmint WaaS | Invisible wallets embedded in your app | - -See [Alchemy's AA overview](https://www.alchemy.com/learn/account-abstraction) for background. - -- [Alchemy Bundler](https://www.alchemy.com/account-abstraction-infrastructure): A highly reliable ERC-4337 bundler - -- [Alchemy Gas Manager](https://www.alchemy.com/gas-manager): Sponsor gas for your users - -- [Alchemy Embedded Accounts](https://www.alchemy.com/embedded-accounts): Bring users onchain in seconds. No seed phrase, no gas - -- [Alchemy Smart Accounts](https://www.alchemy.com/account-contracts): Fully abstract the user experience with secure & extensible smart accounts - -- [Crossmint NFT Checkout](https://www.crossmint.com/products/nft-checkout): Sell NFTs via credit cards and cross-chain payments - -- [Crossmint Wallet-as-a-Service](https://www.crossmint.com/): Invisible wallets, embedded in your app diff --git a/public/tools/bridges.md b/public/tools/bridges.md deleted file mode 100644 index ecab082..0000000 --- a/public/tools/bridges.md +++ /dev/null @@ -1,17 +0,0 @@ -# Bridges - -Bridge ETH and tokens between Ethereum and Shape. - -## Mainnet - -- [Relay](https://relay.link/shape): Instant bridging & cross-chain execution - -- [Superbridge](https://superbridge.app/shape-mainnet): Fast and secure native bridging - -- [Alchemy](https://shape-mainnet.bridge.alchemy.com/) - -## Sepolia - -- [Relay (Sepolia)](https://testnets.relay.link/bridge/shape-sepolia) - -- [Superbridge (Sepolia)](https://superbridge.app/shape-testnet) diff --git a/public/tools/data-indexers.md b/public/tools/data-indexers.md deleted file mode 100644 index b72af5c..0000000 --- a/public/tools/data-indexers.md +++ /dev/null @@ -1,35 +0,0 @@ -# Data Indexers - -| Service | Best for | -| --- | --- | -| Alchemy NFT/Token/Transfers APIs | General-purpose queries, NFT metadata, token balances | -| Alchemy Subgraphs | Custom GraphQL queries on indexed contract events | -| Alchemy Webhooks | Real-time notifications (transfers, mints, contract events) | -| Goldsky | Streaming onchain data to your database (Postgres, Kafka) | -| Reservoir | NFT marketplace data (listings, sales, collection stats) | -| SimpleHash | Cross-chain NFT and token metadata aggregation | - -Fetch NFTs owned by an address using the Alchemy NFT API: - -```ts -const res = await fetch( - `https://shape-mainnet.g.alchemy.com/nft/v3/${ALCHEMY_KEY}/getNFTsForOwner?owner=${address}` -); -const { ownedNfts } = await res.json(); -``` - -- [Alchemy NFT API](https://www.alchemy.com/nft-api): An API to launch, verify, analyze, trade & display NFTs - -- [Alchemy Subgraphs](https://www.alchemy.com/subgraphs): A fast & reliable GraphQL API - -- [Alchemy Token API](https://www.alchemy.com/token-api): Complete token data, no token list required - -- [Alchemy Transfers API](https://www.alchemy.com/transfers-api): Retrieve all historical transaction activity, including internal transfers - -- [Alchemy Webhooks](https://www.alchemy.com/webhooks): Realtime notifications for your users - -- [Goldsky](https://goldsky.com/): Livestream onchain data to your database - -- [Reservoir](https://reservoir.tools/): From market data to metadata, Reservoir APIs provide all-in-one endpoints - -- [SimpleHash](https://simplehash.com/): Instant access to Token & NFT market prices, metadata and media diff --git a/public/tools/explorers.md b/public/tools/explorers.md deleted file mode 100644 index 0efcc5d..0000000 --- a/public/tools/explorers.md +++ /dev/null @@ -1,18 +0,0 @@ -# Explorers - -| Explorer | Focus | -| --- | --- | -| Shapescan | Block explorer: transactions, contracts, verification | -| Shapescan Sepolia | Testnet block explorer | -| Deca | NFT explorer: collections, metadata, floor prices | -| Zapper | Portfolio and activity feed in a human-readable format | - -Verify your contracts on Shapescan to make them readable. See [Deploy a Contract](https://docs.shape.network/quick-start/deploy-a-contract.md) for verification steps. - -- [Shape Mainnet Explorer](https://shapescan.xyz/) - -- [Shape Sepolia Testnet Explorer](https://explorer-sepolia.shape.network/) - -- [Deca](https://deca.art/): See all NFTs on Shape in one place - -- [Zapper](https://zapper.xyz/): See what's happening onchain in a human readable way diff --git a/public/tools/faucets.md b/public/tools/faucets.md deleted file mode 100644 index ce3eb10..0000000 --- a/public/tools/faucets.md +++ /dev/null @@ -1,14 +0,0 @@ -# Faucets - -Get free testnet ETH on Shape Sepolia for development. - -1. Go to the Alchemy or Optimism faucet -2. Sign in with an account (free tier works) -3. Enter your wallet address -4. Receive testnet ETH (usually within seconds) - -- [Alchemy Faucet](https://www.alchemy.com/faucets/shape-sepolia) - -- [Optimism Faucet](https://console.optimism.io/faucet) - -> You can also [bridge Sepolia ETH](https://docs.shape.network/tools/bridges.md) to get started. diff --git a/public/tools/node-providers.md b/public/tools/node-providers.md deleted file mode 100644 index e3dd389..0000000 --- a/public/tools/node-providers.md +++ /dev/null @@ -1,14 +0,0 @@ -# Node Providers - -| Provider | Endpoint | Notes | -| --- | --- | --- | -| Public RPC | `https://mainnet.shape.network` | Rate-limited, not for production | -| Alchemy | `https://shape-mainnet.g.alchemy.com/v2/YOUR_KEY` | Higher limits, WebSocket, enhanced APIs | - -Sepolia: `https://sepolia.shape.network` (public) or `https://shape-sepolia.g.alchemy.com/v2/YOUR_KEY` (Alchemy). - -WebSocket: `wss://shape-mainnet.g.alchemy.com/v2/YOUR_KEY` - -The public RPC is rate-limited and not suitable for production. Use [Alchemy](https://www.alchemy.com/rpc/shape) (free tier available). - -- [Alchemy Supernode](https://www.alchemy.com/rpc/shape): A highly reliable RPC diff --git a/public/tools/oracles/gelato-vrf.md b/public/tools/oracles/gelato-vrf.md deleted file mode 100644 index df12a76..0000000 --- a/public/tools/oracles/gelato-vrf.md +++ /dev/null @@ -1,100 +0,0 @@ -# Gelato VRF - -- **Mechanism**: Uses [Drand](https://drand.love/), a decentralized source for random numbers. -- **Benefits**: Provides genuine, verifiable random values for blockchain applications. - -## Applications of Gelato VRF - -- **Gaming and Gambling**: For fair outcomes in online games and decentralized gambling. -- **Decentralized Finance (DeFi)**: Random selections for lotteries in DeFi protocols. -- **NFT Generation**: Random trait generation for unique digital assets. -- **Protocol Decision Making**: Randomized selections for validators or jurors. - -## Steps to Set Up Gelato VRF - -1. **Set Up Development Environment**: Install either Foundry or Hardhat. -2. **Install Gelato VRF Contracts**: Use specific commands for Hardhat or Foundry. -3. **Inherit** `GelatoVRFConsumerBase` **Contract**: Incorporate it into your contract. -4. **Request Randomness**: Call `_requestRandomness()` function. -5. **Implement Callback Function**: Define how your contract handles the randomness response. -6. **Include** `dedicated msg.sender`: Essential for contract security and function. - -## Quick Start - -### Step 1: Set Up Your Development Environment - -Make sure you have Hardhat or Foundry ready for use. - -### Step 2: Install Gelato VRF Contracts - -For Hardhat, clone the repository and set up the environment. For Foundry, use the `forge install` command. - -### Step 3: Inherit GelatoVRFConsumerBase Contract - -Create a contract that inherits from **GelatoVRFConsumerBase**. - -```solidity -// SPDX-License-Identifier: MIT -pragma solidity 0.8.18; - -import {GelatoVRFConsumerBase} from "./GelatoVRFConsumerBase.sol"; - -contract YourContract is GelatoVRFConsumerBase { - // Your contract's code -} -``` - -### Step 4: Request Randomness - -To request randomness, call the \_requestRandomness() function. You should protect the call since it will take from your 1Balance. The data argument will be passed back to you by the W3F. - -```solidity -function requestRandomness(bytes memory data) external { - require(msg.sender == ...); - uint64 requestId = _requestRandomness(data); -} -``` - -### Step 5: Implement Callback Function - -```solidity -function _fulfillRandomness( - bytes32 randomness, - uint64 requestId, - bytes memory data -) internal override { - // Your implementation here -} -``` - -### Step 6: Include Dedicated msg.sender - -When you're ready to deploy your Gelato VRF-compatible contract, an important step is to include the dedicated msg.sender as a constructor parameter. This ensures that your contract is set up to work with the correct operator for fulfilling the randomness requests. It's crucial for ensuring that only authorized requests are processed. - -```solidity -// SPDX-License-Identifier: MIT -pragma solidity 0.8.18; - -import {GelatoVRFConsumerBase} from "./GelatoVRFConsumerBase.sol"; - -contract YourContract is GelatoVRFConsumerBase { - constructor(address operator) - GelatoVRFConsumerBase(operator) { - // Additional initializations - } - - // The rest of your contract code -} -``` - -## Task Creation - -Upon deploying your contract, you will need to create a Gelato Task. This can be done via the [Gelato UI](https://app.gelato.network/). Next, you will be prompted to provide the address of the Request Contract to which the Gelato nodes should respond. Enter the address of your contract, and once all details have been correctly entered, proceed with launching your Gelato VRF instance. - -Now everytime you call the `_requestRandomness()` function, the Gelato nodes will respond with a random number that you can use in your contract. - -For more detailed information, refer to the [Gelato VRF documentation](https://docs.gelato.network/web3-services/vrf). - -![Gelato VRF 1](https://docs.shape.network/gelato-gui-1.webp) - -![Gelato VRF 2](https://docs.shape.network/gelato-gui-2.webp) diff --git a/public/tools/safes-asset-security.md b/public/tools/safes-asset-security.md deleted file mode 100644 index a354046..0000000 --- a/public/tools/safes-asset-security.md +++ /dev/null @@ -1,10 +0,0 @@ -# Safes & Asset Security - -Manage high-value assets and team operations securely on Shape. - -- **Safe**: Multi-signature wallet for team treasuries, protocol governance, or any operation requiring multiple approvals. Shape's Safe is at [safe.shape.network](https://safe.shape.network/). -- **Delegate**: Prove NFT ownership or claim airdrops from a hot wallet without moving assets from cold storage. - -- [Safe](https://safe.shape.network/): A decentralized custody protocol and collective asset management platform - -- [Delegate](https://delegate.xyz/): Claim airdrops, mint NFTs, and prove ownership via your hot wallet diff --git a/public/tools/sybil-resistance.md b/public/tools/sybil-resistance.md deleted file mode 100644 index 9ebe430..0000000 --- a/public/tools/sybil-resistance.md +++ /dev/null @@ -1,13 +0,0 @@ -# Sybil Resistance - -Protect your app from bots and sybil attacks while preserving user privacy. - -- **Passport**: Privacy-preserving identity scoring. Good for gating access, weighting rewards, detecting bots. -- **Premint**: Allowlist management for mints. Good for curated drops, community-first launches. -- **Crossmint Verifiable Credentials**: Issue and verify credentials at scale. Good for KYC-lite, compliance, loyalty programs. - -- [Passport](https://app.passport.xyz/#/shape/): A tool for dApps to defend against sybils while preserving user privacy - -- [Premint](https://www.premint.xyz/): Create allowlists tailored to your requirements - -- [Crossmint Verifiable Credentials](https://www.crossmint.com/products/verifiable-credentials): Issue and verify credentials at scale diff --git a/public/tutorials/mint-nft-collection.md b/public/tutorials/mint-nft-collection.md deleted file mode 100644 index 1072b24..0000000 --- a/public/tutorials/mint-nft-collection.md +++ /dev/null @@ -1,196 +0,0 @@ -# Launch an NFT Collection on Shape - -Deploy an ERC-721 contract to Shape Sepolia, mint an NFT, and verify it on the block explorer. - -## Prerequisites - -- [Foundry](https://book.getfoundry.sh/getting-started/installation) installed -- Shape Sepolia ETH from the [Alchemy Faucet](https://www.alchemy.com/faucets/shape-sepolia) -- A wallet private key funded with testnet ETH - -## 1. Set Up the Project - -```bash -forge init my-nft && cd my-nft -rm src/Counter.sol test/Counter.t.sol script/Counter.s.sol -forge install OpenZeppelin/openzeppelin-contracts --no-commit -``` - -Add the `remappings` line to `foundry.toml`: - -```toml -[profile.default] -src = "src" -out = "out" -libs = ["lib"] -remappings = ["@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/"] -``` - -## 2. Write the Contract - -Create `src/MyNFT.sol`: - -```solidity -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.20; - -import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; - -contract MyNFT is ERC721, Ownable { - uint256 public totalSupply; - uint256 public constant MAX_SUPPLY = 1000; - string private _baseTokenURI; - - constructor() ERC721("MyNFT", "MNFT") Ownable(msg.sender) {} - - function mint(address to) external onlyOwner { - require(totalSupply < MAX_SUPPLY, "Max supply reached"); - _mint(to, totalSupply); - totalSupply++; - } - - function setBaseURI(string calldata baseURI) external onlyOwner { - _baseTokenURI = baseURI; - } - - function _baseURI() internal view override returns (string memory) { - return _baseTokenURI; - } -} -``` - -## 3. Test - -Create `test/MyNFT.t.sol`: - -```solidity -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.20; - -import {Test} from "forge-std/Test.sol"; -import {MyNFT} from "../src/MyNFT.sol"; - -contract MyNFTTest is Test { - MyNFT nft; - - function setUp() public { - nft = new MyNFT(); - } - - function test_mint() public { - nft.mint(address(this)); - assertEq(nft.ownerOf(0), address(this)); - assertEq(nft.totalSupply(), 1); - } -} -``` - -```bash -forge test -``` - -## 4. Deploy to Shape Sepolia - -```bash -export PRIVATE_KEY= - -forge create src/MyNFT.sol:MyNFT \ - --rpc-url https://sepolia.shape.network \ - --private-key $PRIVATE_KEY -``` - -Save the `Deployed to` address from the output. - -## 5. Mint an NFT - -```bash -cast send "mint(address)" \ - --rpc-url https://sepolia.shape.network \ - --private-key $PRIVATE_KEY -``` - -Confirm the mint: - -```bash -cast call "ownerOf(uint256)" 0 \ - --rpc-url https://sepolia.shape.network -``` - -This returns your address (ABI-encoded, zero-padded to 32 bytes). - -## 6. Optional: Let Users Mint From Another Chain - -If your mint UI should let users start from Ethereum, Base, Arbitrum, or another supported chain, use Relay cross-chain call execution. The UI can let the user pay from an origin-chain balance while Relay executes the NFT mint call on Shape. - -The most important contract detail is to mint to an explicit recipient, like `mint(address to)`, instead of relying only on `msg.sender`. Relay's Shape-side address executes the destination call, so your UI should encode the buyer's address into the mint calldata and your contract should allow the Relay address to call that mint path. Treat this as a narrow exception: most arbitrary addresses should still be blocked from minting this way, but the Relay executor or relayer address you configure for Shape needs permission to call the function and mint the NFT to the recipient. - -```ts -import { getClient } from '@relayprotocol/relay-sdk'; -import { encodeFunctionData, parseEther, zeroAddress } from 'viem'; - -const relayClient = getClient(); -const shapeSepoliaChainId = 11011; // Use 360 for Shape mainnet. -const mintPrice = parseEther('0.01'); - -const callData = encodeFunctionData({ - abi: nftAbi, - functionName: 'mint', - args: [userAddress], -}); - -const quote = await relayClient.actions.getQuote({ - wallet, - chainId: originChainId, - toChainId: shapeSepoliaChainId, - currency: zeroAddress, - toCurrency: zeroAddress, - user: userAddress, - recipient: userAddress, - amount: mintPrice.toString(), - tradeType: 'EXACT_OUTPUT', - txs: [ - { - to: nftContractAddress, - value: mintPrice.toString(), - data: callData, - }, - ], -}); - -await relayClient.actions.execute({ - quote, - wallet, - onProgress: (progress) => { - // Use this to show states like: - // confirm in wallet -> origin transaction submitted -> relaying -> minted - }, -}); -``` - -For a free mint, set the mint transaction `value` and quote `amount` to `"0"`. For a paid mint, use `EXACT_OUTPUT` with the exact ETH value your mint call requires on Shape. Keep quotes fresh, check the user's origin-chain balance before enabling the mint button, and show a clear error if Relay has insufficient liquidity or the user lacks enough ETH for the amount, Relay fees, and origin-chain gas. - -The Stack mint UI uses the same pattern, with one extra convenience: users can optionally send additional ETH to themselves on Shape in the same Relay execution. That is just a second transaction in `txs` and is useful for onboarding, but most mint UIs only need the Shape contract call. - -See Relay's [Call Execution Integration Guide](https://docs.relay.link/references/api/api_guides/calling-integration-guide#common-use-cases) for the full quote, execution, and status flow. - -## 7. Verify on Shapescan - -```bash -forge verify-contract src/MyNFT.sol:MyNFT \ - --verifier blockscout \ - --verifier-url https://sepolia.shapescan.xyz/api/ -``` - -Once verified, view your contract at `https://sepolia.shapescan.xyz/address/`. - -## 8. Register for Gasback - -Register your contract for [Gasback](https://docs.shape.network/tutorials/registering-contract-gasback/index.md) to reclaim 80% of sequencer fees users spend interacting with it. - -## Next Steps - -- **Deploy to mainnet**: Use `--rpc-url https://mainnet.shape.network` and verify against `https://shapescan.xyz/api/` -- **View on Deca**: Once on mainnet, see your collection at `https://deca.art/token/shape//` -- **Add metadata**: Upload JSON metadata to IPFS with [Pinata](https://pinata.cloud/), then call `setBaseURI` to point your tokens at it -- [Build a dApp](https://docs.shape.network/building-on-shape/builder-kit.md) with the Shape Builder Kit diff --git a/public/tutorials/registering-contract-gasback/dashboard.md b/public/tutorials/registering-contract-gasback/dashboard.md deleted file mode 100644 index 4a97437..0000000 --- a/public/tutorials/registering-contract-gasback/dashboard.md +++ /dev/null @@ -1,65 +0,0 @@ -# Registering via the Dashboard - -This tutorial will guide you through the process of registering your smart contract for gasback using the Gasback Dashboard UI. - -## Prerequisites - -1. Your smart contract must be deployed on Shape. -2. You need access to a Web3 wallet (like MetaMask) with the account that owns the smart contract you want to register. -3. Your smart contract must have an owner() function which returns the address of the account you will connect to the dashboard - -## Step 1: Access the Dashboard - -Open your web browser and navigate to the [Gasback dashboard](https://gasback.shape.network/). - -![Gasback Dashboard](https://docs.shape.network/gasback-dashboard-1.webp) - -## Step 2: Connect Your Wallet - -1. Click the "Connect Wallet" button in the top right corner of the page. -2. A popup will appear with various wallet options. Select your preferred wallet (e.g., MetaMask). -3. Follow the prompts in your wallet to connect to the site and select the account you want to use. - -![Connect Wallet](https://docs.shape.network/gasback-dashboard-2.webp) - -## Step 3: View Your Gasback Dashboard - -1. Once connected, you'll see your Gasback dashboard. -2. If you haven't registered any contracts yet, you'll see a hero banner explaining that you don't have a gasback NFT yet. - -![Gasback Dashboard](https://docs.shape.network/gasback-dashboard-3.webp) - -## Step 4: Initiate registration and enter contract details - -1. Click the "Register" button in the hero banner or the header. and a popup window titled "Register a new smart contract" will appear. -2. In the "Contract Address" field, enter the address of the smart contract you want to register for gasback. -3. The "NFT Recipient" field should automatically populate with your connected wallet address. This is the address that will receive the gasback NFT. You can change this if you want the NFT to go to a different address. -4. Click “Register” - -![Register Contract](https://docs.shape.network/gasback-dashboard-4.webp) - -## Step 5: Confirm Registration - -1. Read the warning message and double-check that all the information is correct. -2. Click the "Confirm" button. -3. Your wallet will prompt you to confirm the transaction. Review the details and confirm the transaction. -4. Wait for the transaction to be processed and confirmed on the blockchain. - -![Confirm Registration](https://docs.shape.network/gasback-dashboard-5.webp) - -## Step 6: Verify Registration - -1. After the transaction is confirmed, the dashboard should update to reflect your newly registered contract. -2. You did it! You should see your unique gasback NFT that was generated onchain. The art on your NFT will evolve as your token accrues gasback. - -![Verify Registration](https://docs.shape.network/gasback-dashboard-6.webp) - -## Step 7: Managing Your Gasback - -Your dashboard will now display any gasback activity related to your registered contract. Activity can take up to 10 minutes to show up here. Registration itself earns you gasback, so you've already started your journey! - -If you have more contracts you want to register for Gasback, you can click the “manage” button and add their contract addresses to the field, and all the gasback earned by those contracts will be claimable with a single NFT. - -![Manage Gasback](https://docs.shape.network/gasback-dashboard-7.webp) - -That's it! If you're less of a UI person, check out the next section to see how to do this programmatically. diff --git a/public/tutorials/registering-contract-gasback/index.md b/public/tutorials/registering-contract-gasback/index.md deleted file mode 100644 index 41d3233..0000000 --- a/public/tutorials/registering-contract-gasback/index.md +++ /dev/null @@ -1,7 +0,0 @@ -# Registering Your Contract for Gasback - -There are two different methods to register your contract for Gasback registration. You can either use the UI, or register programmatically from the contract you wish to register. This section has tutorials on how to do each approach. - -- [Using the dashboard](https://docs.shape.network/tutorials/registering-contract-gasback/dashboard.md) - -- [Programmatically](https://docs.shape.network/tutorials/registering-contract-gasback/programmatically.md) diff --git a/public/tutorials/registering-contract-gasback/programmatically.md b/public/tutorials/registering-contract-gasback/programmatically.md deleted file mode 100644 index 9dcaa67..0000000 --- a/public/tutorials/registering-contract-gasback/programmatically.md +++ /dev/null @@ -1,168 +0,0 @@ -# Registering Programmatically - -This tutorial will guide you through the process of registering your smart contract for gasback programmatically. The tutorial walks through 3 different approaches you can use, with full example contracts. - -## Prerequisites - -1. Some familiarity with Solidity and Node JS. -2. If you want to actually deploy the contracts we'll go through so that you can get hands on, download the example repo [here](https://github.com/shape-network/gasback-tutorial). -3. (Optional) If you do decide to deploy the contracts and register, you'll need some Shape Sepolia ETH which you can get from the [Alchemy faucet](https://www.alchemy.com/faucets/shape-sepolia) or the [Superchain faucet](https://console.optimism.io/faucet). You will then need to create a `.env` file according to the `.env.example` file in the repo. - -## Example A: Registering inside the contract and sending the Gasback NFT to the contract owner to hold - -The code snippet below is the complete implementation of a contract called ExampleA, that we'll use for the first example. - -A is an Ownable contract, which means external callers can call an `owner()` method to determine which address has control over the contract. - -```solidity filename="ExampleA.sol" -pragma solidity 0.8.20; - -import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; -import {IGasback} from "./interfaces/IGasback.sol"; - -contract ExampleA is Ownable { - IGasback public gasback; - - constructor(address _gasback) Ownable(msg.sender) { - gasback = IGasback(_gasback); - } - - function registerForGasback() public onlyOwner { - gasback.register(owner(), address(this)); - } -} -``` - -As you can see, registration happens in one line, on line 14: `gasback.register(owner(), address(this));`. This says, register this address for gasback, and send the NFT to the owner of this contract. - -Inside the Gasback.sol contract (not shown), the `owner()` function of the contract that is registering gets called, so that the Gasback contract knows that the person due to receive the Gasback NFT is the person who controls the registering contract. - -> Warning: -> -> If your contract tries to register in the constructor, the call will fail. Registration must -> happen after contract construction. - -To deploy the contract above run: - -```bash -npx hardhat deployA --network shapeSepolia -``` - -You'll then see the deployed address in the console. - -To run the registration function, run: - -```bash -npx hardhat registerA --network shapeSepolia -``` - -Where the deployed address is the address printed in the deployment command. - -Once that's done, you can actually visit the [Gasback dashboard](https://gasback.shape.network/) and see your new Gasback NFT! - -## Example B: Registering inside a contract without requiring an owner - -```solidity filename="ExampleB.sol" -pragma solidity 0.8.20; - -import {IGasback} from "./interfaces/IGasback.sol"; -import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; - -contract ExampleB is IERC721Receiver { - IGasback public gasback; - - constructor(address _gasback) { - gasback = IGasback(_gasback); - } - - function registerForGasback() public { - address me = address(this); - gasback.register(me, me); - } - - function onERC721Received( - address operator, - address from, - uint256 tokenId, - bytes calldata data - ) external override returns (bytes4) { - return IERC721Receiver.onERC721Received.selector; - } -} -``` - -Contract B differs from A in a couple of key ways. Firstly, you'll notice that ExampleB is not an Ownable contract. The reason it's still able to register despite this, is that the contract itself is going to be the recipient of the Gasback NFT. This means we don't have to check an owner, because it's clearly registering itself. - -The second key change is the addition of the `onERC721Received` function. This inclusion is needed because Gasback.sol uses `_safeMint` to mint the NFT, which requires that any contract that receives the NFT implements this function, so that we know the NFT won't be stuck forever inside the contract, and the contract is actually expecting to receive and handle NFTs. - -> Warning: -> -> When implementing this pattern a function protected by some form of access control that -> withdraws the NFT from your contract is a great fallback option. - -Similar to example A you can deploy and run the registration function yourself by doing: - -```bash -npx hardhat deployB --network shapeSepolia -``` - -and - -```bash -npx hardhat registerB --network shapeSepolia -``` - -However in this example you won't see the NFT in your dashboard yet because you aren't the owner of it, the contract is! We'll explain how you can still manage the NFT that one of your contracts holds in a later tutorial, when we discuss the concept of **Delegation**. - -## Example C: Registering outside of a contract - -```solidity filename="ExampleC.sol" -pragma solidity 0.8.20; - -import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; - -contract ExampleC is Ownable { - constructor() Ownable(msg.sender) {} -} -``` - -The final example is a tiny contract. It has no logic in it other than to make itself Ownable. But, we can still register it for Gasback! - -The registration logic happens outside of the contract. All you have to do is call the registration on the Gasback contract directly, entering your own address as the NFT recipient and the contract address. - -You can see how this is done in `scripts/register.ts` in the registerC task: - -```typescript -task('registerC', 'Registers the ExampleC contract for gasback') - .addPositionalParam('contractAddress', 'The address of the ExampleC contract to register') - .setAction(async (taskArgs, hre) => { - const { contractAddress } = taskArgs; - - const [address] = await hre.ethers.getSigners(); - - const gasback = await hre.ethers.getContractAt('Gasback', gasbackAddress); - - const tx = await gasback.register(address, contractAddress); - await tx.wait(1); - - console.log('ExampleC registered! Tx hash: ', tx.hash); - }); -``` - -Of course, as proof it works, you can deploy and register using similar commands as before: - -```bash -npx hardhat deployC --network shapeSepolia -``` - -and - -```bash -npx hardhat registerC --network shapeSepolia -``` - -If you want an easy way to do this method, you can simply use the Gasback dashboard UI, connect your wallet, and paste in the contract address. The UI will make the contract call for you. - -## Summary - -That's it! You have now learned 3 different ways to register your contract for Gasback. In the next tutorials, we'll discuss how to delegate gasback rights when your contract owns the NFT instead of you, and we'll learn how to withdraw claimed gasback. diff --git a/public/wallet-setup.md b/public/wallet-setup.md deleted file mode 100644 index b434e3b..0000000 --- a/public/wallet-setup.md +++ /dev/null @@ -1,25 +0,0 @@ -# Wallet Setup - -Set up your wallet on Shape. - -## 1. Add Shape to Your Wallet - -1. Go to the [Shape website](https://shape.network/) -2. Scroll down to the "Get Started" section and click "Add Shape Mainnet" -3. You'll be prompted to switch to the Shape network - - If the network isn't listed, you can [add it manually](https://docs.shape.network/technical-details/network-information.md) - -## 2. Bridge to Shape - -1. Choose a [bridge](https://shape.network/bridge) to Shape -2. Send ETH over to Shape from another chain -3. Once complete, check your ETH balance on Shape - - If you don't see your balance, make sure your wallet is connected to the Shape network - -## 3. Mint Your Stack - -Build your onchain reputation on Shape by earning medals with the Stack. It's also the most effective way to claim more $SHAPE. - -[Mint your Stack](https://stack.shape.network/) - -More on the Stack in the next section. diff --git a/scripts/generate-ai-docs.mjs b/scripts/generate-ai-docs.mjs index 099e52a..aa109f7 100644 --- a/scripts/generate-ai-docs.mjs +++ b/scripts/generate-ai-docs.mjs @@ -160,27 +160,11 @@ export async function generate(root) { const body = convert(source, { components, paths, routes, route: record.route }); const title = body.match(/^# (.+)$/m)?.[1]; if (!title) throw new Error(`Missing title: ${record.file}`); - const descriptions = { - '/technical-details/network-information': - 'Mainnet and testnet chain IDs, ETH gas currency, RPC endpoints, and explorers.', - '/technical-details/contract-addresses': - 'Official network infrastructure contract addresses.', - '/the-stack': - 'Dynamic NFT achievements, participation, and medals across the Shape ecosystem.', - '/tutorials/registering-contract-gasback': - 'Choose dashboard or programmatic contract registration for Gasback.', - '/building-on-shape/ai': - 'Shape MCP, AI integration examples, and agent development guidance.', - '/tools/node-providers': 'Public and provider RPC endpoints for mainnet and testnet.', - '/tools/data-indexers': 'NFT queries, indexing services, and data APIs.', - '/tools/oracles/gelato-vrf': - 'Request verifiable randomness from smart contracts using Gelato VRF.', - }; const paragraph = body .split('\n\n') .map((block) => block.trim()) .find((block) => block && !/^(#|>|-|\d+\.|\||`|~)/.test(block)); - let description = (descriptions[record.route] || paragraph || 'Documentation for ' + title) + let description = (paragraph || 'Documentation for ' + title) .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1') .replace(/[*`]/g, '') .replace(/\s+/g, ' ') @@ -244,10 +228,10 @@ export async function generate(root) { ], ]; const used = new Set(); + const introduction = rendered.find((record) => record.route === '/'); let index = - '# Shape Documentation\n\n> Official technical documentation for Shape, an Ethereum L2 built on the OP Stack and part of the Optimism Superchain.\n\n' + - 'Mainnet chain ID: 360. Shape Sepolia chain ID: 11011. Gas currency: ETH. Gasback shares 80% of L2 sequencer fees with registered contract owners, excluding L1 data fees.\n\n' + - 'Links below lead to Markdown generated from the same source as the website. Follow the relevant pages for full context. For current $SHAPE token and governance information, see https://shape.network/token.\n\n'; + `# Shape Documentation\n\n> ${introduction.description}\n\n` + + 'Links below are generated from the existing documentation source. Follow individual pages for details.\n\n'; for (const [title, entries] of [ ...sections, ['Tools and Further Reading', rendered.map((record) => record.route)], @@ -268,7 +252,7 @@ export async function generate(root) { '/llms-full.txt): All generated pages in one file. Use individual pages for narrower questions.\n'; await writeFile(path.join(publicDir, 'llms.txt'), index); const full = - '# Shape Technical Documentation\n\nGenerated from the official documentation source. This is the technical corpus; token and governance information is maintained at https://shape.network/token.\n\n' + + '# Shape Technical Documentation\n\nGenerated from the existing documentation source.\n\n' + rendered .map( (record) => From f7c00dd239c9a4b2e4cfc88acd03bc5504295a57 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 23:06:20 +0000 Subject: [PATCH 3/3] Derive Markdown alternates from source path; improve generated summaries - generateMetadata now maps Nextra's metadata.filePath to the generated .md path instead of reading the manifest from disk for every page, so pages no longer depend on a runtime file read and use paths.canonical for the origin. - Page summaries in llms.txt come from the lead paragraph, an opening table's first column, or section headings, instead of falling back to 'Documentation for ' or a sentence that only introduces a code example. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017YU1EuhLrUiADjcd88gTCa --- README.md | 2 +- app/[[...mdxPath]]/page.tsx | 24 ++++++------------------ scripts/generate-ai-docs.mjs | 25 ++++++++++++++++++++++--- 3 files changed, 29 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index e77bd6c..8e03c55 100644 --- a/README.md +++ b/README.md @@ -52,4 +52,4 @@ bun run test:ai-docs Edit the MDX source or shared components, then regenerate the assets. Do not edit generated Markdown directly. The converter handles the current static MDX patterns and stops on unknown components, unclosed code fences, or unmapped documentation links. Add conversion support and a test when introducing a new MDX component. Fenced code blocks are preserved verbatim. -Generated files under `public/` are ignored by Git. Both development and production scripts generate them from the existing source before starting Next.js. `.ai-docs-manifest.json` records the generated page paths so deleted pages are removed on regeneration and HTML alternatives use the same route map. Titles, summaries, examples, and component text come from the original content; only navigation grouping is configured in the generator. +Generated files under `public/` are ignored by Git. Both development and production scripts generate them from the existing source before starting Next.js. `.ai-docs-manifest.json` records the generated page paths so deleted pages are removed on regeneration. Each HTML page derives its Markdown alternate from its source file path, which the generator mirrors under `public/`. Titles, summaries, examples, and component text come from the original content; only navigation grouping is configured in the generator. diff --git a/app/[[...mdxPath]]/page.tsx b/app/[[...mdxPath]]/page.tsx index bf0fb5f..ac9f351 100644 --- a/app/[[...mdxPath]]/page.tsx +++ b/app/[[...mdxPath]]/page.tsx @@ -1,5 +1,4 @@ -import { readFile } from 'node:fs/promises'; -import path from 'node:path'; +import { paths } from '@paths'; import { generateStaticParamsFor, importPage } from 'nextra/pages'; import { useMDXComponents as getMDXComponents } from '../../mdx-components'; @@ -8,28 +7,17 @@ export const generateStaticParams = generateStaticParamsFor('mdxPath'); export async function generateMetadata(props) { const params = await props.params; const { metadata } = await importPage(params.mdxPath); - const markdownPages: string[] = JSON.parse( - await readFile(path.join(process.cwd(), 'public/.ai-docs-manifest.json'), 'utf8') - ); - const segments = params.mdxPath || []; - const route = '/' + segments.join('/'); - const indexes = new Set( - markdownPages - .filter((file) => file.endsWith('/index.md') || file === 'index.md') - .map((file) => '/' + file.replace(/(^|\/)index\.md$/, '').replace(/\/$/, '')) - ); - const markdown = indexes.has(route) - ? route === '/' - ? '/index.md' - : route + '/index.md' - : route + '.md'; + // Nextra exposes the source file (e.g. content/quick-start/index.mdx); the AI docs + // generator writes its Markdown twin to the same relative path under public/. + const markdown = metadata.filePath?.replace(/^content\//, '/').replace(/\.mdx?$/, '.md'); + if (!markdown) return metadata; return { ...metadata, alternates: { ...metadata.alternates, types: { ...metadata.alternates?.types, - 'text/markdown': 'https://docs.shape.network' + markdown, + 'text/markdown': paths.canonical + markdown, }, }, }; diff --git a/scripts/generate-ai-docs.mjs b/scripts/generate-ai-docs.mjs index aa109f7..ba32515 100644 --- a/scripts/generate-ai-docs.mjs +++ b/scripts/generate-ai-docs.mjs @@ -160,11 +160,30 @@ export async function generate(root) { const body = convert(source, { components, paths, routes, route: record.route }); const title = body.match(/^# (.+)$/m)?.[1]; if (!title) throw new Error(`Missing title: ${record.file}`); - const paragraph = body + // Summarise from the lead (between the title and the first section, or the first + // section when there is no lead): its opening paragraph, else the first column of + // an opening table, else a paragraph that does not just introduce an example, + // else the page's section headings. + const [intro, first = ''] = body.slice(body.indexOf('\n') + 1).split(/^## /m); + const lead = (intro.trim() ? intro : first.slice(first.indexOf('\n') + 1)) .split('\n\n') .map((block) => block.trim()) - .find((block) => block && !/^(#|>|-|\d+\.|\||`|~)/.test(block)); - let description = (paragraph || 'Documentation for ' + title) + .filter(Boolean); + const isParagraph = (block) => !/^(#|>|-|\*|\d+\.|\||`|~|!\[)/.test(block); + const tableRows = (block) => + block + .split('\n') + .slice(2) + .map((row) => row.split('|')[1]?.trim()) + .filter(Boolean); + const sections = [...body.matchAll(/^## (.+)$/gm)].map((match) => match[1].trim()); + let summary; + if (lead[0] && isParagraph(lead[0])) summary = lead[0].replace(/:$/, '.'); + else if (lead[0]?.startsWith('|') && tableRows(lead[0]).length) + summary = `${title}: ${tableRows(lead[0]).join(', ')}.`; + else summary = lead.find((block) => isParagraph(block) && !block.endsWith(':')); + if (!summary && sections.length) summary = `${title}: ${sections.join(', ')}.`; + let description = (summary || `Documentation for ${title}.`) .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1') .replace(/[*`]/g, '') .replace(/\s+/g, ' ')