diff --git a/.env-example b/.env-example index 7c9c333e3..3dded82cd 100644 --- a/.env-example +++ b/.env-example @@ -1,4 +1,2 @@ -NEXT_PUBLIC_ALGOLIA_APP_ID= -NEXT_PUBLIC_ALGOLIA_API_KEY= -NEXT_PUBLIC_ALGOLIA_INDEX= NEXT_PUBLIC_GTM_ID= +LLMS_BASE_URL= diff --git a/.eslintrc.json b/.eslintrc.json index ed21dd815..86fed8bef 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,6 +1,11 @@ { "extends": ["next/core-web-vitals", "next/typescript"], "rules": { - "@typescript-eslint/no-explicit-any": "off" + "@typescript-eslint/no-explicit-any": "off", + "react-hooks/rules-of-hooks": "off", + "@next/next/no-img-element": "off", + "@typescript-eslint/no-empty-object-type": "off", + "@typescript-eslint/no-unused-vars": "off", + "react-hooks/exhaustive-deps": "off" } } \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 00dbe2e98..000000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,16 +0,0 @@ -## Description - -Describe the changes that were made in this pull request. When possible start with the motivations behind the change. Be sure to also include the following information: - -1. Motivation for change? -2. What was changed? -3. Link to relevant issues? - -## Checklist - -- [ ] [Conventional commits were used](https://www.conventionalcommits.org/en/v1.0.0/) -- [ ] New links to files and images were verified -- [ ] For fixes/refactors: all existing references were identified and replaced -- [ ] [Style guide](https://developers.google.com/style) was reviewed and applied -- [ ] Clear code samples were provided -- [ ] People were tagged for review diff --git a/.github/mlc_config.json b/.github/mlc_config.json deleted file mode 100644 index 9ec46cca3..000000000 --- a/.github/mlc_config.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "ignorePatterns": [ - { - "pattern": "^http://localhost" - }, - { - "pattern": "^https://banter.pub" - }, - { - "pattern": "^/img" - }, - { - "pattern": "(gaia|hub).blockstack.org" - }, - { - "pattern": "explorer.hiro.so/txid" - }, - { - "pattern": "explorer-api.legacy.blockstack.org" - }, - { - "pattern": "archive.hiro.so" - }, - { - "pattern": "identity.foundation" - }, - { - "pattern": "stackoverflow.com/questions/tagged/stacks\\-blockchain\\+or\\+clarity\\-lang", - "comment": "// Returns a 403 sometimes" - } - ], - "replacementPatterns": [ - { - "pattern": "^/", - "replacement": "https://docs.hiro.so/" - } - ], - "timeout": "10s", - "retryOn429": true, - "retryCount": 5, - "aliveStatusCodes": [200, 206, 406, 400] -} diff --git a/.github/workflows/board-automation.yaml b/.github/workflows/board-automation.yaml deleted file mode 100644 index 470904311..000000000 --- a/.github/workflows/board-automation.yaml +++ /dev/null @@ -1,16 +0,0 @@ -name: Board automation for Docs project - -on: - issues: - types: - - opened - -jobs: - add-to-project: - name: Add issue to project Docs - runs-on: ubuntu-latest - steps: - - uses: actions/add-to-project@main - with: - project-url: https://github.com/orgs/hirosystems/projects/43 - github-token: ${{ secrets.GH_TOKEN }} diff --git a/.github/workflows/linkcheck-prs.yml b/.github/workflows/linkcheck-prs.yml deleted file mode 100644 index 91d71fb23..000000000 --- a/.github/workflows/linkcheck-prs.yml +++ /dev/null @@ -1,14 +0,0 @@ -name: linkcheck -on: - pull_request: - branches: [main] - -jobs: - linkcheck: - runs-on: ubuntu-latest - if: github.event.pull_request.head.repo.full_name == github.repository - steps: - - uses: actions/checkout@v3 - - uses: gaurav-nelson/github-action-markdown-link-check@v1 - with: - config-file: ".github/mlc_config.json" diff --git a/.github/workflows/linkcheck.yml b/.github/workflows/linkcheck.yml new file mode 100644 index 000000000..5e0583a0a --- /dev/null +++ b/.github/workflows/linkcheck.yml @@ -0,0 +1,32 @@ +name: linkcheck + +on: + push: + branches: ["main"] + pull_request: + branches: ["main"] + workflow_dispatch: + +jobs: + lint: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Bun + uses: oven-sh/setup-bun@v1 + with: + bun-version: latest + + - name: Install dependencies + run: bun install --frozen-lockfile + + - name: Generate llms.txt files + run: bun run generate-llms + env: + LLMS_BASE_URL: https://docs.hiro.so + + - name: Run link validation + run: bun run lint diff --git a/.github/workflows/stylecheck-prs.yml b/.github/workflows/stylecheck-prs.yml deleted file mode 100644 index e37c69e9a..000000000 --- a/.github/workflows/stylecheck-prs.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: stylecheck -on: - pull_request: - branches: [main] - paths: - - '**.md' - -jobs: - stylecheck: - runs-on: ubuntu-latest - if: github.event.pull_request.head.repo.full_name == github.repository - steps: - - name: checkout - uses: actions/checkout@v4 - - name: get changed Files - id: get_changed_files - uses: lots0logs/gh-action-get-changed-files@2.1.4 - with: - token: ${{ secrets.GITHUB_TOKEN }} - - name: run vale - uses: errata-ai/vale-action@reviewdog - with: - files: '${{ steps.get_changed_files.outputs.all }}' - onlyAnnotateModifiedLines: true - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index b1f63bec0..835decd5a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,6 @@ bun.lockb node_modules -openapi +/openapi .DS_Store **/.DS_Store .env @@ -8,4 +8,15 @@ openapi .cache .cursorrules .next -tmp \ No newline at end of file +.source/ +tmp +.cursor/ +.claude/ + +# Local workflow files +/tasks/** +*.local.* + +# Generated files +public/**/*.txt +/generated \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 000000000..fd4af3aa2 --- /dev/null +++ b/README.md @@ -0,0 +1,215 @@ +# Hiro Docs + +Documentation for Hiro Systems PBC. Built with [Fumadocs](https://fumadocs.vercel.app/) and enhanced with custom components. + +## Contributing + +### Documentation Structure + +**Component-Based** (`/tools/*`): Features organized by tool capabilities + +Example structure: + +``` +/tools/clarinet/ +├── Overview/ # Introduction and setup +├── Clarinet CLI/ # Command-line features +├── Clarinet JS SDK/ # Testing and programmatic usage +└── Integrations/ # External connections +``` + +### Writing Guidelines + +Follow our content rhythm pattern: + +``` +Paragraph (2-3 sentences) → Code Example → Paragraph → List/Table → Code +``` + +- **60% code, 40% text** - Show, don't just tell +- **Never put two paragraphs in a row** - Break with code/lists/tables +- **Every concept needs a code example** +- **Use complete, contextual sentences** - Explain "why" before "how" + +### Available Components + +#### Layout Components + +````mdx + + + ### Action verb phrase Context sentence explaining what and why. ```terminal + $ command with options ``` + + + +--- + + + +```terminal !! macOS +$ brew install tool +``` + +```terminal !! Windows +$ winget install tool +``` + + + +--- + + + +```typescript +const result = await contract.call(); +``` + +```javascript +const result = await contract.call(); +``` + + +```` + +#### Directives (Auto-converted to components) + + +```mdx +:::callout +type: tip|info|warn|help +### Optional Title +Content here +::: + +:::objectives +- What you'll learn +- Another learning objective +::: + +:::prerequisites +- Required knowledge +- Tools needed +::: + +:::next-steps +- [Next Guide](/path): Description +- [Another Guide](/path): Description +::: +``` + + +#### Interactive Components + +```mdx + + + Question + Answer + + + + +``` + +#### Code Block Features + +**Languages**: `terminal`, `clarity`, `typescript`, `javascript`, `json`, `yaml`, `console`, `package-install` + +**Flags**: `-n` (line numbers), `-c` (copy button), `-w` (word wrap), `-a` (animate) + +**Annotations**: + +````mdx +```ts +// !mark[3:5] Highlight lines 3-5 +// !mark[/regex/] Highlight pattern +// !diff + Addition +// !diff - Removal +// !collapse[3:5] Collapse lines +``` +```` + +```` + +**Special blocks**: + +```terminal +$ command # Renders with prompt +``` + +```package-install +@stacks/connect # Auto-generates npm/yarn/pnpm commands +``` + +```` + +### Page Templates + +#### Overview Page +```mdx +--- +title: Tool Name +sidebarTitle: Overview +description: Brief tool description +--- + +## Overview +Expand on what the tool does and its value. Include llms.txt link if available. + +## Key features +- ✓ **Feature** - User benefit description +- ✓ **Feature** - Technical capability explained simply + +## Installation +... + +:::next-steps +- [Quickstart](/path): Get started in minutes +::: +```` + +#### Quickstart Page + +```mdx +--- +title: Quickstart +description: Learn how to [task] with [tool] +--- + +Brief intro paragraph about what you'll build. + +:::objectives +- Learning objective 1 +- Learning objective 2 +::: + +:::prerequisites +- Prerequisites +::: + +## Quickstart + +[3-5 focused steps] + +:::next-steps +- [Next Guide](/path): Description +::: +``` + +### File Structure + +- `/content/docs/` - All documentation content +- `/components/` - Custom components +- `/public/` - Images and static assets +- `meta.json` files control sidebar organization + +### Quick Checklist + +- Follow content rhythm (no consecutive paragraphs) +- 60% code, 40% text ratio +- Every concept has a code example +- Use appropriate page template +- Specify language for all code blocks +- Include context before code +- Keep paragraphs to 2-3 sentences diff --git a/app/(docs)/[...slug]/page.tsx b/app/(docs)/[...slug]/page.tsx index 5ae7fe988..b5cc9a718 100644 --- a/app/(docs)/[...slug]/page.tsx +++ b/app/(docs)/[...slug]/page.tsx @@ -1,135 +1,317 @@ -import type { Metadata } from "next"; -import { Card, Cards } from "fumadocs-ui/components/card"; -import { RollButton } from "fumadocs-ui/components/roll-button"; -import { DocsPage, DocsBody } from "fumadocs-ui/page"; +import fs from "fs/promises"; +import matter from "gray-matter"; +import { source } from "@/lib/source"; import { notFound } from "next/navigation"; -import { utils, type Page } from "@/utils/source"; -import { createMetadata, getRouteMetadata } from "@/utils/metadata"; +import type { HeadingProps } from "@/types"; +import { getMDXComponents } from "@/components/mdx"; +import { API } from "@/components/reference/api-page"; +import { APIPage } from "@/components/openapi/api-page"; +import { Badge } from "@/components/ui/badge"; +import { + DocsPage, + DocsPageLayout, + DocsPageHeader, + DocsPageContent, + DocsPageContentWrapper, + DocsPageBreadcrumb, + DocsPageTitle, + DocsPageDescription, + DocsPageProse, +} from "@/components/layouts/page"; +import { + InteractiveHeader, + InteractiveLayout, +} from "@/components/layouts/interactive"; +import defaultMdxComponents from "fumadocs-ui/mdx"; +import { LLMShare } from "@/components/llm-share"; +import { CheckIcon } from "lucide-react"; +import { TagFilterSystem } from "@/components/ui/tag-filter-system"; +import { getAllFilterablePages } from "@/lib/source"; +import { Mermaid } from "@/components/mdx/mermaid"; +import { Callout } from "@/components/callout"; +import * as customIcons from "@/components/ui/icon"; +import * as lucideIcons from "lucide-react"; -interface Param { - slug: string[]; -} +export default async function Page(props: { + params: Promise<{ slug?: string[] }>; +}) { + const params = await props.params; + const page = source.getPage(params.slug); + if (!page) notFound(); -export const dynamicParams = false; + const fileContent = await fs.readFile(page.data._file.absolutePath, "utf-8"); + const { content: rawMarkdownContent } = matter(fileContent); -export default function Page({ params }: { params: Param }): JSX.Element { - const page = utils.getPage(params.slug); + const LLMContent = rawMarkdownContent + .split("\n") + .filter((line) => !line.trim().startsWith("import")) + .join("\n") + .trim(); - if (!page) notFound(); + const MDX = page.data.body; + + if (!MDX) { + console.error("MDX component is undefined for page:", page.url); + notFound(); + } + + // Get all filterable pages for tag filtering + const allFilterablePages = getAllFilterablePages(); + + // Extract section from current page URL for scoped filtering + const currentSection = page.url.split("/").filter(Boolean)[1] || "general"; + + // Helper function to get icon component + const getIconComponent = (iconName: string) => { + const iconProps = { className: "w-3 h-3 shrink-0" }; + + // Check custom icons first + const CustomIcon = (customIcons as any)[iconName]; + if (CustomIcon && typeof CustomIcon === "function") { + return ; + } + + // Try with "Icon" suffix for custom icons + const CustomIconWithSuffix = (customIcons as any)[`${iconName}Icon`]; + if (CustomIconWithSuffix && typeof CustomIconWithSuffix === "function") { + return ; + } + + // Check lucide icons - try multiple naming patterns + const lucidePatterns = [ + iconName, // exact name + `${iconName}Icon`, // with Icon suffix + iconName.charAt(0).toUpperCase() + iconName.slice(1), // capitalize first letter + `${iconName.charAt(0).toUpperCase() + iconName.slice(1)}Icon`, // capitalize + Icon + ]; + + for (const pattern of lucidePatterns) { + const LucideIcon = (lucideIcons as any)[pattern]; + if (LucideIcon && typeof LucideIcon === "function") { + return ; + } + } + + return null; + }; + + // Convert icon names to React components + const interactiveLinks = page.data.interactiveLinks?.map((link) => ({ + ...link, + icon: link.icon ? getIconComponent(link.icon) : undefined, + })); + + // Prepare page data for context - only include serializable data + const pageData = { + toc: page.data.toc, + full: page.data.full, + interactive: page.data.interactive, + title: page.data.title, + description: page.data.description, + interactiveFeatures: page.data.interactiveFeatures, + interactiveLinks, // Use the processed links with React components + }; return ( - - - {page.data.title !== "Home" && ( -

- {page.data.title} -

- )} - {page.data.title !== "Home" && ( -

- {page.data.description} -

- )} - {page.data.title !== "Home" && ( -
+ + {page.data.interactive ? ( + + + + + + +
+ + + + + , + APIPage: (props) => ( + + ), + h1: ({ children, ...props }: HeadingProps) => { + const H1 = + defaultMdxComponents.h1 as React.ComponentType; + const id = + typeof children === "string" ? children : undefined; + return ( +

+ {children} +

+ ); + }, + blockquote: (props) => {props.children}, + code: (props: React.PropsWithChildren) => ( + + ), + hr: (props: React.PropsWithChildren) => ( +
+ ), + input: ( + props: React.InputHTMLAttributes + ) => { + if (props.type === "checkbox") { + return ( +
+ +
+ {props.checked && ( + + )} +
+
+ ); + } + return ; + }, + Mermaid, + })} + /> +
+
+
+ + ) : ( + + + + +
+
+ + {page.data.isRpc && ( + + RPC node + + )} +
+ {page.data.llm !== false && } +
+ + + {/* Render TagFilterSystem if tags are present in frontmatter */} + {page.data.tags && page.data.tags.length > 0 && ( + + )} + +
+ + , + APIPage: (props) => ( + + ), + h1: ({ children, ...props }: HeadingProps) => { + const H1 = + defaultMdxComponents.h1 as React.ComponentType; + const id = + typeof children === "string" ? children : undefined; + return ( +

+ {children} +

+ ); + }, + blockquote: (props) => {props.children}, + code: (props: React.PropsWithChildren) => ( + + ), + hr: (props: React.PropsWithChildren) => ( +
+ ), + input: ( + props: React.InputHTMLAttributes + ) => { + if (props.type === "checkbox") { + return ( +
+ +
+ {props.checked && ( + + )} +
+
+ ); + } + return ; + }, + Mermaid, + })} + /> +
+ + + )} - - {page.data.index ? ( - - ) : ( - - )} - ); } -function Category({ page }: { page: Page }): JSX.Element { - const filtered = utils.files.filter( - (docs) => - docs.type === "page" && - docs.file.dirname === page.file.dirname && - docs.file.name !== "index" - ) as Page[]; - - return ( - - {filtered.map((item) => ( - - ))} - +export async function generateStaticParams() { + return source.generateParams().filter( + (params) => + // Filter out empty slug arrays (root path) + params.slug && params.slug.length > 0 ); } export async function generateMetadata(props: { params: Promise<{ slug?: string[] }>; -}): Promise { +}) { const params = await props.params; - const page = utils.getPage(params.slug); + const page = source.getPage(params.slug); if (!page) notFound(); - const path = `/${params.slug?.join("/") || ""}`; - const routeMetadata = getRouteMetadata(path); - - const pathParts = path.split("/").filter(Boolean); - - const genericTitles = [ - "Overview", - "Installation", - "Quickstart", - "Concepts", - "Getting Started", - ]; - - let title = page.data.title; - - if (page.file.name === "index" || genericTitles.includes(title)) { - let sectionName = - page.file.name === "index" - ? pathParts[pathParts.length - 1] - : pathParts[pathParts.length - 2] || pathParts[pathParts.length - 1]; - - if (sectionName === "api" && pathParts.length >= 2) { - const parentSection = pathParts[pathParts.length - 2]; - if (parentSection === "runes" || parentSection === "ordinals") { - const capitalizedParent = - parentSection.charAt(0).toUpperCase() + parentSection.slice(1); - sectionName = `${capitalizedParent} API`; - } - } - - const sectionTitle = sectionName - .split("-") - .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) - .join(" ") - .replace("Api", "API") - .replace("Js", "JS") - .replace("Sdk", "SDK"); - - if (page.file.name === "index") { - title = `${sectionTitle} Overview`; - } else { - title = `${sectionTitle} ${title}`; - } - } - - const pageMetadata: Partial = { - title, + return { + title: page.data.title, description: page.data.description, }; - - return createMetadata({ - ...routeMetadata, - ...pageMetadata, - }); } diff --git a/app/(docs)/error.tsx b/app/(docs)/error.tsx new file mode 100644 index 000000000..1930ed80b --- /dev/null +++ b/app/(docs)/error.tsx @@ -0,0 +1,59 @@ +"use client"; + +import React from "react"; +import Link from "next/link"; + +export default function Error({ + error, + reset, +}: { + error: Error & { digest?: string }; + reset: () => void; +}) { + React.useEffect(() => { + // Hide sidebar for errors (including 404s) + const aside = document.querySelector("aside"); + if (aside) { + aside.style.display = "none"; + } + + return () => { + const asideCleanup = document.querySelector("aside"); + if (asideCleanup) { + asideCleanup.style.display = ""; + } + }; + }, []); + + // Check if this is likely a 404 error + const is404 = error.message?.includes("404") || error.message?.includes("not found"); + + return ( +
+

+ {is404 ? "Page not found" : "Something went wrong"} +

+

+ {is404 + ? "The documentation you are looking for doesn't exist or has been moved." + : "An error occurred while loading this page."} +

+
+ + Back to homepage + + {!is404 && ( + + )} +
+
+ ); +} \ No newline at end of file diff --git a/app/(docs)/layout.client.tsx b/app/(docs)/layout.client.tsx deleted file mode 100644 index bef178ed4..000000000 --- a/app/(docs)/layout.client.tsx +++ /dev/null @@ -1,110 +0,0 @@ -"use client"; - -import { cva } from "class-variance-authority"; -import Link from "next/link"; -import { useParams, usePathname } from "next/navigation"; -import type { ReactNode } from "react"; -import { cn } from "@/lib/utils"; -import { modes } from "@/utils/modes"; -import { ChevronLeft } from "lucide-react"; - -type Mode = "stacks" | "bitcoin" | null | undefined; - -const itemVariants = cva( - "rounded-md px-2 py-1 transition-colors hover:text-accent-foreground", - { - variants: { - active: { - true: "text-accent-foreground pointer-events-none", - }, - mode: { - bitcoin: "bg-hiro", - stacks: "bg-background", - }, - }, - compoundVariants: [ - { - active: true, - mode: "bitcoin", - className: "bg-hiro dark:text-background", - }, - { - active: true, - mode: "stacks", - className: "bg-inverted text-background", - }, - ], - } -); - -export function Body({ children }: { children: ReactNode }): JSX.Element { - const mode = useMode(); - - return
{children}
; -} - -export function NavChildren(): JSX.Element { - const mode = useMode(); - - const filteredModes = modes.filter((m) => m.param !== "guides"); - - return ( -
- {filteredModes.map((m) => ( - -
- {m.icon && } - {m.name} -
- - ))} -
- ); -} - -export function useMode(): string | undefined { - const { slug } = useParams(); - return Array.isArray(slug) && slug.length > 0 ? slug[0] : undefined; -} - -export function SidebarBanner(): JSX.Element { - const pathname = usePathname(); - const mode = useMode(); - const currentMode = modes.find((item) => item.param === mode) ?? modes[0]; - - if ( - pathname === "/stacks" || - pathname === "/stacks/get-started" || - pathname === "/bitcoin" || - pathname === "/bitcoin/get-started" || - pathname.startsWith("/guides") || - pathname === "/stacks/api-keys" || - pathname === "/stacks/rate-limiting" || - pathname === "/stacks/contributors-guide" || - pathname === "/bitcoin/rate-limiting" || - pathname === "/bitcoin/api-keys" || - pathname === "/bitcoin/contributors-guide" - ) { - return <>; - } - - return ( - -
- -
-

Back

-
-
- - ); -} diff --git a/app/(docs)/layout.tsx b/app/(docs)/layout.tsx index 530830b84..6058b6ff1 100644 --- a/app/(docs)/layout.tsx +++ b/app/(docs)/layout.tsx @@ -1,88 +1,12 @@ -import { DocsLayout, type DocsLayoutProps } from "fumadocs-ui/layout"; +import { DocsLayout } from "@/components/layouts/docs"; import type { ReactNode } from "react"; -import { ArrowUpRight } from "lucide-react"; -import { utils } from "@/utils/source"; -import { DocsLogo } from "@/components/ui/icon"; -import { Body, NavChildren, SidebarBanner } from "./layout.client"; -import { Statuspage } from "statuspage.io"; +import { baseOptions } from "@/app/layout.config"; +import { source } from "@/lib/source"; -const statuspage = new Statuspage("3111l89394q4"); -// console.log({ status: await statuspage.api.getStatus() }); - -export const layoutOptions: Omit = { - tree: utils.pageTree, - nav: { - transparentMode: "top", - title: , - children: , - links: [ - { - label: "Hiro Platform", - href: "https://platform.hiro.so/", - icon: ( -
- Hiro Platform -
- ), - external: true, - }, - ], - }, - links: [ - { - text: "Guides", - url: "/guides", - }, - { - text: "Cookbook", - url: "/cookbook", - }, - ], - sidebar: { - defaultOpenLevel: 0, - banner: , - }, -}; - -export const homeLayoutOptions: Omit = { - tree: utils.pageTree, - nav: { - transparentMode: "top", - title: , - children: null, - links: [ - { - label: "Hiro Platform", - href: "https://platform.hiro.so/", - icon: ( -
- Hiro Platform -
- ), - external: true, - }, - ], - }, - links: [ - { - text: "Guides", - url: "/guides", - }, - { - text: "Cookbook", - url: "/cookbook", - }, - ], -}; - -export default function Layout({ - children, -}: { - children: ReactNode; -}): JSX.Element { +export default function Layout({ children }: { children: ReactNode }) { return ( - - {children} - + + {children} + ); } diff --git a/app/(docs)/not-found.tsx b/app/(docs)/not-found.tsx new file mode 100644 index 000000000..315b86fb6 --- /dev/null +++ b/app/(docs)/not-found.tsx @@ -0,0 +1,28 @@ +import Link from "next/link"; + +export default function DocsNotFound() { + return ( + <> + + + +
+

Token Operations

+ + +
+
+ +
+

NFT Operations

+ + + +
+
+ +
+

Complex Workflows

+ +
+
+ +
+

Message Signing

+ + + + +
+
+ + + + +``` + +## Troubleshooting + +**Post conditions failing** +- Verify exact amounts and addresses in post conditions +- Check wallet compatibility - some wallets don't support post conditions +- Use `PostConditionMode.Allow` for testing, `Deny` for production + +**Token operations not working** +- Confirm contract implements SIP-010 or SIP-009 standards correctly +- Check token contract address and name spelling +- Verify user has sufficient balance for transfers + +**Multi-step workflows failing** +- Add longer delays between steps for slow networks +- Implement transaction status checking before next step +- Handle nonce conflicts with proper sequencing + +**Message signing failures** +- Leather doesn't support non-standard `publicKey` parameter - omit it +- Xverse requires non-standard `publicKey` parameter for simple messages +- Both wallets require hex-encoded Clarity values for structured messages +- Verify message format matches wallet expectations + +**Structured message signing errors** +- Ensure Clarity tuples are properly constructed with `Cl` helpers +- Domain separation requires consistent naming across app versions +- Chain ID must match network: 1 for mainnet, 2147483648 for testnet +- Complex nested structures may not be supported by all wallets + +**Authentication workflow issues** +- Generate unique challenges to prevent replay attacks +- Verify signature on backend before trusting authentication +- Handle wallet connection changes during auth process +- Implement proper session management and timeout handling + +**Wallet compatibility issues** +- Reference the [wallet support table](/docs/building-frontend-applications/wallet-integration#wallet-support) for feature availability +- Implement fallback methods for unsupported features +- Test with multiple wallet types during development +- Handle wallet-specific parameter requirements for message signing \ No newline at end of file diff --git a/content/_hidden/(building-frontend-applications)/meta.json b/content/_hidden/(building-frontend-applications)/meta.json new file mode 100644 index 000000000..8ce4d19bd --- /dev/null +++ b/content/_hidden/(building-frontend-applications)/meta.json @@ -0,0 +1,7 @@ +{ + "title": "building-frontend-applications", + "pages": [ + "wallet-integration", + "interacting-with-smart-contracts" + ] +} \ No newline at end of file diff --git a/content/_hidden/(building-frontend-applications)/wallet-integration.mdx b/content/_hidden/(building-frontend-applications)/wallet-integration.mdx new file mode 100644 index 000000000..d0eda0d79 --- /dev/null +++ b/content/_hidden/(building-frontend-applications)/wallet-integration.mdx @@ -0,0 +1,383 @@ +--- +title: Wallet integration +description: Connect your web app to Stacks wallets and enable users to authenticate, sign transactions, and interact with smart contracts +--- + +Wallet integration transforms your web app from a static interface into a fully interactive blockchain application. Users can authenticate with their Stacks wallets, sign transactions, and interact with smart contracts directly from your app. + +Stacks Connect makes this integration straightforward with a single library that works with all major Stacks wallets including Leather, Xverse, and Asigna. + +## What you'll learn + +You'll learn how to: +- Connect and disconnect Stacks wallets +- Authenticate users and manage connection state +- Read user account information and balances +- Enable contract function calls from your frontend +- Deploy contracts through wallet interactions +- Sign messages for authentication and verification + +## Prerequisites + +Before starting, make sure you have: +- A web application (React, vanilla JS, or any framework) +- Basic knowledge of JavaScript and async/await +- [Node.js and npm](https://nodejs.org/) installed +- A Stacks wallet extension for testing (we recommend [Leather](https://leather.io/)) + +## Step 1: Install Stacks Connect + +Install the latest version of Stacks Connect in your project: + +```bash +npm install @stacks/connect@latest +``` + +> **Note:** This guide uses Stacks Connect v8.x.x which introduces the new `request` method pattern. If you're migrating from v7.x.x, the old `showConnect`, `openContractCall` methods are deprecated in favor of the unified `request` approach. + +Stacks Connect works with any JavaScript framework or vanilla JS applications. + +## Step 2: Set up wallet connection + +Create connection functions using the new `connect`, `disconnect`, and `isConnected` methods: + +```typescript +import { connect, disconnect, isConnected, getLocalStorage } from '@stacks/connect'; + +// Connect wallet function +async function connectWallet() { + try { + const response = await connect({ + forceWalletSelect: true, // Always show wallet selection modal + }); + + console.log('Connected successfully:', response); + updateUserInterface(); + } catch (error) { + console.error('Connection failed:', error); + } +} + +// Check if user is connected +function isUserConnected() { + return isConnected(); +} + +// Disconnect wallet function +function disconnectWallet() { + disconnect(); + updateUserInterface(); +} + +// Get stored user data from local storage +function getUserData() { + if (!isConnected()) return null; + + const data = getLocalStorage(); + return data?.addresses?.stx?.[0]?.address || null; +} +``` + +Add connect/disconnect buttons to your UI: + +```html +
+ + + +
+``` + +## Step 3: Read user account data + +Once connected, access user information and display it: + +```typescript +// Get STX balance +async function getStxBalance(address, network = 'mainnet') { + const baseUrl = network === 'mainnet' + ? 'https://api.hiro.so' + : 'https://api.testnet.hiro.so'; + + try { + const response = await fetch(`${baseUrl}/v2/accounts/${address}?proof=0`); + const data = await response.json(); + + return { + balance: parseInt(data.balance) / 1000000, // Convert to STX + locked: parseInt(data.locked) / 1000000, + nonce: data.nonce, + }; + } catch (error) { + console.error('Failed to fetch balance:', error); + return { balance: 0, locked: 0, nonce: 0 }; + } +} + +// Update UI with user data +async function updateUserInterface() { + const userAddress = getUserData(); + const userInfoDiv = document.getElementById('user-info'); + const connectBtn = document.getElementById('connect-wallet'); + const disconnectBtn = document.getElementById('disconnect-wallet'); + + if (userAddress) { + const balance = await getStxBalance(userAddress); + + userInfoDiv.innerHTML = ` +

Address: ${userAddress}

+

Balance: ${balance.balance} STX

+ `; + userInfoDiv.style.display = 'block'; + connectBtn.style.display = 'none'; + disconnectBtn.style.display = 'block'; + enableWalletFeatures(); + } else { + userInfoDiv.style.display = 'none'; + connectBtn.style.display = 'block'; + disconnectBtn.style.display = 'none'; + disableWalletFeatures(); + } +} +``` + +## Step 4: Make contract calls + +Enable users to interact with smart contracts using the new `request` method: + +```typescript +import { request } from '@stacks/connect'; +import { Cl } from '@stacks/transactions'; + +// Call a contract function +async function callContract() { + try { + const response = await request('stx_callContract', { + contract: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.hello-world', + functionName: 'set-value', + functionArgs: [ + Cl.uint(42), + Cl.stringUtf8('Hello from frontend!') + ], + network: 'testnet', // or 'mainnet' + }); + + console.log('Transaction ID:', response.txid); + alert(`Transaction submitted! ID: ${response.txid}`); + } catch (error) { + console.error('Contract call failed:', error); + alert('Transaction failed: ' + error.message); + } +} +``` + +Add a button to trigger contract calls: + +```html + +``` + +## Step 5: Deploy contracts + +Let users deploy contracts directly from your interface: + +```typescript +// Deploy a contract +async function deployContract() { + const contractCode = ` + ;; A simple counter contract + (define-data-var counter uint u0) + + (define-read-only (get-counter) + (var-get counter)) + + (define-public (increment) + (begin + (var-set counter (+ (var-get counter) u1)) + (ok (var-get counter)))) + `; + + try { + const response = await request('stx_deployContract', { + name: 'my-counter-contract', + clarityCode: contractCode, + clarityVersion: '2', + network: 'testnet', + }); + + console.log('Contract deployed! Transaction ID:', response.txid); + alert(`Contract deployed! Transaction ID: ${response.txid}`); + } catch (error) { + console.error('Contract deployment failed:', error); + alert('Deployment failed: ' + error.message); + } +} +``` + +Add deployment button: + +```html + +``` + +## Step 6: Sign messages + +Implement message signing for authentication and verification: + +```typescript +// Sign a simple message +async function signMessage() { + const message = 'Please sign this message to verify your identity'; + + try { + const response = await request('stx_signMessage', { + message, + }); + + console.log('Message signed:', response.signature); + console.log('Public key:', response.publicKey); + + // Store signature for verification + localStorage.setItem('userSignature', JSON.stringify(response)); + alert('Message signed successfully!'); + } catch (error) { + console.error('Message signing failed:', error); + alert('Signing failed: ' + error.message); + } +} + +// Sign a structured message +async function signStructuredMessage() { + try { + // Create structured message using Clarity values + const clarityMessage = Cl.tuple({ + proposal: Cl.stringAscii('Increase block reward'), + choice: Cl.stringAscii('Yes'), + voter: Cl.stringAscii(getUserData() || ''), + }); + + const clarityDomain = Cl.tuple({ + name: Cl.stringAscii('My dApp'), + version: Cl.stringAscii('1.0.0'), + 'chain-id': Cl.uint(1), + }); + + const response = await request('stx_signStructuredMessage', { + message: clarityMessage, + domain: clarityDomain, + }); + + console.log('Structured message signed:', response); + alert('Structured message signed successfully!'); + } catch (error) { + console.error('Structured message signing failed:', error); + alert('Structured signing failed: ' + error.message); + } +} +``` + +Add signing buttons: + +```html + + +``` + +## Step 7: Persist user session + +Store wallet connection state across browser sessions: + +```typescript +// Check connection status on page load +function initializeApp() { + updateUserInterface(); +} + +// Enable wallet-dependent features +function enableWalletFeatures() { + document.getElementById('contract-call-btn').disabled = false; + document.getElementById('deploy-contract-btn').disabled = false; + document.getElementById('sign-message-btn').disabled = false; + document.getElementById('sign-structured-btn').disabled = false; +} + +// Disable wallet features when disconnected +function disableWalletFeatures() { + document.getElementById('contract-call-btn').disabled = true; + document.getElementById('deploy-contract-btn').disabled = true; + document.getElementById('sign-message-btn').disabled = true; + document.getElementById('sign-structured-btn').disabled = true; +} + +// Store additional user preferences +function storeUserPreferences(preferences) { + localStorage.setItem('userPreferences', JSON.stringify(preferences)); +} + +function getUserPreferences() { + const stored = localStorage.getItem('userPreferences'); + return stored ? JSON.parse(stored) : {}; +} + +// Initialize on page load +document.addEventListener('DOMContentLoaded', initializeApp); +``` + +## Verify it's working + +Test your wallet integration: + +1. **Open your app** in a browser with a Stacks wallet installed +2. **Click "Connect Wallet"** and select your preferred wallet +3. **Verify user info displays** including address and balance +4. **Test contract calls** - transactions should open in the wallet +5. **Try message signing** - wallet should prompt for signature +6. **Refresh the page** - connection should persist + +Connected successfully? Your wallet integration is working! + +## Troubleshooting + +**Wallet not detected** +- Ensure you have a Stacks wallet extension installed +- Try refreshing the page after installing the wallet +- Check browser console for any JavaScript errors + +**Connection popup doesn't appear** +- Check if popup blockers are disabled for your site +- Verify you're using the latest version of `@stacks/connect` +- Make sure you're serving over HTTPS in production + +**Transactions fail** +- Verify contract addresses and function names are correct +- Check that the user has sufficient STX for fees +- Ensure you're using the correct network ('testnet' vs 'mainnet') +- Check that Clarity values are properly constructed with `Cl` helpers + +**User session not persisting** +- Check localStorage is enabled in the browser +- Verify `isConnected()` is called after page load +- Make sure `connect()` completed successfully + +**Balance not updating** +- API calls may be cached - add timestamp parameters +- Check network configuration matches the user's wallet +- Verify the Stacks API endpoints are accessible + +**Migration from older versions** +- Replace `showConnect()` with `connect()` +- Replace `openContractCall()` with `request('stx_callContract', {})` +- Replace `UserSession` usage with `isConnected()` and `getLocalStorage()` +- Update error handling from `onFinish/onCancel` to `try/catch` \ No newline at end of file diff --git a/content/_hidden/(deployment)/configuring-your-deployment-plans.mdx b/content/_hidden/(deployment)/configuring-your-deployment-plans.mdx new file mode 100644 index 000000000..f6cceb8f4 --- /dev/null +++ b/content/_hidden/(deployment)/configuring-your-deployment-plans.mdx @@ -0,0 +1,6 @@ +--- +title: Working with deployment plans +description: Working with deployment plans +--- + +## Working with deployment plans \ No newline at end of file diff --git a/content/_hidden/(deployment)/deploying-your-application.mdx b/content/_hidden/(deployment)/deploying-your-application.mdx new file mode 100644 index 000000000..5fc485e6b --- /dev/null +++ b/content/_hidden/(deployment)/deploying-your-application.mdx @@ -0,0 +1,6 @@ +--- +title: Deploying your application +description: Deploying your application +--- + +## Deploying your application \ No newline at end of file diff --git a/content/_hidden/(deployment)/meta.json b/content/_hidden/(deployment)/meta.json new file mode 100644 index 000000000..8eba5b82d --- /dev/null +++ b/content/_hidden/(deployment)/meta.json @@ -0,0 +1,7 @@ +{ + "title": "deployment", + "pages": [ + "deploying-your-application", + "configuring-your-deployment-plans" + ] +} \ No newline at end of file diff --git a/content/_hidden/(event-streaming)/building-a-simple-indexer.mdx b/content/_hidden/(event-streaming)/building-a-simple-indexer.mdx new file mode 100644 index 000000000..50568eba7 --- /dev/null +++ b/content/_hidden/(event-streaming)/building-a-simple-indexer.mdx @@ -0,0 +1,6 @@ +--- +title: Building an Indexer +description: Building an Indexer +--- + +## Building a simple indexer \ No newline at end of file diff --git a/content/_hidden/(event-streaming)/contract-monitoring.mdx b/content/_hidden/(event-streaming)/contract-monitoring.mdx new file mode 100644 index 000000000..de8868a50 --- /dev/null +++ b/content/_hidden/(event-streaming)/contract-monitoring.mdx @@ -0,0 +1,6 @@ +--- +title: Contract monitoring +description: Contract monitoring +--- + +## Contract monitoring \ No newline at end of file diff --git a/content/_hidden/(event-streaming)/creating-predicates.mdx b/content/_hidden/(event-streaming)/creating-predicates.mdx new file mode 100644 index 000000000..6a83084dd --- /dev/null +++ b/content/_hidden/(event-streaming)/creating-predicates.mdx @@ -0,0 +1,6 @@ +--- +title: Creating Predicates +description: Learn how to create predicates for your Clarinet project. +--- + +# Creating Predicates \ No newline at end of file diff --git a/content/_hidden/(event-streaming)/meta.json b/content/_hidden/(event-streaming)/meta.json new file mode 100644 index 000000000..b8031bb4e --- /dev/null +++ b/content/_hidden/(event-streaming)/meta.json @@ -0,0 +1,9 @@ +{ + "title": "event-driven-architecture", + "pages": [ + "creating-predicates", + "working-with-events-and-transaction-payloads", + "building-a-simple-indexer", + "contract-monitoring" + ] +} \ No newline at end of file diff --git a/content/_hidden/(event-streaming)/working-with-events-and-transaction-payloads.mdx b/content/_hidden/(event-streaming)/working-with-events-and-transaction-payloads.mdx new file mode 100644 index 000000000..fe002a1db --- /dev/null +++ b/content/_hidden/(event-streaming)/working-with-events-and-transaction-payloads.mdx @@ -0,0 +1,6 @@ +--- +title: Creating custom indexers +description: Creating custom indexers +--- + +## Creating custom indexers \ No newline at end of file diff --git a/content/_hidden/(local-development)/building-transactions.mdx b/content/_hidden/(local-development)/building-transactions.mdx new file mode 100644 index 000000000..f0933ab27 --- /dev/null +++ b/content/_hidden/(local-development)/building-transactions.mdx @@ -0,0 +1,434 @@ +--- +title: Building Transactions +description: Create and customize all types of Stacks transactions with precise control over signing, sponsorship, and multi-signature scenarios +--- + +Building transactions programmatically gives you complete control over how your application interacts with the Stacks blockchain. You can create signed transactions for immediate broadcast, unsigned transactions for multi-signature workflows, sponsored transactions to pay fees for users, and complex multi-signature transactions. + +This approach is essential for backends, automated systems, and advanced dApps that need precise transaction control. + +## Feature overview + +Stacks.js provides transaction builders for every blockchain operation: + +**STX transfers**: Send native tokens between accounts with memo support +**Contract deployment**: Deploy Clarity smart contracts with version control +**Contract calls**: Execute functions with proper argument validation and post-conditions +**Sponsored transactions**: Pay transaction fees for other users +**Multi-signature transactions**: Require multiple signatures for enhanced security +**Fee and nonce management**: Automatic estimation or explicit control + +## Required packages + +Install the core transaction building package: + +```bash +npm install @stacks/transactions@latest +``` + +The `@stacks/network` package is optional in v7 - you can use string literals for networks. + +## Building signed transactions + +Signed transactions are ready to broadcast immediately. The private key signs the transaction during creation. + +### STX token transfer + +Send STX tokens between accounts: + +```typescript +import { makeSTXTokenTransfer, broadcastTransaction } from '@stacks/transactions'; + +const transaction = await makeSTXTokenTransfer({ + recipient: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG', + amount: '1000000', // 1 STX in microSTX + senderKey: 'your-private-key-hex', + network: 'testnet', + memo: 'Payment for services', + // nonce and fee are auto-fetched/estimated if not provided +}); + +const result = await broadcastTransaction({ + transaction, + network: 'testnet' +}); + +console.log('Transaction ID:', result.txid); +``` + +### Smart contract deployment + +Deploy Clarity contracts to the blockchain: + +```typescript +import { makeContractDeploy } from '@stacks/transactions'; +import { readFileSync } from 'fs'; + +const contractCode = readFileSync('./my-contract.clar', 'utf8'); + +const transaction = await makeContractDeploy({ + contractName: 'my-awesome-contract', + codeBody: contractCode, + senderKey: 'your-private-key-hex', + network: 'testnet', + clarityVersion: 3, // Defaults to latest if not specified +}); + +const result = await broadcastTransaction({ + transaction, + network: 'testnet' +}); +``` + +### Smart contract function call + +Execute contract functions with arguments and post-conditions: + +```typescript +import { makeContractCall, Cl } from '@stacks/transactions'; + +const transaction = await makeContractCall({ + contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM', + contractName: 'hello-world', + functionName: 'set-value', + functionArgs: [ + Cl.uint(42), + Cl.stringUtf8('Hello Stacks!') + ], + senderKey: 'your-private-key-hex', + network: 'testnet', + validateWithAbi: true, // Validates against contract ABI + postConditions: [], // Add safety conditions +}); +``` + +## Building unsigned transactions + +Unsigned transactions require a separate signing step. Use these for multi-signature workflows or when you want to inspect transactions before signing. + +### Unsigned STX transfer + +```typescript +import { makeUnsignedSTXTokenTransfer } from '@stacks/transactions'; +import { privateKeyToPublicKey } from '@stacks/transactions'; + +const publicKey = privateKeyToPublicKey('your-private-key-hex'); + +const unsignedTx = await makeUnsignedSTXTokenTransfer({ + recipient: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG', + amount: '1000000', + publicKey: publicKey, + network: 'testnet', + memo: 'Unsigned transfer', +}); + +// Sign separately +import { TransactionSigner } from '@stacks/transactions'; + +const signer = new TransactionSigner(unsignedTx); +signer.signOrigin('your-private-key-hex'); + +// Now ready to broadcast +const signedTx = signer.getTxInComplete(); +``` + +### Unsigned contract call + +```typescript +import { makeUnsignedContractCall } from '@stacks/transactions'; + +const unsignedTx = await makeUnsignedContractCall({ + contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM', + contractName: 'my-contract', + functionName: 'my-function', + functionArgs: [Cl.uint(100)], + publicKey: publicKey, + network: 'testnet', +}); + +// Sign with TransactionSigner as shown above +``` + +## Building sponsored transactions + +Sponsored transactions let you pay fees for other users. The origin creates and signs the transaction, then the sponsor adds their signature and fee. + +### Create sponsored transaction (origin side) + +```typescript +import { makeContractCall, Cl } from '@stacks/transactions'; + +// Origin creates transaction with sponsored: true +const sponsoredTx = await makeContractCall({ + contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM', + contractName: 'my-contract', + functionName: 'user-action', + functionArgs: [Cl.standardPrincipal('ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG')], + senderKey: 'origin-private-key', + network: 'testnet', + sponsored: true, // This makes it a sponsored transaction +}); + +// Serialize for the sponsor +const serializedTx = sponsoredTx.serialize(); +``` + +### Complete sponsored transaction (sponsor side) + +```typescript +import { sponsorTransaction, deserializeTransaction } from '@stacks/transactions'; + +// Sponsor receives the serialized transaction +const deserializedTx = deserializeTransaction(serializedTx); + +// Sponsor adds fee and signature +const completedTx = await sponsorTransaction({ + transaction: deserializedTx, + sponsorPrivateKey: 'sponsor-private-key', + fee: '2000', // Sponsor pays the fee + network: 'testnet', +}); + +// Sponsor broadcasts the completed transaction +const result = await broadcastTransaction({ + transaction: completedTx, + network: 'testnet' +}); +``` + +## Building multi-signature transactions + +Multi-sig transactions require multiple signatures. Create unsigned transactions and collect signatures from multiple parties. + +### Create multi-sig transaction + +```typescript +import { + makeUnsignedSTXTokenTransfer, + TransactionSigner, + privateKeyToPublicKey +} from '@stacks/transactions'; + +// Collect public keys from all participants +const privateKeys = [ + 'private-key-1', + 'private-key-2', + 'private-key-3' +]; + +const publicKeys = privateKeys.map(privateKeyToPublicKey); + +// Create unsigned multi-sig transaction +const multiSigTx = await makeUnsignedSTXTokenTransfer({ + recipient: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG', + amount: '5000000', + numSignatures: 2, // Require 2 of 3 signatures + publicKeys: publicKeys, + network: 'testnet', +}); +``` + +### Collect signatures + +```typescript +const signer = new TransactionSigner(multiSigTx); + +// First participant signs +signer.signOrigin(privateKeys[0]); + +// Second participant signs +signer.signOrigin(privateKeys[1]); + +// Add remaining public key (unsigned participant) +signer.appendOrigin(publicKeys[2]); + +// Get completed transaction +const signedMultiSigTx = signer.getTxInComplete(); +``` + +## Configuration options + +### Custom network endpoints + +Connect to custom Stacks nodes: + +```typescript +const transaction = await makeSTXTokenTransfer({ + recipient: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG', + amount: '1000000', + senderKey: 'your-private-key', + network: 'testnet', + client: { baseUrl: 'http://localhost:3999' } // Custom devnet +}); +``` + +### Explicit fee and nonce control + +Override automatic fee estimation and nonce fetching: + +```typescript +const transaction = await makeContractCall({ + contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM', + contractName: 'my-contract', + functionName: 'my-function', + functionArgs: [], + senderKey: 'your-private-key', + network: 'testnet', + nonce: '42', // Explicit nonce + fee: '5000', // Explicit fee in microSTX + anchorMode: 'any' // Transaction timing preference +}); +``` + +### Advanced post-conditions + +Add safety constraints using the new v7 post-condition format: + +```typescript +const stxPostCondition = { + type: 'stx-postcondition', + address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B', + condition: 'gte', + amount: '1000000' +}; + +const ftPostCondition = { + type: 'ft-postcondition', + address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B', + condition: 'eq', + amount: '100', + asset: 'SP3D6PV2ACBPEKYJTCMH7HEN02KP87QSP8KTEH335.my-token::token' +}; + +const transaction = await makeContractCall({ + // ... other options + postConditions: [stxPostCondition, ftPostCondition] +}); +``` + +### Fee estimation + +Get fee estimates before building transactions: + +```typescript +import { fetchFeeEstimate } from '@stacks/transactions'; + +// Estimate for a specific transaction +const feeEstimate = await fetchFeeEstimate({ + transaction, + network: 'testnet' +}); + +// Use the estimate +const newTransaction = await makeSTXTokenTransfer({ + // ... other options + fee: feeEstimate.toString() +}); +``` + +## Working with Clarity values + +Use the `Cl` helper for building type-safe Clarity arguments: + +```typescript +import { Cl } from '@stacks/transactions'; + +const functionArgs = [ + Cl.uint(42), // unsigned integer + Cl.int(-10), // signed integer + Cl.bool(true), // boolean + Cl.stringUtf8('Hello World'), // UTF-8 string + Cl.stringAscii('ASCII only'), // ASCII string + Cl.buffer(new Uint8Array([1, 2, 3])), // buffer + Cl.principal('ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG'), // principal + Cl.contractPrincipal('ST123...', 'my-contract'), // contract principal + Cl.list([Cl.uint(1), Cl.uint(2)]), // list + Cl.tuple({ name: Cl.stringUtf8('Alice') }), // tuple + Cl.some(Cl.uint(42)), // optional (some) + Cl.none(), // optional (none) + Cl.ok(Cl.uint(100)), // response (ok) + Cl.error(Cl.uint(404)) // response (error) +]; +``` + +## Error handling + +Handle broadcast errors properly with the consistent v7 response format: + +```typescript +try { + const result = await broadcastTransaction({ + transaction, + network: 'testnet' + }); + + if (result.error) { + console.error('Transaction rejected:', result.reason); + console.error('Details:', result.reason_data); + } else { + console.log('Success:', result.txid); + } +} catch (error) { + console.error('Network or serialization error:', error); +} +``` + +## Best practices + +### Transaction serialization + +Transactions serialize to hex strings in v7 (not byte arrays): + +```typescript +const transaction = await makeSTXTokenTransfer({ /* options */ }); +const serialized = transaction.serialize(); // hex string +console.log('Serialized tx:', serialized); + +// For bytes (if needed for compatibility) +const bytes = transaction.serializeBytes(); // Uint8Array +``` + +### Nonce management + +For multiple transactions, manage nonces carefully: + +```typescript +import { fetchNonce } from '@stacks/transactions'; + +let currentNonce = await fetchNonce({ + address: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM', + network: 'testnet' +}); + +// Send multiple transactions with incremented nonces +for (const recipient of recipients) { + const transaction = await makeSTXTokenTransfer({ + recipient, + amount: '1000000', + senderKey: privateKey, + network: 'testnet', + nonce: currentNonce.toString() + }); + + await broadcastTransaction({ transaction, network: 'testnet' }); + currentNonce++; +} +``` + +### ABI validation + +Always validate contract calls against ABIs: + +```typescript +const transaction = await makeContractCall({ + contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM', + contractName: 'my-contract', + functionName: 'my-function', + functionArgs: [Cl.uint(42)], + senderKey: privateKey, + network: 'testnet', + validateWithAbi: true // Fetches ABI and validates arguments +}); +``` + +This comprehensive approach to transaction building gives you the flexibility to handle any blockchain interaction scenario while maintaining type safety and proper error handling. \ No newline at end of file diff --git a/content/_hidden/(local-development)/configuring-clarity-vscode-extension.mdx b/content/_hidden/(local-development)/configuring-clarity-vscode-extension.mdx new file mode 100644 index 000000000..afdbe001f --- /dev/null +++ b/content/_hidden/(local-development)/configuring-clarity-vscode-extension.mdx @@ -0,0 +1,182 @@ +--- +title: Configuring Clarity VSCode extension +description: Essential features and setup for the Clarity VS Code extension to streamline smart contract development +--- + +The Clarity VS Code extension transforms your editor into a powerful smart contract development environment. You'll get syntax highlighting, auto-completion, debugging, and real-time error checking—all the tools you need to write safe Clarity code. + +Think of it as your coding copilot. The extension catches errors before you deploy, suggests functions as you type, and shows documentation without leaving your editor. + +> **Need to install the extension?** Check our [Prerequisites guide](/docs/setting-up-your-environment/installing-prerequisites#set-up-vs-code-for-clarity) for installation instructions. + +## Core Features + +### Smart Auto-Completion + +Start typing any Clarity function and get instant suggestions with documentation. The extension adds parentheses and creates placeholders for function arguments. + +```clarity +;; Type "stx-tr" and get: +(stx-transfer? amount sender recipient) +;; ^ ^ ^ +;; Placeholders for easy navigation +``` + +Use `Tab` to jump between placeholders. Use `Escape` to exit placeholder mode. + +### Documentation on Hover + +Hover over any Clarity function or keyword to see its documentation. No need to switch tabs or search external docs. + +```clarity +;; Hover over 'map-set' to see: +;; - Function signature +;; - Parameter descriptions +;; - Return type +;; - Usage examples +(map-set my-map {key: "value"} "data") +``` + +### Go-to Definition + +Jump to function, constant, or variable definitions instantly: + +- `F12` or `Ctrl+Click` to go to definition +- `Alt+F12` to peek definition without leaving current file +- Works across contract files and contract calls + +### Real-Time Error Checking + +The extension validates your code on every save. You'll see: + +- **Red squiggles**: Syntax errors, unknown keywords +- **Yellow squiggles**: Warnings for potentially unsafe code +- **Error list**: All issues in the Problems panel (`Ctrl+Shift+M`) + +Common errors caught: +- Undefined variables or functions +- Type mismatches +- Missing trait implementations +- Invalid function signatures + +### Local Contract Resolution + +Auto-completion works across your entire project. Reference functions from other contracts in your workspace: + +```clarity +;; Auto-complete local contract calls +(contract-call? .my-token transfer amount sender recipient) +;; ^ +;; Suggests contracts in your project +``` + +### Trait Support + +When implementing traits (like SIP-009 NFTs or SIP-010 tokens), the extension verifies: + +- All required functions are implemented +- Function signatures match trait definitions +- Return types are correct + +```clarity +;; Extension warns if missing required trait functions +(impl-trait .sip-010-trait.sip-010-trait) + +;; ⚠️ Warning: Missing required function 'get-balance' +``` + +## Debugging Support + +The extension includes a visual debugger for step-by-step code execution. + +**Requirements:** +- VS Code Desktop (doesn't work in web version) +- [Clarinet installed locally](https://github.com/hirosystems/clarinet#installation) + +**How to debug:** + +1. Set breakpoints by clicking line numbers +2. Press `F5` or use Run → Start Debugging +3. Step through code line-by-line +4. Inspect variables and stack state + +The debugger shows you exactly how Clarity executes your functions, making it easier to understand complex logic and catch bugs. + +## Configuration Options + +### File Associations + +The extension automatically recognizes `.clar` files. For custom extensions: + +```json +// settings.json +{ + "files.associations": { + "*.clarity": "clarity" + } +} +``` + +### Formatting + +Enable format-on-save for consistent code style: + +```json +// settings.json +{ + "editor.formatOnSave": true, + "[clarity]": { + "editor.defaultFormatter": "HiroSystems.clarity-lsp" + } +} +``` + +### Error Checking Frequency + +Adjust how often the extension checks for errors: + +```json +// settings.json +{ + "clarity.checkOnSave": true, + "clarity.checkOnType": false +} +``` + +## Best Practices + +**Organize your workspace** +- Keep all contract files in your Clarinet project root +- Use descriptive filenames that match contract names +- Group related contracts in subdirectories + +**Use the extension's power** +- Hover before assuming—check function documentation +- Let auto-completion guide you to valid function names +- Pay attention to error squiggles; they catch real issues + +**Debugging workflow** +- Start with simple functions before debugging complex ones +- Use breakpoints strategically at decision points +- Check variable values at each step + +**Performance tips** +- Close unused Clarity files to improve responsiveness +- For large projects, consider workspace-specific settings +- Restart the extension (`Ctrl+Shift+P` → "Restart Extension Host") if it becomes slow + +## Troubleshooting + +**Extension not recognizing files?** +- Ensure files have `.clar` extension +- Check if you're in a Clarinet project directory +- Restart VS Code + +**Auto-completion not working?** +- Verify the language server is running (check status bar) +- Try reloading the window (`Ctrl+Shift+P` → "Reload Window") + +**Debugger won't start?** +- Confirm Clarinet is installed: `clarinet --version` +- Make sure you're using VS Code Desktop, not web +- Check that your project has a valid `Clarinet.toml` \ No newline at end of file diff --git a/content/_hidden/(local-development)/creating-a-clarinet-project.mdx b/content/_hidden/(local-development)/creating-a-clarinet-project.mdx new file mode 100644 index 000000000..66225f569 --- /dev/null +++ b/content/_hidden/(local-development)/creating-a-clarinet-project.mdx @@ -0,0 +1,194 @@ +--- +title: Creating a Clarinet project +sidebarTitle: Create a project +description: Step-by-step guide to create your first smart contract project with Clarinet +--- + +Ready to build your first smart contract? Clarinet makes it simple to generate a new project, write Clarity code, and test everything locally. You'll have a working counter contract up and running in minutes. + +Think of Clarinet as your smart contract workshop. It gives you project structure, testing tools, and a local blockchain—everything you need to build confidently before deploying to mainnet. + +## What You'll Learn + +- Generate a new Clarinet project +- Create your first smart contract +- Write basic Clarity functions +- Validate your contract code +- Test contract interactions locally + +## What You'll Need + +- [Clarinet installed](/docs/setting-up-your-environment/installing-prerequisites) +- Basic terminal knowledge +- 10 minutes for the walkthrough + +## Step 1: Generate Your Project + +Create a new Clarinet project called `counter`. This sets up everything you need for smart contract development. + +```terminal +$ clarinet new counter +Creating directory counter +Created file counter/Clarinet.toml +Created file counter/.gitignore +Created directory counter/contracts +Created directory counter/tests +Created file counter/settings/Devnet.toml +Created file counter/settings/Mainnet.toml +Created file counter/settings/Testnet.toml +Created file counter/package.json +Created file counter/tsconfig.json +Created file counter/vitest.config.js +``` + +Navigate into your new project: + +```terminal +$ cd counter +``` + +You now have a complete Clarinet workspace with: +- **contracts/**: Where your Clarity files live +- **tests/**: JavaScript test files +- **settings/**: Network configurations +- **Clarinet.toml**: Project configuration + +## Step 2: Create Your First Contract + +Generate a new smart contract called `counter` inside your project: + +```terminal +$ clarinet contract new counter +Created contracts/counter.clar +``` + +This command: +- Creates the contract file `contracts/counter.clar` +- Updates `Clarinet.toml` with contract configuration +- Sets up the proper folder structure + +Your `Clarinet.toml` now includes: + +```toml +[contracts.counter] +path = 'contracts/counter.clar' +clarity_version = 2 +epoch = 2.5 +``` + +## Step 3: Write Your Smart Contract + +Open `contracts/counter.clar` and add this code: + +```clarity +;; Define a map to store counters for each user +(define-map Counters principal uint) + +;; Public function to increment a user's counter +(define-public (count-up) + (ok (map-set Counters tx-sender (+ (get-count tx-sender) u1))) +) + +;; Read-only function to get a user's current count +(define-read-only (get-count (who principal)) + (default-to u0 (map-get? Counters who)) +) +``` + +**What this contract does:** +- **Counters map**: Stores a number for each user (principal) +- **count-up function**: Increases the caller's count by 1 +- **get-count function**: Returns anyone's current count + +Each user gets their own counter that starts at 0 and increments when they call `count-up`. + +## Step 4: Validate Your Contract + +Check your contract for syntax errors and issues: + +```terminal +$ clarinet check +✅ 1 contract checked, no problems found. +``` + +See the checkmark? Your contract is valid! If you see errors: +- Check for typos in function names +- Make sure parentheses are balanced +- Verify correct Clarity syntax + +Common fixes: +- Missing or extra parentheses +- Incorrect function signatures +- Typos in built-in functions + +## Step 5: Test Your Contract Locally + +Start the Clarinet console to interact with your contract: + +```terminal +$ clarinet console +Welcome to Clarinet console. +Type (help) for available commands. +>> +``` + +**Test the count-up function:** + +```clarity +>> (contract-call? .counter count-up) +(ok true) +``` + +**Check your count:** + +```clarity +>> (contract-call? .counter get-count tx-sender) +u1 +``` + +**Increment again:** + +```clarity +>> (contract-call? .counter count-up) +(ok true) + +>> (contract-call? .counter get-count tx-sender) +u2 +``` + +Perfect! Your counter is working. Each call to `count-up` increases your count by 1. + +Hit `Ctrl+C` twice to leave the console. + +> **Project Structure**: Your Clarinet project includes contracts for your Clarity code, tests for JavaScript unit tests, settings for network configurations, and Clarinet.toml for project configuration. For a complete breakdown of each file and configuration options, see our [Anatomy of a Clarinet Project](/tools/clarinet/anatomy-of-a-clarinet-project) guide. + +## Verification + +Let's confirm everything is working: + +1. **Project created**: `ls` shows all the project files +2. **Contract valid**: `clarinet check` passes with no errors +3. **Contract interactive**: Console commands return expected results +4. **Functions work**: Counter increments correctly + +If any step fails, double-check the contract code and try `clarinet check` again. + +## Troubleshooting + +**"Command not found: clarinet"** +- Make sure [Clarinet is installed](/docs/setting-up-your-environment/installing-prerequisites) +- Restart your terminal after installation + +**"Contract validation failed"** +- Check for syntax errors in your `.clar` file +- Ensure parentheses are balanced +- Look for typos in function names + +**"Console not responding"** +- Exit with `Ctrl+C` and try `clarinet console` again +- Make sure you're in your project directory + +**"Contract call failed"** +- Verify the contract name matches your file (`.counter`) +- Check function names for typos +- Ensure you're using correct Clarity syntax \ No newline at end of file diff --git a/content/_hidden/(local-development)/meta.json b/content/_hidden/(local-development)/meta.json new file mode 100644 index 000000000..a726a82af --- /dev/null +++ b/content/_hidden/(local-development)/meta.json @@ -0,0 +1,10 @@ +{ + "title": "local-development", + "pages": [ + "creating-a-clarinet-project", + "using-clarity-vscode-extension", + "working-with-devnet", + "using-local-accounts", + "building-transactions" + ] +} \ No newline at end of file diff --git a/content/_hidden/(local-development)/using-local-accounts.mdx b/content/_hidden/(local-development)/using-local-accounts.mdx new file mode 100644 index 000000000..28c861f6a --- /dev/null +++ b/content/_hidden/(local-development)/using-local-accounts.mdx @@ -0,0 +1,370 @@ +--- +title: Using Local Accounts +description: Create, manage, and use local Stacks accounts with private keys for development and testing +--- + +Local accounts let you work with Stacks blockchain directly using private keys. This approach is perfect for server-side applications, testing environments, and development workflows where you need full control over account operations. + +You'll use private keys to sign transactions, call contracts, and manage STX tokens without wallet extensions or user interaction. + +## What are local accounts? + +A local account is an account whose signing keys are stored and managed directly in your application code. It performs signing of transactions and messages with a private key **before** broadcasting them to the Stacks network. + +This is different from wallet-connected accounts (like those using Leather or Xverse), where: +- **Local accounts**: Private keys live in your code, signing happens locally +- **Wallet accounts**: Private keys stay in the user's wallet, signing requires user approval + +Local accounts are ideal for: +- **Server-side applications** that need to sign transactions automatically +- **Development and testing** where you want predictable, fast signing +- **Automated scripts** for blockchain interactions +- **Backend services** managing STX transfers or contract calls + +There are two ways to create local accounts in Stacks.js: +- **Private key accounts**: Direct hex private key usage +- **Seed phrase accounts**: Generate from 24-word mnemonic phrases + +## Feature overview + +Working with local accounts involves these core operations: + +**Account creation**: Generate new accounts with private keys and addresses +**Account restoration**: Load existing accounts from private keys or seed phrases +**Balance checking**: Query STX balances and nonces for transaction planning +**Read-only calls**: Execute contract functions without spending STX +**Transaction broadcasting**: Send STX transfers and contract calls to the network + +## Core packages required + +Stacks.js v7 simplifies account management with these packages: + +```bash +npm install @stacks/wallet-sdk @stacks/transactions @stacks/common@latest +``` + +The `@stacks/network` package is optional - you can use string literals like `'testnet'` or `'mainnet'` instead. + +## Creating new accounts + +### Generate a random account + +Create a completely new account with a random private key: + +```typescript +import { generateWallet, randomSeedPhrase, getStxAddress } from '@stacks/wallet-sdk'; + +// Generate new 24-word seed phrase +const seedPhrase = randomSeedPhrase(); + +// Create wallet from seed phrase +const wallet = await generateWallet({ + secretKey: seedPhrase, + password: 'your-secure-password' +}); + +// Access the first account +const account = wallet.accounts[0]; +const privateKey = account.stxPrivateKey; +const address = getStxAddress(account, 'testnet'); + +console.log('Address:', address); +console.log('Private Key:', privateKey); +console.log('Seed Phrase:', seedPhrase); +``` + +### Generate additional accounts + +Add more accounts to an existing wallet: + +```typescript +import { generateNewAccount } from '@stacks/wallet-sdk'; + +// Add second account to wallet +const walletWithTwoAccounts = generateNewAccount(wallet); +const secondAccount = walletWithTwoAccounts.accounts[1]; +const secondAddress = getStxAddress(secondAccount, 'testnet'); +``` + +## Loading existing accounts + +### From private key + +Use an existing private key directly: + +```typescript +import { privateKeyToAddress } from '@stacks/transactions'; + +const privateKey = 'your-64-character-hex-private-key'; +const address = privateKeyToAddress(privateKey, 'testnet'); +``` + +### From seed phrase + +Restore a wallet from a 24-word seed phrase: + +```typescript +import { generateWallet } from '@stacks/wallet-sdk'; + +const existingSeedPhrase = 'abandon ability able about above absent...'; +const restoredWallet = await generateWallet({ + secretKey: existingSeedPhrase, + password: 'your-password' +}); + +const restoredAccount = restoredWallet.accounts[0]; +``` + +## Getting account information + +### Check STX balance + +Query account balance and nonce from the Stacks API: + +```typescript +async function getAccountInfo(address: string, network = 'testnet') { + const baseUrl = network === 'mainnet' + ? 'https://api.hiro.so' + : 'https://api.testnet.hiro.so'; + + const response = await fetch(`${baseUrl}/v2/accounts/${address}?proof=0`); + const data = await response.json(); + + return { + balance: data.balance, + locked: data.locked, + nonce: data.nonce, + unlockHeight: data.unlock_height + }; +} + +// Usage +const accountInfo = await getAccountInfo('ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM'); +console.log(`Balance: ${accountInfo.balance} microSTX`); +console.log(`Next nonce: ${accountInfo.nonce}`); +``` + +### Get account nonce + +Use the built-in function for cleaner nonce fetching: + +```typescript +import { fetchNonce } from '@stacks/transactions'; + +const nonce = await fetchNonce({ + address: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM', + network: 'testnet' +}); +``` + +## Calling read-only functions + +Execute contract functions that don't modify state: + +```typescript +import { fetchCallReadOnlyFunction, Cl } from '@stacks/transactions'; + +const result = await fetchCallReadOnlyFunction({ + contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM', + contractName: 'hello-world', + functionName: 'get-counter', + functionArgs: [], // No arguments needed + network: 'testnet', + senderAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM' +}); + +console.log('Contract result:', result); +``` + +### With function arguments + +Pass Clarity values as function arguments: + +```typescript +const result = await fetchCallReadOnlyFunction({ + contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM', + contractName: 'my-contract', + functionName: 'get-user-balance', + functionArgs: [ + Cl.standardPrincipal('ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG') + ], + network: 'testnet', + senderAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM' +}); +``` + +## Broadcasting transactions + +### STX token transfer + +Send STX tokens between accounts: + +```typescript +import { makeSTXTokenTransfer, broadcastTransaction } from '@stacks/transactions'; + +const transaction = await makeSTXTokenTransfer({ + recipient: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG', + amount: '1000000', // 1 STX in microSTX + senderKey: privateKey, + network: 'testnet', + memo: 'Test transfer', + // nonce and fee are optional - will be fetched/estimated automatically +}); + +const broadcastResponse = await broadcastTransaction({ + transaction, + network: 'testnet' +}); + +console.log('Transaction ID:', broadcastResponse.txid); +``` + +### Contract function call + +Call a contract function that modifies state: + +```typescript +import { makeContractCall, Cl } from '@stacks/transactions'; + +const transaction = await makeContractCall({ + contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM', + contractName: 'hello-world', + functionName: 'increment-counter', + functionArgs: [Cl.uint(5)], + senderKey: privateKey, + network: 'testnet', + validateWithAbi: true // Validates function exists and arguments match +}); + +const broadcastResponse = await broadcastTransaction({ + transaction, + network: 'testnet' +}); +``` + +## Configuration options + +### Custom network endpoints + +Connect to custom Stacks nodes: + +```typescript +const transaction = await makeSTXTokenTransfer({ + recipient: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG', + amount: '1000000', + senderKey: privateKey, + network: 'testnet', + client: { baseUrl: 'http://localhost:3999' } // Custom devnet +}); +``` + +### Transaction options + +Customize transaction behavior: + +```typescript +const transaction = await makeContractCall({ + contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM', + contractName: 'my-contract', + functionName: 'my-function', + functionArgs: [], + senderKey: privateKey, + network: 'testnet', + nonce: 42, // Explicit nonce + fee: '1000', // Explicit fee in microSTX + postConditions: [], // Add safety conditions + anchorMode: 'any' // Transaction timing preference +}); +``` + +### Fee estimation + +Get fee estimates before broadcasting: + +```typescript +import { fetchFeeEstimate } from '@stacks/transactions'; + +const feeEstimate = await fetchFeeEstimate({ + transaction, + network: 'testnet' +}); + +console.log('Estimated fee:', feeEstimate); +``` + +## Best practices + +### Private key security + +Never expose private keys in client-side code or logs: + +```typescript +// ✅ Good - Environment variables +const privateKey = process.env.PRIVATE_KEY; + +// ❌ Bad - Hardcoded keys +const privateKey = 'edf9aee84d9b7abc145504dde6726c64f369d37ee34ded868fabd876c26570bc'; +``` + +### Error handling + +Always handle network and transaction errors: + +```typescript +try { + const transaction = await makeSTXTokenTransfer({ + recipient: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG', + amount: '1000000', + senderKey: privateKey, + network: 'testnet' + }); + + const result = await broadcastTransaction({ transaction, network: 'testnet' }); + + if (result.error) { + console.error('Transaction failed:', result.reason); + } else { + console.log('Success:', result.txid); + } +} catch (error) { + console.error('Network error:', error); +} +``` + +### Nonce management + +For multiple transactions, increment nonces manually: + +```typescript +let currentNonce = await fetchNonce({ address, network: 'testnet' }); + +// Send multiple transactions +for (const recipient of recipients) { + const transaction = await makeSTXTokenTransfer({ + recipient, + amount: '1000000', + senderKey: privateKey, + network: 'testnet', + nonce: currentNonce++ + }); + + await broadcastTransaction({ transaction, network: 'testnet' }); +} +``` + +### Testing on devnet + +Use local devnet for faster development: + +```typescript +// Works with clarinet devnet +const transaction = await makeSTXTokenTransfer({ + recipient: 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5', + amount: '1000000', + senderKey: privateKey, + network: 'devnet', + client: { baseUrl: 'http://localhost:3999' } +}); +``` + +This approach gives you complete control over Stacks accounts for development, testing, and server-side applications. You can sign transactions, interact with contracts, and manage STX tokens without relying on wallet extensions or user interaction. \ No newline at end of file diff --git a/content/_hidden/(local-development)/working-with-devnet.mdx b/content/_hidden/(local-development)/working-with-devnet.mdx new file mode 100644 index 000000000..82e68ddeb --- /dev/null +++ b/content/_hidden/(local-development)/working-with-devnet.mdx @@ -0,0 +1,128 @@ +--- +title: Working with devnet +description: Set up and use Clarinet's local development network for testing smart contracts +--- + +Clarinet's devnet gives you a complete local blockchain environment. You'll run Bitcoin and Stacks nodes, APIs, and explorers right on your machine using Docker containers. + +This lets you test contracts, debug transactions, and develop frontends without spending real money or waiting for network confirmations. + +## What you'll learn + +You'll learn how to: +- [x] Start and configure a local devnet +- [x] Deploy contracts to your local network +- [x] Use devnet accounts for testing +- [x] Monitor transactions and contract calls +- [x] Troubleshoot common devnet issues + +## Prerequisites + +Before starting, make sure you have: +- [Docker Desktop](https://www.docker.com/products/docker-desktop/) installed and running +- A Clarinet project (see [Creating a Clarinet Project](/creating-a-clarinet-project)) +- Basic familiarity with terminal commands + +## Step 1: Start your devnet + +Navigate to your Clarinet project directory and start the devnet: + +```bash +clarinet devnet start +``` + +You'll see Docker containers spinning up. This creates a full blockchain stack: +- Bitcoin node (local bitcoind) +- Stacks node (local stacks-blockchain) +- Stacks API (for querying blockchain data) +- Stacks Explorer (web interface) +- Bitcoin Explorer +- PostgreSQL database + +The command opens an interactive dashboard by default. You can view logs instead with `--no-dashboard`. + +## Step 2: Access your local blockchain + +Once devnet starts, you can access these services: + +- **Stacks Explorer**: http://localhost:8000 - View blocks, transactions, and contracts +- **Bitcoin Explorer**: http://localhost:8001 - Monitor Bitcoin transactions +- **Stacks API**: http://localhost:3999 - Query blockchain data programmatically + +Your contracts from `contracts/` are automatically deployed when devnet starts. + +## Step 3: Use devnet accounts + +Devnet provides pre-funded accounts for testing. You can find account details in: +- The devnet dashboard (default view) +- `settings/Devnet.toml` configuration file + +Each account has: +- STX tokens for transaction fees +- Bitcoin for stacking/mining operations +- Private keys for signing transactions + +## Step 4: Test contract interactions + +With devnet running, you can interact with your contracts through: + +**Clarinet console** (in a new terminal): +```bash +clarinet console +``` + +**Frontend applications** pointing to `http://localhost:3999` + +**Direct API calls**: +```bash +curl http://localhost:3999/v2/info +``` + +## Verify it's working + +Check that devnet is running properly: + +1. **Visit the explorer**: Go to http://localhost:8000 and verify you see recent blocks +2. **Check API health**: Run `curl http://localhost:3999/v2/info` and confirm you get network info +3. **View your contracts**: Look for your deployed contracts in the explorer's contract section + +See recent transactions and your contract deployments? You're good to go. + +## Deploy and try it out + +Your contracts are automatically deployed when devnet starts. To test them: + +1. **Use the console**: Run `clarinet console` and call contract functions +2. **Check deployment status**: View deployments in the explorer or dashboard +3. **Test with a frontend**: Point your dapp to the local API endpoint + +## Troubleshooting + +**Error: clarinet was unable to create network** +- Make sure Docker Desktop is running +- Check that ports 3999, 8000, 8001 aren't in use by other applications + +**Containers won't start** +- Stop any running devnet: `clarinet devnet stop` +- Clear Docker containers: `docker system prune` +- Restart devnet + +**Contracts not deploying** +- Check `Clarinet.toml` for syntax errors +- Verify contract files are in the `contracts/` directory +- Review deployment logs in the dashboard + +## Configuration options + +Customize devnet behavior with these flags: + +- `--manifest-path`: Use a different Clarinet.toml file +- `--deployment-plan-path`: Specify custom deployment plan +- `--no-dashboard`: Show logs instead of interactive dashboard +- `--use-on-disk-deployment-plan`: Use existing deployment plan without updates + +Modify `settings/Devnet.toml` to change: +- Network ports +- Docker images +- Mining configuration +- Epoch settings \ No newline at end of file diff --git a/content/_hidden/(setting-up-your-environment)/installing-prerequisites.mdx b/content/_hidden/(setting-up-your-environment)/installing-prerequisites.mdx new file mode 100644 index 000000000..21bf7c46a --- /dev/null +++ b/content/_hidden/(setting-up-your-environment)/installing-prerequisites.mdx @@ -0,0 +1,116 @@ +--- +title: Installing development tools +sidebarTitle: Prerequisites +description: Set up Clarinet and VS Code for Stacks development. +--- + + +import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'; + +Get your development environment ready with Clarinet and the VS Code extension. These tools provide everything you need to write, test, and deploy smart contracts. + +## Install Clarinet + + + +```terminal !! macOS +$ brew install clarinet +``` + +```terminal !! Windows +$ winget install clarinet +``` + +```terminal !! Cargo +$ sudo apt install build-essential pkg-config libssl-dev +``` + +```terminal !! Binary +$ wget -nv https://github.com/hirosystems/clarinet/releases/download/v0.27.0/clarinet-linux-x64-glibc.tar.gz -O clarinet-linux-x64.tar.gz +$ tar -xf clarinet-linux-x64.tar.gz +$ chmod +x ./clarinet +$ mv ./clarinet /usr/local/bin +``` + + + +Verify installation: + +```terminal +$ clarinet --version +clarinet-cli 2.10.0 +``` + +## Install VS Code extension + +```terminal +$ code --install-extension hirosystems.clarity-lsp +``` + +Or install from VS Code: Extensions panel → Search "Clarity" → Install + +## Configuration options + +| Setting | Command | Description | +|---------|---------|-------------| +| Shell completions | `clarinet completions ` | Enable tab completion for commands | +| Update Clarinet | `brew upgrade clarinet` | Get the latest version (macOS) | +| Extension settings | VS Code Settings → Clarity | Configure formatter, linting | + +## Test your environment + +Verify your setup is working correctly: + +```terminal +$ clarinet new my-test && cd my-test +Created directory my-test +Created file Clarinet.toml + +$ clarinet contract new counter +Created file contracts/counter.clar +Created file tests/counter.test.ts + +$ npm run test +✔ 0 passed | 0 failed +``` + +## Common issues + + + + Command not found + +
+ Check: Is Clarinet in PATH?
+ Fix: Add to PATH or reinstall +
+
+
+ + + VS Code not highlighting + +
+ Check: Extension installed?
+ Fix: Reload window after install +
+
+
+ + + No auto-completion + +
+ Check: In Clarinet project?
+ Fix: Open folder with Clarinet.toml +
+
+
+
+ +For detailed VS Code features, see the [extension guide](/tools/clarinet/vscode-extension). + +## Related guides + +- [Create your first project](/tools/clarinet/quickstart) +- [VS Code extension features](/tools/clarinet/vscode-extension) \ No newline at end of file diff --git a/content/_hidden/(setting-up-your-environment)/meta.json b/content/_hidden/(setting-up-your-environment)/meta.json new file mode 100644 index 000000000..0c28f9123 --- /dev/null +++ b/content/_hidden/(setting-up-your-environment)/meta.json @@ -0,0 +1,7 @@ +{ + "title": "setting-up-your-environment", + "pages": [ + "installing-prerequisites", + "setting-up-a-web-wallet" + ] +} \ No newline at end of file diff --git a/content/_hidden/(setting-up-your-environment)/setting-up-a-web-wallet.mdx b/content/_hidden/(setting-up-your-environment)/setting-up-a-web-wallet.mdx new file mode 100644 index 000000000..e9811c40b --- /dev/null +++ b/content/_hidden/(setting-up-your-environment)/setting-up-a-web-wallet.mdx @@ -0,0 +1,98 @@ +--- +title: Setting up a web wallet +sidebarTitle: Wallet installation +description: Quick setup guide for Leather wallet and devnet configuration for local development +--- + +You need a Bitcoin and Stacks wallet to interact with smart contracts during development. Leather is the most popular choice for developers—it supports both Bitcoin and Stacks, works with all major browsers, and makes switching between networks simple. + +This guide gets you set up with Leather and configured for local development in under 5 minutes. + +## What You'll Learn + +- Install Leather browser extension +- Create or restore a wallet +- Add devnet network for local development +- Alternative wallet options + +## What You'll Need + +- Chrome, Brave, Edge, or Opera browser +- 5 minutes for setup + +## Step 1: Install Leather + +**For Chrome, Brave, Edge, or Opera:** + +1. Visit the [Chrome Web Store Leather page](https://chrome.google.com/webstore/detail/leather/ldinpeekobnhjjdofggfgjlcehhmanlj) +2. Click "Add to Chrome" (or "Get" depending on your browser) +3. Allow the extension when prompted + +The extension icon appears in your browser toolbar. Click it to open Leather. + +**Alternative installation:** +You can also [install from source](https://leather.io/guides/install-leather) for developer builds or testing. + +## Step 2: Create Your Wallet + +**For new users:** + +1. Click "Create new wallet" +2. Write down your 12-word secret recovery phrase offline +3. Confirm your phrase by selecting words in order +4. Set a password for the wallet + +**For existing users:** +Click "Restore wallet" and enter your existing seed phrase. + +Your secret recovery phrase is the only way to restore your wallet. Store it securely offline—preferably written down or engraved on metal. + +## Step 3: Add Devnet Network + +This is the key step for local development. Devnet lets you test with Clarinet's local blockchain. + +1. Click the overflow menu (3 dots) at top-right of Leather +2. Select "Change network" +3. Click "Add network" +4. Enter these devnet details: + +``` +Name: Devnet +Stacks API URL: http://localhost:3999 +Bitcoin API URL: http://localhost:18443/wallet/{wallet_id} +``` + +5. Click "Add network" +6. Select "Devnet" from the network dropdown + +You're now connected to your local development environment. When you start Clarinet devnet, Leather will interact with your local blockchain. + +## Step 4: Verify Setup + +Test your setup: + +1. Switch to Devnet network in Leather +2. You should see "Devnet" in the top-left corner +3. Your STX balance will show 0 (normal—you'll get test tokens later) + +If you see any connection errors, make sure you've started `clarinet devnet` before switching to the devnet network. + +## Alternative Wallets + +**Xverse**: Another popular Bitcoin/Stacks wallet with mobile support. Follow their [complete setup guide](https://www.xverse.app/blog/how-to-set-up-an-xverse-wallet) if you prefer Xverse over Leather. + +**For production apps**: Support multiple wallets to give users choice. Both Leather and Xverse work with the same Stacks.js integration code. + +## Troubleshooting + +**Extension not appearing?** +- Check if it's hidden in your browser's extensions menu +- Pin it to your toolbar for easy access + +**Can't add devnet network?** +- Double-check the URLs exactly as shown above +- Make sure you're using `http://` not `https://` + +**Connection errors on devnet?** +- Start Clarinet devnet first: `clarinet devnet` +- Wait for all of the services to be running before verifying the setup \ No newline at end of file diff --git a/content/_hidden/(testing-your-contracts)/cost-analysis-and-debugging.mdx b/content/_hidden/(testing-your-contracts)/cost-analysis-and-debugging.mdx new file mode 100644 index 000000000..a7bba2b6d --- /dev/null +++ b/content/_hidden/(testing-your-contracts)/cost-analysis-and-debugging.mdx @@ -0,0 +1,6 @@ +--- +title: Cost analysis and debugging +description: Cost analysis and debugging +--- + +## Cost analysis and debugging \ No newline at end of file diff --git a/content/_hidden/(testing-your-contracts)/integration-testing.mdx b/content/_hidden/(testing-your-contracts)/integration-testing.mdx new file mode 100644 index 000000000..bc5d75302 --- /dev/null +++ b/content/_hidden/(testing-your-contracts)/integration-testing.mdx @@ -0,0 +1,219 @@ +--- +title: Integration testing +description: Learn how to write and run integration tests for your Clarity smart contracts using the Clarinet JS SDK and Vitest. +--- + +Integration testing is a crucial step in smart contract development that involves testing how different components of your system work together. The Clarinet JS SDK provides powerful tools for writing and running integration tests, allowing you to simulate complex scenarios and interactions between multiple contracts. + +By using integration tests, you can ensure that your smart contracts function correctly as part of a larger system and catch potential issues that might not be apparent in unit tests alone. + +In this guide, you will: + +1. [Set up a Clarinet project with a `defi` contract.](#set-up-a-clarinet-project) +2. [Write an integration test for the smart contract.](#test-the-deposit-and-borrow-functionality) +3. [Run tests and generate coverage reports.](#run-tests-and-generate-coverage-reports) + +--- + +## Set up a Clarinet project + +Start by creating a new Clarinet project. This command will create a new directory named `defi` and set up a basic Clarinet project inside it. + +```terminal +$ clarinet new stx-defi +$ cd stx-defi +``` + +After changing into your project directory, run `npm install` to install the package dependencies for testing. + +```terminal +$ npm install +``` + +We are going to use the same `defi` contract that we used in the [unit testing guide](/tools/clarinet/unit-testing), but with some additional functionality - the ability to `borrow` STX from the contract. If you don't have this project set up already, follow the steps below: + +```terminal +$ clarinet contract new defi +``` + +Then, inside your `defi.clar` file, copy and paste the following contract code: + +```clarity +;; Error constants for various failure scenarios. +(define-constant err-overborrow (err u300)) + +;; The interest rate for loans, represented as 10% (out of a base of 100). +(define-data-var loan-interest-rate uint u10) ;; Representing 10% interest rate + + +;; Holds the total amount of deposits in the contract, initialized to 0. +(define-data-var total-deposits uint u0) + +;; Maps a user's principal address to their deposited amount. +(define-map deposits { owner: principal } { amount: uint }) + +;; Maps a borrower's principal address to their loan details: amount and the last interaction block. +(define-map loans principal { amount: uint, last-interaction-block: uint }) + +;; Public function for users to deposit STX into the contract. +;; Updates their balance and the total deposits in the contract. +(define-public (deposit (amount uint)) + (let + ( + ;; Fetch the current balance or default to 0 if none exists. + (current-balance (default-to u0 (get amount (map-get? deposits { owner: tx-sender })))) + ) + ;; Transfer the STX from sender = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM" to recipient = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.defi (ie: contract identifier on the chain!)". + (try! (stx-transfer? amount tx-sender (as-contract tx-sender))) + ;; Update the user's deposit amount in the map. + (map-set deposits { owner: tx-sender } { amount: (+ current-balance amount) }) + ;; Update the total deposits variable. + (var-set total-deposits (+ (var-get total-deposits) amount)) + ;; Return success. + (ok true) + ) +) + +;; Public function for users to borrow STX based on their deposits. +(define-public (borrow (amount uint)) + (let + ( + ;; Fetch user's deposit or default to 0. + (user-deposit (default-to u0 (get amount (map-get? deposits { owner: tx-sender })))) + ;; Calculate the maximum amount the user is allowed to borrow. (which will be upto HALF of what they deposited) + (allowed-borrow (/ user-deposit u2)) + ;; Fetch current loan details or default to initial values. + (current-loan-details (default-to { amount: u0, last-interaction-block: u0 } (map-get? loans tx-sender ))) + ;; Calculate accrued interest on the current loan. + (accrued-interest (calculate-accrued-interest (get amount current-loan-details) (get last-interaction-block current-loan-details))) + ;; Calculate the total amount due including interest. + (total-due (+ (get amount current-loan-details) (unwrap-panic accrued-interest))) + ;; Calculate the new loan total after borrowing additional amount. + (new-loan (+ amount)) + ) + ;; Ensure the requested borrow amount does not exceed the allowed amount. + (asserts! (<= new-loan allowed-borrow) err-overborrow) + ;; Transfer the borrowed STX to the user. + (let + ( + (recipient tx-sender) + ) + (try! (as-contract (stx-transfer? amount tx-sender recipient))) + ) + ;; Update the user's loan details in the map. + (map-set loans tx-sender { amount: new-loan, last-interaction-block: block-height }) + ;; Return success. + (ok true) + ) +) + +;; Read-only function to get the total balance by tx-sender +(define-read-only (get-balance-by-sender) + (ok (map-get? deposits { owner: tx-sender })) +) + +;; Read-only function to get the total amount owed by the user. +(define-read-only (get-amount-owed) + (let + ( + ;; Fetch current loan details or default to initial values. + (current-loan-details (default-to { amount: u0, last-interaction-block: u0 } (map-get? loans tx-sender ))) + ;; Calculate accrued interest on the current loan. + (accrued-interest (calculate-accrued-interest (get amount current-loan-details) (get last-interaction-block current-loan-details))) + ;; Calculate the total amount due including interest. + (total-due (+ (get amount current-loan-details) (unwrap-panic accrued-interest))) + ) + ;; Return the total amount due. + (ok total-due) + ) +) + +;; Private function to calculate the accrued interest on a loan. +(define-private (calculate-accrued-interest (principal uint) (start-block uint)) + (let + ( + ;; Calculate the number of blocks elapsed since the last interaction. + (elapsed-blocks (- block-height start-block)) + ;; Calculate the interest based on the principal, rate, and elapsed time. + (interest (/ (* principal (var-get loan-interest-rate) elapsed-blocks) u10000)) + ) + ;; Ensure the loan started in the past (not at block 0). + (asserts! (not (is-eq start-block u0)) (ok u0)) + ;; Return the calculated interest. + (ok interest) + ) +) +``` + +Run `clarinet check` to ensure that your smart contract is valid and ready for testing. + + +You can find the full code for this project in [this repo](https://github.com/hirosystems/clarity-examples/tree/main/examples/stx-defi). + + +## Test the deposit and borrow functionality + +In order to `borrow` STX from the contract, users must first `deposit` STX into it. Therefore, we need to write an integration test that simulates the interaction between these two functions. + +Inside of your `defi.test.ts` file, replace the boilerplate code and add the following: + +```typescript +import { describe, it, expect } from 'vitest'; +import { Cl } from '@stacks/transactions'; + +const accounts = simnet.getAccounts(); +const wallet1 = accounts.get('wallet_1')!; + +describe('stx-defi', () => { + it('borrows 10 and verifies the amount owed to be 10', () => { + simnet.callPublicFn('defi', 'deposit', [Cl.uint(1000)], wallet1); + const totalDeposits = simnet.getDataVar('defi', 'total-deposits'); + expect(totalDeposits).toBeUint(1000); + + simnet.callPublicFn('defi', 'borrow', [Cl.uint(10)], wallet1); + const { result } = simnet.callReadOnlyFn('defi', 'get-amount-owed', [], wallet1); + expect(result).toBeOk(Cl.uint(10)); + }); +}); +``` + +In this integration test, we're simulating a scenario where a user deposits STX into the DeFi contract and then borrows against that deposit. Let's walk through the process step by step. + +We start by simulating a deposit of 1000 STX from `wallet1`. To do this, we use the `callPublicFn` method from the Clarinet JS SDK `simnet` object, which allows us to call public functions in our smart contract just as we would on the actual blockchain. + +After making the deposit, we want to verify that it was successful. We do this by checking the total deposits in the contract using `getDataVar`. + +This handy method lets us peek at the value of data variables defined in your contract. + + +To learn more about available methods for integration testing, check out the [reference page](/tools/clarinet/sdk-reference). + + +To ensure the deposit was recorded correctly, we use a custom matcher, `toBeUint`. This matcher is specifically designed to check if a value is a Clarity unsigned integer with the exact value we expect. + +With the deposit confirmed, we simulate `wallet1` borrowing 10 STX. We do this with another call to `callPublicFn`, this time invoking the `borrow` function of our contract. + +After the borrowing operation, we want to check how much `wallet1` owes. We use `callReadOnlyFn` to call a read-only function named `get-amount-owed` in our contract. + +Finally, we verify the amount owed using another custom matcher, `toBeOk(Cl.uint(10))`. This matcher is particularly useful because it checks two things at once: + +1. That our contract returned a successful Clarity response type. +2. That the value returned is a Clarity unsigned integer with the exact value we expect (`10`). + +These custom matchers and simnet methods are powerful tools and allow you to simulate complex interactions with your smart contracts and make detailed assertions about the results. + +## Run tests and generate coverage reports + +To run your tests, use: + +```terminal +$ npm run test +``` + +To generate a coverage report, use: + +```terminal +$ npm run coverage +``` + +This will run your tests and produce a detailed coverage report, helping you identify any untested parts of your contract. \ No newline at end of file diff --git a/content/_hidden/(testing-your-contracts)/meta.json b/content/_hidden/(testing-your-contracts)/meta.json new file mode 100644 index 000000000..69bdb02e0 --- /dev/null +++ b/content/_hidden/(testing-your-contracts)/meta.json @@ -0,0 +1,8 @@ +{ + "title": "testing-your-contracts", + "pages": [ + "unit-testing", + "integration-testing", + "cost-analysis-and-debugging" + ] +} \ No newline at end of file diff --git a/content/_hidden/(testing-your-contracts)/unit-testing.mdx b/content/_hidden/(testing-your-contracts)/unit-testing.mdx new file mode 100644 index 000000000..af4b18525 --- /dev/null +++ b/content/_hidden/(testing-your-contracts)/unit-testing.mdx @@ -0,0 +1,211 @@ +--- +title: Unit testing with Clarinet JS SDK +description: Learn how to write and run unit tests for your Clarity smart contracts using the Clarinet JS SDK and Vitest. +--- + +import { Accordions, Accordion } from 'fumadocs-ui/components/accordion'; + +Unit testing is the process of testing individual components or functions of smart contracts to ensure they work as expected. The Clarinet JS SDK provides a testing framework that allows you to write these tests using the Vitest testing framework, helping you catch bugs and errors early in the development process. + +In this guide, you will: + +1. [Set up a new Clarinet project with a `defi` contract](#set-up-a-new-clarinet-project). +2. [Write a unit test covering the `deposit` function](#test-the-deposit-function). +3. [Run tests and generate coverage reports](#run-tests-and-generate-coverage-reports). + +--- + +## Set up a new Clarinet project + +Start by creating a new project with the Clarinet CLI. The command below will create a project structure inside of `defi` with the necessary files and folders, including the Clarinet JS SDK already set up for testing. + +```terminal +$ clarinet new stx-defi +$ cd stx-defi +``` + +After changing into your project directory, run `npm install` to install the package dependencies for testing. + +```terminal +$ npm install +``` + +Since the smart contract code is out of scope for this guide, we are going to use a pre-existing contract. First, generate a new file using the `clarinet contract new` command in order to set up your project with the necessary configuration and test files. + +```terminal +$ clarinet contract new defi +``` + +Now, inside your `defi.clar` file, copy and paste the following contract code: + +```clarity +;; Holds the total amount of deposits in the contract, initialized to 0. +(define-data-var total-deposits uint u0) + +;; Maps a user's principal address to their deposited amount. +(define-map deposits { owner: principal } { amount: uint }) + +;; Public function for users to deposit STX into the contract. +;; Updates their balance and the total deposits in the contract. +(define-public (deposit (amount uint)) + (let + ( + ;; Fetch the current balance or default to 0 if none exists. + (current-balance (default-to u0 (get amount (map-get? deposits { owner: tx-sender })))) + ) + ;; Transfer the STX from sender = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM" to recipient = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.defi (ie: contract identifier on the chain!)". + (try! (stx-transfer? amount tx-sender (as-contract tx-sender))) + ;; Update the user's deposit amount in the map. + (map-set deposits { owner: tx-sender } { amount: (+ current-balance amount) }) + ;; Update the total deposits variable. + (var-set total-deposits (+ (var-get total-deposits) amount)) + ;; Return success. + (ok true) + ) +) + +;; Read-only function to get the total balance by tx-sender +(define-read-only (get-balance-by-sender) + (ok (map-get? deposits { owner: tx-sender })) +) +``` + +Run `clarinet check` to ensure that your smart contract is valid and ready for testing. + + +You can find the full code for this project in [this repo](https://github.com/hirosystems/clarity-examples/tree/main/examples/stx-defi). + + +## Test the deposit function + +This `deposit` function allows users to deposit STX into the contract, updating their balance inside a `deposits` map and adding to the total deposits stored in a `total-deposits` variable. The key tests we want to cover are that the deposit is successful and that the user's balance, as well as the contract's total deposits, are updated correctly. + +Inside of your `defi.test.ts` file, replace the boilerplate code and add the following: + +```typescript +import { describe, it, expect } from 'vitest'; +import { Cl } from '@stacks/transactions'; + +const accounts = simnet.getAccounts(); +const wallet1 = accounts.get('wallet_1')!; +``` + +These imports provide the testing framework and utilities we need. We also get the `wallet_1` account, which will act as our test user. + +Next, define the test suite and the specific test case: + +```typescript +describe('stx-defi', () => { + it('allows users to deposit STX', () => { + // Test code will go here + }); +}); +``` + +This structure comes from our Vitest integration, and it organizes our tests and describes what we're testing. The `describe` block groups multiple test cases together, while the `it` block represents a single test case. + +Now, let's simulate a deposit. Inside of the `it` block, define the amount to deposit and call the `deposit` function: + +```typescript +const amount = 1000; +const deposit = simnet.callPublicFn('defi', 'deposit', [Cl.uint(amount)], wallet1); +``` + +This code simulates a deposit by calling the `deposit` function, using the `callPublicFn` method from the Clarinet JS SDK, in our contract with a specified amount, just as a user would in the real world. + +After making the deposit, create an assertion to verify that the call itself was successful and returns an `ok` response type with the value `true`: + +```typescript +expect(deposit.result).toBeOk(Cl.bool(true)); +``` + +Run `npm run test` to confirm that this test passes. + +Let's go over some of the code in this assertion: + +- `expect` is a function from Vitest that makes an assertion about the value we expect to get back from the `deposit` function. + +But how do we test against Clarity types and values? This is where the `Cl` and `toBeOk` helpers come in. + +- `toBeOk` is a custom matcher function built into Vitest that checks if the result of the deposit call is an `Ok` response, which is a Clarity type. This is important because it confirms that the deposit transaction was processed successfully. +- `Cl` helper is from the `@stacks/transactions` package and is used to create Clarity values in JavaScript. In this case, it's used to create a Clarity boolean with the value of `true`. + + +To see more custom matcher examples, check out the [reference page](/tools/clarinet/sdk-reference). + + +Once we can confirm that the deposit was successful, write a test to verify that the contract's total deposits have been updated correctly. + +```typescript +const totalDeposits = simnet.getDataVar('defi', 'total-deposits'); +expect(totalDeposits).toBeUint(amount); +``` + +Run `npm run test` again to confirm that this test also passes. + +This check ensures that the contract accepted our deposit without any issues. + +Lastly, verify that the user's balance has been updated correctly: + +```typescript +const balance = simnet.callReadOnlyFn('defi', 'get-balance-by-sender', [], wallet1); +expect(balance.result).toBeOk( + Cl.some( + Cl.tuple({ + amount: Cl.uint(amount), + }) + ) +); +``` + +We call the `get-balance-by-sender` function and check if it matches the amount we just deposited. + +By following these steps, our test comprehensively verifies that the `deposit` function works as intended, updating individual balances and total deposits accurately. + + + +```typescript + import { describe, it, expect } from 'vitest'; + import { Cl } from '@stacks/transactions'; + + const accounts = simnet.getAccounts(); + const wallet1 = accounts.get('wallet_1')!; + + describe('stx-defi', () => { + it('allows users to deposit STX', () => { + const amount = 1000; + const deposit = simnet.callPublicFn('defi', 'deposit', [Cl.uint(amount)], wallet1); + expect(deposit.result).toBeOk(Cl.bool(true)); + + const totalDeposits = simnet.getDataVar('defi', 'total-deposits'); + expect(totalDeposits).toBeUint(amount); + + const balance = simnet.callReadOnlyFn('defi', 'get-balance-by-sender', [], wallet1); + expect(balance.result).toBeOk( + Cl.some( + Cl.tuple({ + amount: Cl.uint(amount), + }) + ) + ); + }); + }); +``` + + + +## Run tests and generate coverage reports + +To run your tests, use: + +```terminal +$ npm run test +``` + +To generate a coverage report, use: + +```terminal +$ npm run coverage +``` + +This will run your tests and produce a detailed coverage report, helping you identify any untested parts of your contract. \ No newline at end of file diff --git a/content/_hidden/(working-with-hiro-apis)/api-fundamentals.mdx b/content/_hidden/(working-with-hiro-apis)/api-fundamentals.mdx new file mode 100644 index 000000000..6cca08d2c --- /dev/null +++ b/content/_hidden/(working-with-hiro-apis)/api-fundamentals.mdx @@ -0,0 +1,6 @@ +--- +title: API fundamentals +description: API fundamentals +--- + +## API fundamentals \ No newline at end of file diff --git a/content/_hidden/(working-with-hiro-apis)/backend-integration-patterns.mdx b/content/_hidden/(working-with-hiro-apis)/backend-integration-patterns.mdx new file mode 100644 index 000000000..7f8f285b7 --- /dev/null +++ b/content/_hidden/(working-with-hiro-apis)/backend-integration-patterns.mdx @@ -0,0 +1,6 @@ +--- +title: Backend integration patterns +description: Backend integration patterns +--- + +## Backend integration patterns \ No newline at end of file diff --git a/content/_hidden/(working-with-hiro-apis)/meta.json b/content/_hidden/(working-with-hiro-apis)/meta.json new file mode 100644 index 000000000..6713b40d3 --- /dev/null +++ b/content/_hidden/(working-with-hiro-apis)/meta.json @@ -0,0 +1,7 @@ +{ + "title": "working-with-hiro-apis", + "pages": [ + "api-fundamentals", + "backend-integration-patterns" + ] +} \ No newline at end of file diff --git a/content/docs/guides/docskit.mdx b/content/_hidden/docskit.mdx similarity index 100% rename from content/docs/guides/docskit.mdx rename to content/_hidden/docskit.mdx diff --git a/content/_hidden/features.mdx b/content/_hidden/features.mdx new file mode 100644 index 000000000..0a13ebb57 --- /dev/null +++ b/content/_hidden/features.mdx @@ -0,0 +1,149 @@ +--- +title: Introduction to Hiro tools +sidebarTitle: Introduction to Hiro tools +description: Learn more about our tools and how to use them together. +isNew: true +--- + + + +## Overview + +Core tools for building and testing smart contracts: + +- [**Clarinet**](/tools/clarinet) - Local blockchain development environment +- [**Clarinet JS SDK**](/tools/clarinet/sdk-introduction) - JavaScript testing framework +- [**Stacks.js**](/reference/stacks.js) - Frontend integration library +- [**Chainhook**](/tools/chainhook) - Event-driven blockchain applications + +## API services + +Query blockchain data without running infrastructure: + +- [**Stacks Blockchain API**](/apis/stacks-blockchain-api) - RESTful blockchain queries +- [**Token Metadata API**](/apis/token-metadata-api) - NFT and token metadata +- [**Ordinals API**](/apis/ordinals-api) - Bitcoin inscriptions data +- [**Runes API**](/apis/runes-api) - Bitcoin fungible tokens + +## Platform services + +Cloud-based tools for teams and production: + +- [**Hiro Platform**](https://platform.hiro.so) - Cloud development environment +- [**Contract Monitoring**](/tools/contract-monitoring) - Real-time alerts and metrics +- **Hosted Devnets** - Isolated test environments + +## Integrations + +How our tools connect and complement each other: + +| Tool | Integrates With | How They Work Together | +|------------|-----------------|-----------------------------------------------| +| Clarinet | Stacks.js | Deploy contracts locally, connect frontend | +| Clarinet | Chainhook | Test event handling in development | +| Stacks.js | Stacks API | Submit transactions, query results | + +## Development workflows + +### Smart contract DApp + +Building user-facing applications with smart contracts: + +```terminal +$ clarinet new my-project && cd my-project +$ clarinet contract new token +$ clarinet test + +$ clarinet devnet start +$ clarinet deployments apply --devnet +``` + +```typescript +import { request } from '@stacks/connect'; + +const response = await request('stx_callContract', { + contract: 'SP2MF04VAGYHGAZWGTEDW5VYCPDWWSY08Z1QFNDSN.counters', + functionName: 'count', + functionArgs: [Cl.int(3)], + network: 'mainnet', +}); + +const balance = await fetch( + 'https://api.hiro.so/v2/accounts/ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM' +); +``` + +**Tool flow**: Clarinet → Stacks.js → Stacks API + +### Event-driven backend + +React to blockchain events in real-time: + +```json +// 1. Create Chainhook predicate +{ + "chain": "stacks", + "uuid": "my-hook", + "networks": { + "mainnet": { + "if_this": { + "scope": "contract_call", + "method": "transfer" + }, + "then_that": { + "http_post": { + "url": "https://my-api.com/webhook" + } + } + } + } +} +``` + +```javascript +// 2. Handle webhook in your backend +app.post('/webhook', (req, res) => { + const { apply } = req.body; + const transactions = apply[0].transactions; + // Process event, update database + db.save(transactions); +}); +``` + +**Tool flow**: Chainhook → Your backend + +### Bitcoin applications + +Build on Bitcoin L1 protocols: + +```bash +# 1. Query existing data +curl https://api.hiro.so/ordinals/v1/inscriptions + +# 2. Or create custom indexes +bitcoin-indexer --config my-protocol.json +``` + +```typescript +// 3. Display in frontend +const inscriptions = await fetch( + 'https://api.hiro.so/ordinals/v1/inscriptions' +); +``` + +**Tool flow**: Ordinals / Runes APIs / Bitcoin Indexer → Your backend + +## Decision matrix + +| If You're Building | Use These Tools | Why | +|------------------------|------------------------------------------|-----------------------------------| +| Smart contract app | Clarinet + Stacks.js + API | Complete dev-to-production flow | +| NFT marketplace | Clarinet + Stacks.js + API + Token Metadata API | Automatic metadata handling | +| Bitcoin explorer | Ordinals/Runes APIs | Pre-indexed Bitcoin data | +| Analytics dashboard | APIs + Chainhook | Historical + real-time data | +| Custom protocol | Chainhook + Bitcoin Indexer | Build your own indexes | + +:::next-steps +- [Install Clarinet](/tools/clarinet/getting-started/installing-clarinet): Learn how to install Clarinet. +- [Explore API references](/apis): Explore our API references. +::: \ No newline at end of file diff --git a/content/_hidden/recommended-resources.mdx b/content/_hidden/recommended-resources.mdx new file mode 100644 index 000000000..faa4bcd63 --- /dev/null +++ b/content/_hidden/recommended-resources.mdx @@ -0,0 +1,112 @@ +--- +title: Recommended resources +description: Here's a list of recommended content to further expand your knowledge in this amazing tool. +full: true +--- + +import { Card as MainCard, SecondaryCard, SmallCard } from '@/components/card'; +import { PageFooter } from '@/components/footer'; +import { Book, Play, Lightbulb, FileText, Key, Send, Webhook, Timer, ExternalLink } from 'lucide-react'; + +## Guides + + +} + tag="Guide" + description="Learn how to integrate, build, and extend functionality with practical, developer-focused guidance." +/> +} + tag="Quickstart" + description="Get started fast with the basics you need to set up and run your first project." +/> +} + tag="Concepts" + description="Understand the core ideas, principles, and mental models behind the system." +/> +} + tag="Tutorial" + description="A hands-on walkthrough to help you accomplish a specific task from start to finish." +/> + + +## Snippets/Recipes + + +} + tag="Authentication" + description="Learn how to securely authenticate API requests using access tokens." +/> +} + tag="Transactions" + description="Step-by-step guide to submit transactions using REST API endpoints." +/> +} + tag="Events" + description="Set up webhooks to listen for and respond to blockchain events in real-time." +/> +} + tag="Best Practices" + description="Implement proper rate limiting and retry logic in your applications." +/> + + +## Project templates + +To learn more about these concepts, check out these resources: + +- [Deep dive on Concept #1 ](https://example.com/concept-1) +- [Video tutorial on Concept #2 ](https://example.com/concept-2) +- [Clarity reference for functions ](https://example.com/clarity-reference) +- [Stacks documentation for PoX ](https://example.com/pox-docs) + +## Blog posts + +To learn more about these concepts, check out these resources: + +- [Deep dive on Concept #1 ](https://example.com/blog/concept-1) +- [Video tutorial on Concept #2 ](https://example.com/blog/concept-2) +- [Clarity reference for functions ](https://example.com/blog/clarity-reference) +- [Stacks documentation for PoX ](https://example.com/blog/pox-docs) + + +## Videos + +To learn more about these concepts, check out these resources: + +- [Deep dive on Concept #1 ](https://example.com/videos/concept-1) +- [Video tutorial on Concept #2 ](https://example.com/videos/concept-2) +- [Clarity reference for functions ](https://example.com/videos/clarity-reference) +- [Stacks documentation for PoX ](https://example.com/videos/pox-docs) + +## e-Books + +To learn more about these concepts, check out these resources: + +- [Deep dive on Concept #1 ](https://example.com/ebooks/concept-1) +- [Video tutorial on Concept #2 ](https://example.com/ebooks/concept-2) +- [Clarity reference for functions ](https://example.com/ebooks/clarity-reference) +- [Stacks documentation for PoX ](https://example.com/ebooks/pox-docs) \ No newline at end of file diff --git a/content/_recipes/build-a-stx-pc.mdx b/content/_recipes/build-a-stx-pc.mdx deleted file mode 100644 index 9600b0c1b..000000000 --- a/content/_recipes/build-a-stx-pc.mdx +++ /dev/null @@ -1,49 +0,0 @@ -# Build a STX post-condition - -A helper function that creates a post-condition for STX token transfers using the `Pc` builder class, ensuring exact amounts are transferred as expected. - -## Use cases - -- Securing STX token transfers with transfer amount validation - -## Example usage - -```typescript -cn -import { - AnchorMode, - broadcastTransaction, - makeSTXTokenTransfer, - Pc, - PostConditionMode, -} from "@stacks/transactions"; - -// !hover post-conditions -const pc = Pc.principal("ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM") - // !hover post-conditions - .willSendEq(10000000) - // !hover post-conditions - .ustx(); - -const txOptions = { - recipient: "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5", - amount: 10000000, - senderKey: "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601", - network: STACKS_TESTNET, - // !hover post-conditions - postConditions: [pc], - postConditionMode: PostConditionMode.Deny, - anchorMode: AnchorMode.Any, -}; - -const transaction = await makeSTXTokenTransfer(txOptions); -const broadcastResponse = await broadcastTransaction({ - transaction, -}); -``` - -This example passes in our post-conditions as part of the transaction options, ensuring that exactly 10 STX will be transferred from the `ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM` principal. - -## Resources - -- [Stacks.js / Transactions](/stacks/stacks.js/packages/transactions) -- [Post-conditions](/stacks/stacks.js/guides/post-conditions) diff --git a/content/_recipes/build-an-ft-pc.mdx b/content/_recipes/build-an-ft-pc.mdx deleted file mode 100644 index f8442ec59..000000000 --- a/content/_recipes/build-an-ft-pc.mdx +++ /dev/null @@ -1,12 +0,0 @@ -# Build a fungible token post-condition - -A helper function that creates a post-condition for SIP-010 fungible token transfers using the `Pc` builder class, ensuring exact amounts of specific tokens are transferred as expected. - -## Use cases - -- Securing token swaps with transfer amount validation - -## Resources - -- [Stacks.js / Transactions](/stacks/stacks.js/packages/transactions) -- [Post-conditions](/stacks/stacks.js/guides/post-conditions) diff --git a/content/_recipes/build-an-nft-pc.mdx b/content/_recipes/build-an-nft-pc.mdx deleted file mode 100644 index f9f11a92a..000000000 --- a/content/_recipes/build-an-nft-pc.mdx +++ /dev/null @@ -1,12 +0,0 @@ -# Build an NFT post-condition - -A helper function that creates a post-condition for NFT transfers using the `Pc` builder class, ensuring specific NFTs are handled as expected. - -## Use cases - -- Securing NFT transfers with ownership validation - -## Resources - -- [Stacks.js / Transactions](/stacks/stacks.js/packages/transactions) -- [Post-conditions](/stacks/stacks.js/guides/post-conditions) diff --git a/content/_recipes/build-an-unsigned-tx.mdx b/content/_recipes/build-an-unsigned-tx.mdx deleted file mode 100644 index a910ffc77..000000000 --- a/content/_recipes/build-an-unsigned-tx.mdx +++ /dev/null @@ -1,34 +0,0 @@ -# Build an unsigned transaction - -A script that constructs an unsigned STX token transfer transaction using Stacks.js, allowing for transaction preparation without immediate signing. This pattern is particularly useful for multi-party transactions where signatures need to be collected separately. - -## Use cases - -- Implementing offline signing workflows -- Creating sponsored transactions to be signed by a third party -- Setting up transaction proposals for DAO governance - -## Signing the transaction - -After building your transaction, you can sign and then broadcast the newly signed transaction to the network. - -```typescript -c -import { - broadcastTransaction, - TransactionSigner, -} from "@stacks/transactions"; - -const privateKey = ""; // KEEP THIS SECRET! - -// !hover sign -const signer = new TransactionSigner(privateKey); -// !hover sign -const signedTx = await signer.signTransaction(transaction); - -// !hover broadcast -const broadcastedTx = await broadcastTransaction(signedTx); -``` - -## Resources - -- [Stacks.js / Transactions](/stacks/stacks.js/packages/transactions) diff --git a/content/_recipes/check-for-duplicates.mdx b/content/_recipes/check-for-duplicates.mdx deleted file mode 100644 index 484d82de5..000000000 --- a/content/_recipes/check-for-duplicates.mdx +++ /dev/null @@ -1,21 +0,0 @@ -# Check for duplicates - -A collection of helper functions to check for duplicates in both strings and lists. - -## Use cases - -- Verifying input strings have no duplicates -- Input validation for specific string formats -- Verifying unique participant addresses in reward distribution - -The first approach uses string manipulation to check for duplicate characters. It concatenates an _clarity`"|END"`_ marker to the input string and progressively checks each character using `fold` against the remaining substring. - -The second approach uses the `is-dup` private function to check for duplicates. This function retrieves each element at index `i`, checks if it appears again in the remaining sublist and returns `true` if any duplicates are found. - -## Resources - -**Clarity functions** - -- [`fold`](/stacks/clarity/functions/fold) [`slice?`](/stacks/clarity/functions/slice) [`concat`](/stacks/clarity/functions/concat) -- [`len`](/stacks/clarity/functions/len) [`index-of?`](/stacks/clarity/functions/index-of) [`unwrap-panic`](/stacks/clarity/functions/unwrap-panic) -- [`match`](/stacks/clarity/functions/match) \ No newline at end of file diff --git a/content/_recipes/convert-btc-to-stx-address.mdx b/content/_recipes/convert-btc-to-stx-address.mdx deleted file mode 100644 index b8708ba3b..000000000 --- a/content/_recipes/convert-btc-to-stx-address.mdx +++ /dev/null @@ -1,44 +0,0 @@ -# Convert a bitcoin address to its corresponding Stacks address - -Every base58-encoded bitcoin address can be easily converted to its corresponding Stacks address. This conversion can be done on-chain by implementing the base58 encoding scheme in Clarity. - -## Use cases - -- Abstracting away Stacks address usage for native bitcoin users -- Onboard bitcoin users onto Stacks with familiar UX -- Verify Stacks asset ownership of a bitcoin address - -## Example usage - -```typescript -let stxAddress = b58ToC32("1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa") // SP1HEJ1XHBJZJFNA2AECYQXQGZD8EQE4F30D6H5CR -``` - -```clarity -;; verify bitcoin address owns sBTC - -(define-public (verify-sbtc-ownership (btc-address (string-ascii 60))) - (let - ( - (stx-address (try! (btc-to-stx btc-address))) - (sbtc-balance (try! (contract-call? 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token get-balance stx-address))) - ) - (if (> sbtc-balance u0) - (ok true) - (err false) - ) - ) -) -``` - -## Resources - -**Clarity functions** - -- [`principal-construct?`](/stacks/clarity/functions/principal-construct) -- [`element-at?`](/stacks/clarity/functions/element-at) [`index-of?`](/stacks/clarity/functions/index-of) -- [`fold`](/stacks/clarity/functions/fold) - -**Related snippet** - -- [Convert a Stacks address to its corresponding Bitcoin address](https://play.hiro.so/?epoch=3.1&snippet=KGRlZmluZS1jb25zdGFudCBBTExfSEVYIDB4MDAwMTAyMDMwNDA1MDYwNzA4MDkwQTBCMEMwRDBFMEYxMDExMTIxMzE0MTUxNjE3MTgxOTFBMUIxQzFEMUUxRjIwMjEyMjIzMjQyNTI2MjcyODI5MkEyQjJDMkQyRTJGMzAzMTMyMzMzNDM1MzYzNzM4MzkzQTNCM0MzRDNFM0Y0MDQxNDI0MzQ0NDU0NjQ3NDg0OTRBNEI0QzRENEU0RjUwNTE1MjUzNTQ1NTU2NTc1ODU5NUE1QjVDNUQ1RTVGNjA2MTYyNjM2NDY1NjY2NzY4Njk2QTZCNkM2RDZFNkY3MDcxNzI3Mzc0NzU3Njc3Nzg3OTdBN0I3QzdEN0U3RjgwODE4MjgzODQ4NTg2ODc4ODg5OEE4QjhDOEQ4RThGOTA5MTkyOTM5NDk1OTY5Nzk4OTk5QTlCOUM5RDlFOUZBMEExQTJBM0E0QTVBNkE3QThBOUFBQUJBQ0FEQUVBRkIwQjFCMkIzQjRCNUI2QjdCOEI5QkFCQkJDQkRCRUJGQzBDMUMyQzNDNEM1QzZDN0M4QzlDQUNCQ0NDRENFQ0ZEMEQxRDJEM0Q0RDVENkQ3RDhEOURBREJEQ0REREVERkUwRTFFMkUzRTRFNUU2RTdFOEU5RUFFQkVDRURFRUVGRjBGMUYyRjNGNEY1RjZGN0Y4RjlGQUZCRkNGREZFRkYpCihkZWZpbmUtY29uc3RhbnQgQkFTRTU4X0NIQVJTICIxMjM0NTY3ODlBQkNERUZHSEpLTE1OUFFSU1RVVldYWVphYmNkZWZnaGlqa21ub3BxcnN0dXZ3eHl6IikKKGRlZmluZS1jb25zdGFudCBTVFhfVkVSIDB4MTYxNDFhMTUpCihkZWZpbmUtY29uc3RhbnQgQlRDX1ZFUiAweDAwMDU2ZmM0KQooZGVmaW5lLWNvbnN0YW50IExTVCAobGlzdCkpCgooZGVmaW5lLWNvbnN0YW50IEVSUl9JTlZBTElEX0FERFIgKGVyciB1MSkpCgooZGVmaW5lLXJlYWQtb25seSAoY29udmVydCAoYWRkciBwcmluY2lwYWwpKQogICAgKG1hdGNoIChwcmluY2lwYWwtZGVzdHJ1Y3Q_IGFkZHIpIAogICAgICAgIDs7IGlmIHZlcnNpb24gYnl0ZSBtYXRjaCB0aGUgbmV0d29yayAoaWUuIG1haW5uZXQgcHJpbmNpcGFsIG9uIG1haW5uZXQsIG9yIHRlc3RuZXQgcHJpbmNpcGFsIG9uIHRlc3RuZXQpCiAgICAgICAgbmV0d29yay1tYXRjaC1kYXRhIChjb252ZXJ0LWlubmVyIG5ldHdvcmstbWF0Y2gtZGF0YSkKICAgICAgICA7OyBpZiB2ZXJzaW4gYnl0ZSBkb2VzIG5vdCBtYXRjaCB0aGUgbmV0d29yawogICAgICAgIG5ldHdvcmstbm90LW1hdGNoLWRhdGEgKGNvbnZlcnQtaW5uZXIgbmV0d29yay1ub3QtbWF0Y2gtZGF0YSkKICAgICkKKQoKKGRlZmluZS1wcml2YXRlIChjb252ZXJ0LWlubmVyIChkYXRhIHtoYXNoLWJ5dGVzOiAoYnVmZiAyMCksIG5hbWU6IChvcHRpb25hbCAoc3RyaW5nLWFzY2lpIDQwKSksIHZlcnNpb246KGJ1ZmYgMSl9KSkKICAgIChsZXQgKAogICAgICAgIDs7IGV4aXQgZWFybHkgaWYgY29udHJhY3QgcHJpbmNpcGFsCiAgICAgICAgKHQxIChhc3NlcnRzISAoaXMtbm9uZSAoZ2V0IG5hbWUgZGF0YSkpIEVSUl9JTlZBTElEX0FERFIpKQogICAgICAgIDs7IGNvbnZlcnQgU1RYIHZlcnNpb24gYnl0ZSB0byBCVEMgdmVyc2lvbgogICAgICAgICh2ZXJzaW9uICh1bndyYXAtcGFuaWMgKGVsZW1lbnQtYXQ_IEJUQ19WRVIgKHVud3JhcC1wYW5pYyAoaW5kZXgtb2Y_IFNUWF9WRVIgKGdldCB2ZXJzaW9uIGRhdGEpKSkpKSkKICAgICAgICA7OyBjb25jYXQgQlRDIHZlcnNpb24gJiBoYXNoMTYwIAogICAgICAgICh2ZXJzaW9uZWQtaGFzaC1ieXRlcyAoY29uY2F0IHZlcnNpb24gKGdldCBoYXNoLWJ5dGVzIGRhdGEpKSkKICAgICAgICA7OyBjb25jYXQgaGFzaC1ieXRlcyAmIDQgYnl0ZXMgY2hlY2tzdW0sIGFuZCBjb252ZXJ0IGhleHQgdG8gdWludAogICAgICAgICh0by1lbmNvZGUgKG1hcCBoZXgtdG8tdWludCAoY29uY2F0IAogICAgICAgICAgICB2ZXJzaW9uZWQtaGFzaC1ieXRlcyAKICAgICAgICAgICAgOzsgY2hlY2tzdW0gPSBlbmNvZGUgdmVyc2lvbmRlZC1oYXNoLWJ5dGVzIDJ4IHdpdGggc2hhMjU2LCBhbmQgdGhlbiBleHRyYWN0IGZpcnN0IDQgYnl0ZXMKICAgICAgICAgICAgOzsgd2UgY2FuIHVzZSB1bndyYXAtcGFuaWMgdHdpY2UsIGJlY2F1c2Ugc2hhMjU2IG9mIGVtcHR5IGJ1ZmYgd2lsbCBhbHdhc3kgcmV0dXJuIHZhbHVlCiAgICAgICAgICAgICh1bndyYXAtcGFuaWMgKGFzLW1heC1sZW4_ICh1bndyYXAtcGFuaWMgKHNsaWNlPyAoc2hhMjU2IChzaGEyNTYgdmVyc2lvbmVkLWhhc2gtYnl0ZXMpKSB1MCB1NCkpIHU0KSkKICAgICAgICApKSkKICAgICAgICA7OyAiY3V0IiBsZWFkaW5nIHplcm9zIGxldmVyYWdpbmcgaW5kZXgtb2Y_IHByb3BlcnR5CiAgICAgICAgOzsgZmlyc3QgY29udmVydCBsaXN0IG9mIHVpbnQncyB0byBsaXN0IG9mIGJvb2xlYW5zIHRoYXQgdGVsbHMgaWYgdmFsdWUgd2FzIDAgb3Igbm90CiAgICAgICAgOzsgKGxpc3QgdTAgdTAgdTIgdTIzIHUwIHUzIHU1MyB1MjIpIC0-IChsaXN0IHRydWUgdHJ1ZSBmYWxzZSBmYWxzZSB0cnVlIGZhbHNlIGZhbHNlIGZhbHNlKQogICAgICAgIDs7IHNpbmNlIGluZGV4LW9mPyBhbHdheXMgcmV0dXJucyBmaXJzdCBpbmRleCB3ZSB1c2UgaXQgdG8gZmluZCB0aGUgcG9zaXRpb24gb2YgZmlyc3Qgbm9uLXplcm8gdmFsdWUKICAgICAgICA7OyBhbmQgd2UgZGVmYXVsdCBpdCB0byB1MCAtIGluIGNhc2UgaXQgd29uJ3QgZmluZCBhbnl0aGluZwogICAgICAgIDs7IGluIG91ciBleGFtcGxlLCBpdCB3aWxsIHJldHVybiAoc29tZSB1MikKICAgICAgICA7OyB0aGUgcmVhc29uIHdoeSB3ZSBkZWZhdWx0IHRvIHUwIGlzIHRoYXQgKHNsaWNlPyAobGlzdCB1MCB1MCB1MiB1MjMgdTAgdTMgdTUzIHUyMikgdTAgdTApIHdpbGwgcmV0dXJuIChzb21lIChsaXN0KSkKICAgICAgICA7OyBpdCBndWFyYW50ZWVzIHRoYXQgb3VyIHNsaWNlPyB3aWxsIG5ldmVyIHJldHVybiAobm9uZSkgc28gd2UgY2FuIHNhZmVseSB1c2UgdW53cmFwLXBhbmljIGhlcmUKICAgICAgICAobGVhZGluZy16ZXJvcyAodW53cmFwLXBhbmljIChzbGljZT8gdG8tZW5jb2RlIHUwIChkZWZhdWx0LXRvIHUwIChpbmRleC1vZj8gKG1hcCBpcy16ZXJvIHRvLWVuY29kZSkgZmFsc2UpKSkpKQogICAgKQogICAgICAgIChvayAKICAgICAgICAgICAgKGZvbGQgCiAgICAgICAgICAgICAgICBjb252ZXJ0LXRvLWJhc2U1OC1zdHJpbmcgCiAgICAgICAgICAgICAgICA7OyBydW4gdGhyb3VnaCAib3V0ZXItbG9vcCIgZXZlcnl0aGluZyBleGNlcHQgbGVhZGluZyB6ZXJvcwogICAgICAgICAgICAgICAgOzsgYW5kIGNvbmNhdGVuYXRlIHJlc3VsdHMgd2l0aCBsZWFkaW5nIHplcm9zIGlmIGFueQogICAgICAgICAgICAgICAgOzsgd2UgdXNlIHUyNSwgYmVjYXVzZSBoYXNoLWJ5dGVzIChha2EuIGhhc2gxNjApID0gMjAgYnl0ZXMsIHZlcnNpb24gPSAxIGJ5dGUsIGFuZCBjaGVja3N1bSA9IDQgYnl0ZXMKICAgICAgICAgICAgICAgIChjb25jYXQgKGZvbGQgb3V0ZXItbG9vcCAodW53cmFwLXBhbmljIChzbGljZT8gdG8tZW5jb2RlIChsZW4gbGVhZGluZy16ZXJvcykgdTI1KSkgTFNUKSBsZWFkaW5nLXplcm9zKSAKICAgICAgICAgICAgICAgICIiCiAgICAgICAgICAgICkKICAgICAgICApCiAgICApCikKCgooZGVmaW5lLXJlYWQtb25seSAob3V0ZXItbG9vcCAoeCB1aW50KSAob3V0IChsaXN0IDQ0IHVpbnQpKSkKICAgIChsZXQgKAogICAgICAgIChuZXctb3V0IChmb2xkIHVwZGF0ZS1vdXQgb3V0IChsaXN0IHgpKSkKICAgICAgICAocHVzaCAoZm9sZCBjYXJyeS1wdXNoIDB4MDAwMCAobGlzdCAodW53cmFwLXBhbmljIChlbGVtZW50LWF0PyBuZXctb3V0IHUwKSkpKSkKICAgICkKICAgICAgICAoY29uY2F0IAogICAgICAgICAgICAoZGVmYXVsdC10byBMU1QgKHNsaWNlPyBuZXctb3V0IHUxIChsZW4gbmV3LW91dCkpKQogICAgICAgICAgICAoZGVmYXVsdC10byBMU1QgKHNsaWNlPyBwdXNoIHUxIChsZW4gcHVzaCkpKQogICAgICAgICkKICAgICkKKQoKKGRlZmluZS1yZWFkLW9ubHkgKHVwZGF0ZS1vdXQgKHggdWludCkgKG91dCAobGlzdCAzNSB1aW50KSkpCiAgICAobGV0ICgKICAgICAgICA7OyBmaXJzdCBieXRlIG9mIG91dCBpcyBhbHdheXMgYSBjYXJyeSBmcm9tIHByZXZpb3VzIGl0ZXJhdGlvbgogICAgICAgIChjYXJyeSAoKyAodW53cmFwLXBhbmljIChlbGVtZW50LWF0PyBvdXQgdTApKSAoKiB4IHUyNTYpKSkKICAgICkKICAgICAgICAodW53cmFwLXBhbmljIChhcy1tYXgtbGVuPyAoY29uY2F0ICAKICAgICAgICAgICAgKGxpc3QgKC8gY2FycnkgdTU4KSkgOzsgbmV3IGNhcnJ5CiAgICAgICAgICAgIChjb25jYXQgCiAgICAgICAgICAgICAgICAoZGVmYXVsdC10byBMU1QgKHNsaWNlPyBvdXQgdTEgKGxlbiBvdXQpKSkgOzsgZXhpc3RpbmcgbGlzdAogICAgICAgICAgICAgICAgKGxpc3QgKG1vZCBjYXJyeSB1NTgpKSA7OyBuZXcgdmFsdWUgd2Ugd2FudCB0byBhcHBlbmQKICAgICAgICAgICAgKQogICAgICAgICkgdTM1KSkKICAgICkKKQoKKGRlZmluZS1yZWFkLW9ubHkgKGNhcnJ5LXB1c2ggKHggKGJ1ZmYgMSkpIChvdXQgKGxpc3QgOSB1aW50KSkpCiAgICAobGV0ICgKICAgICAgICA7OyBmaXJzdCBieXRlIG9mIG91dCBpcyBhbHdheXMgYSBjYXJyeSBmcm9tIHByZXZpb3VzIGl0ZXJhdGlvbgogICAgICAgIChjYXJyeSAodW53cmFwLXBhbmljIChlbGVtZW50LWF0PyBvdXQgdTApKSkKICAgICkKICAgICAgICAoaWYgKD4gY2FycnkgdTApCiAgICAgICAgICAgIDs7IHdlIG9ubHkgY2hhbmdlIG91dCBpZiBjYXJ5IGlzID4gdTAKICAgICAgICAgICAgKHVud3JhcC1wYW5pYyAoYXMtbWF4LWxlbj8gKGNvbmNhdCAKICAgICAgICAgICAgICAgIChsaXN0ICgvIGNhcnJ5IHU1OCkpIDs7IG5ldyBjYXJyeQogICAgICAgICAgICAgICAgKGNvbmNhdAogICAgICAgICAgICAgICAgICAgIChkZWZhdWx0LXRvIExTVCAoc2xpY2U_IG91dCB1MSAobGVuIG91dCkpKSA7OyBleGlzdGluZyBsaXN0CiAgICAgICAgICAgICAgICAgICAgKGxpc3QgKG1vZCBjYXJyeSB1NTgpKSA7OyBuZXcgdmFsdWUgd2Ugd2FudCB0byBhcHBlbmQKICAgICAgICAgICAgICAgICkKICAgICAgICAgICAgKSB1OSkpCiAgICAgICAgICAgIDs7IGRvIG5vdGhpbmcKICAgICAgICAgICAgb3V0CiAgICAgICAgKQogICAgKQopCgo7OyBjb252ZXJ0cyB1aW50IHRvIGJhc2U1OCBjYXJhY3RlciBhbmQgY29uY2F0ZW5hdGUgaW4gcmV2ZXJzZSBvcmRlcgooZGVmaW5lLXJlYWQtb25seSAoY29udmVydC10by1iYXNlNTgtc3RyaW5nICh4IHVpbnQpIChvdXQgKHN0cmluZy1hc2NpaSA0NCkpKQogICAgKHVud3JhcC1wYW5pYyAoYXMtbWF4LWxlbj8gKGNvbmNhdCAodW53cmFwLXBhbmljIChlbGVtZW50LWF0PyBCQVNFNThfQ0hBUlMgeCkpIG91dCkgdTQ0KSkKKQoKKGRlZmluZS1yZWFkLW9ubHkgKGhleC10by11aW50ICh4IChidWZmIDEpKSkgKHVud3JhcC1wYW5pYyAoaW5kZXgtb2Y_IEFMTF9IRVggeCkpKQooZGVmaW5lLXJlYWQtb25seSAoaXMtemVybyAoaSB1aW50KSkgKDw9IGkgdTApKQ) diff --git a/content/_recipes/convert-string-to-principal.mdx b/content/_recipes/convert-string-to-principal.mdx deleted file mode 100644 index e0f03cc77..000000000 --- a/content/_recipes/convert-string-to-principal.mdx +++ /dev/null @@ -1,15 +0,0 @@ -# Convert string to principal address - -A read-only function that converts a string to a principal type, handling both standard and contract principal formats. The function includes validation, checksum verification, and proper byte conversion. - -## Use cases - -- Cross-chain address format verification and conversion - -## Resources - -**Clarity functions** - -- [`sha256`](/stacks/clarity/functions/sha256) [`concat`](/stacks/clarity/functions/concat) [`slice?`](/stacks/clarity/functions/slice) -- [`element-at?`](/stacks/clarity/functions/element-at) [`unwrap-panic`](/stacks/clarity/functions/unwrap-panic) [`as-max-len?`](/stacks/clarity/functions/as-max-len) -- [`principal-construct?`](/stacks/clarity/functions/principal-construct) \ No newline at end of file diff --git a/content/_recipes/create-a-random-burn-address.mdx b/content/_recipes/create-a-random-burn-address.mdx deleted file mode 100644 index c1ba23c0c..000000000 --- a/content/_recipes/create-a-random-burn-address.mdx +++ /dev/null @@ -1,17 +0,0 @@ -# Create a random burn address - -A read-only function that generates a random burn address using principal-construct? from a hash of user-provided input, using different version bytes for mainnet (0x16) or testnet (0x1a). - -## Use cases - -- Creating verifiable burn addresses for token burning mechanisms -- Implementing proof-of-burn protocols -- Generating unique, unreclaimable addresses for protocol-level operations -- Setting up permanent token removal systems - -## Resources - -**Clarity functions** - -- [`hash160`](/stacks/clarity/functions/hash160) [`principal-construct?`](/stacks/clarity/functions/principal-construct) [`to-consensus-buff?`](/stacks/clarity/functions/to-consensus-buff) -- [`unwrap-panic`](/stacks/clarity/functions/unwrap-panic) diff --git a/content/_recipes/create-a-sponsored-tx.mdx b/content/_recipes/create-a-sponsored-tx.mdx deleted file mode 100644 index 847497b02..000000000 --- a/content/_recipes/create-a-sponsored-tx.mdx +++ /dev/null @@ -1,51 +0,0 @@ -# Create a sponsored transaction - -A script to create sponsored transactions where one party (the sponsor) pays the transaction fees for another party's transaction. - -## Use cases - -- Building onboarding flows where a service pays user fees -- Creating DAO operations where treasury pays member fees - -## Example usage - -```typescript -cn -import { - broadcastTransaction, - deserializeTransaction, - sponsorTransaction, -} from "@stacks/transactions"; -// !hover serialized-tx -import { serializedTx } from "./create-a-sponsored-tx"; - -const deserializedTx = deserializeTransaction(serializedTx); -const sponsorOptions = { - // !hover tx-options - transaction: deserializedTx, - // !hover tx-options - sponsorPrivateKey: "", - // !hover tx-options - fee: 1000n; - // !hover tx-options - sponsorNonce: 0, - // !hover tx-options - network: STACKS_TESTNET, -}; -// !hover sponsor-tx -const sponsoredTx = await sponsorTransaction(sponsorOptions); - -const broadcastResponse = await broadcastTransaction({ - transaction: sponsoredTx, -}); -const txId = broadcastResponse.txid; -``` - -This example takes the pre-built transaction and adds the sponsorship details to it. The sponsorship options include the transaction itself, the sponsor's credentials, their next valid nonce, and network details. - -Once configured, the sponsorTransaction function creates the sponsored version, which can then be broadcast to the network. - -## Resources - -- [Stacks.js / Transactions](/stacks/stacks.js/packages/transactions) -- [Transaction Broadcasting](/stacks/stacks.js/guides/broadcast-transactions) -- [Sponsored Transactions Use Cases (external)](https://tx2.app/docs) diff --git a/content/_recipes/create-sha256-hash-clarity.mdx b/content/_recipes/create-sha256-hash-clarity.mdx deleted file mode 100644 index 0edfdb9a9..000000000 --- a/content/_recipes/create-sha256-hash-clarity.mdx +++ /dev/null @@ -1,33 +0,0 @@ -# Create a SHA-256 hash using Clarity - -A scripts in Clarity that creates a sha256 hash -that can be created in javascript as well. - -## Use cases - -- validate a secret vote - -## Example usage - -```typescript -const hash = createSha256Hash("deadbeef"); //b462657d5547c972e675cfd7ee2e313eb033e6aa74f668ca7bd1d79a056c9fea -``` - -```clarity -;; vote -(define-map votes principal (buff 32)) -(map-set votes tx-sender 0xb462657d5547c972e675cfd7ee2e313eb033e6aa74f668ca7bd1d79a056c9fea) - -;; validate vote - -(define-read-only (validate-vote (vote (buff 8))) - (is-eq (map-get? votes tx-sender) (some (create-sha256-hash vote)))) - -(validate-vote 0xdeadbeef) -``` - -## Resources - -**Recipes** - -- [Create a SHA-256 hash using Stacks.js](/cookbook/create-sha256-hash-stacks-js) diff --git a/content/_recipes/create-sha256-hash-stacks-js.mdx b/content/_recipes/create-sha256-hash-stacks-js.mdx deleted file mode 100644 index 0e09f7adb..000000000 --- a/content/_recipes/create-sha256-hash-stacks-js.mdx +++ /dev/null @@ -1,33 +0,0 @@ -# Create a SHA-256 hash using Stacks.js - -A scripts in javascript that creates a sha256 hash -that can be created in Clarity as well. - -## Use cases - -- validate a secret vote - -## Example usage - -```typescript -const hash = createSha256Hash("deadbeef"); //b462657d5547c972e675cfd7ee2e313eb033e6aa74f668ca7bd1d79a056c9fea -``` - -```clarity -;; vote -(define-map votes principal (buff 32)) -(map-set votes tx-sender 0xb462657d5547c972e675cfd7ee2e313eb033e6aa74f668ca7bd1d79a056c9fea) - -;; validate vote - -(define-read-only (validate-vote (vote (buff 8))) - (is-eq (map-get? votes tx-sender) (some (create-sha256-hash vote)))) - -(validate-vote 0xdeadbeef) -``` - -## Resources - -**Recipes** - -- [Create a SHA-256 hash using Clarity](/cookbook/create-sha256-hash-clarity) diff --git a/content/_recipes/deploy-a-contract.mdx b/content/_recipes/deploy-a-contract.mdx deleted file mode 100644 index f48c3be32..000000000 --- a/content/_recipes/deploy-a-contract.mdx +++ /dev/null @@ -1,28 +0,0 @@ -# Deploy a contract - -A script that deploys a Clarity smart contract to the Stacks blockchain using Stacks.js. - -## Example usage - -```typescript -import { STACKS_TESTNET } from "@stacks/network"; -import { makeContractDeploy, broadcastTransaction } from "@stacks/transactions"; -import { readFileSync } from 'fs'; - -const txOptions = { - contractName: "super-cool-contract", - codeBody: readFileSync("./contract.clar", "utf8"), - senderKey: "", - network: STACKS_TESTNET, -}; - -const transaction = await makeContractDeploy(txOptions); -const broadcastResponse = await broadcastTransaction({transaction}); -const txId = broadcastResponse.txid; -``` - -This example reads the contract code from a file and uses it to deploy a contract to the Stacks blockchain. - -## Resources - -- [Stacks.js / Transactions](/stacks/stacks.js/packages/transactions) diff --git a/content/_recipes/derive-principal-addresses-between-networks.mdx b/content/_recipes/derive-principal-addresses-between-networks.mdx deleted file mode 100644 index 6c4819d14..000000000 --- a/content/_recipes/derive-principal-addresses-between-networks.mdx +++ /dev/null @@ -1,29 +0,0 @@ -# Derive principal addresses between networks - -A read-only function that extracts the hash bytes from an address. These bytes can then be used with the networks version byte to construct and derive an address on the other network. - -## Use cases - -- Useful for airdrop contracts that want to honor testnet participation by checking testnet address activity and mapping to mainnet addresses - -This example extracts the underlying hash bytes from a mainnet address using _clarity`principal-destruct?`_. These bytes remain constant between networks - only the version byte changes. - -_For mainnet addresses, the version byte is _clarity`0x16`_._ - -## Example usage - -With the following code, we can now convert a string by calling the _clarity`get-hash-bytes`_ function with the appropriate version bytes. - -```clarity -cn -(principal-construct? VERSION_BYTES (get-hash-bytes)) -``` - -## Resources - -**Clarity functions** - -- [`principal-construct?`](/stacks/clarity/functions/principal-construct) [`principal-destruct?`](/stacks/clarity/functions/principal-destruct) [`unwrap-err-panic`](/stacks/clarity/functions/unwrap-err-panic) - -**Recipes** - -- [create-a-random-burn-address](/cookbook/create-a-random-burn-address) diff --git a/content/_recipes/derive-stacks-address-from-keys.mdx b/content/_recipes/derive-stacks-address-from-keys.mdx deleted file mode 100644 index a7c53f6bf..000000000 --- a/content/_recipes/derive-stacks-address-from-keys.mdx +++ /dev/null @@ -1,12 +0,0 @@ -# Derive a Stacks address from private and public keys - -A utility function that derives a Stacks address from a private key and public key, with network specification (testnet/mainnet) to ensure correct address format. - -## Use cases - -- Message authentication and signing is one of the most common use cases for proving ownership or authenticity without exposing private keys -- Multisignature wallets when participants need to share their public keys - -## Resources - -- [Stacks.js / Transactions](/stacks/stacks.js/packages/transactions) diff --git a/content/_recipes/fetch-testnet-bitcoin-on-regtest.mdx b/content/_recipes/fetch-testnet-bitcoin-on-regtest.mdx deleted file mode 100644 index 38b1a4a59..000000000 --- a/content/_recipes/fetch-testnet-bitcoin-on-regtest.mdx +++ /dev/null @@ -1,8 +0,0 @@ -# Fetch testnet Bitcoin on regtest - -A script that requests test Bitcoin via API from Hiro's testnet faucet, allowing developers to receive testnet BTC to a specified address when testing on regtest mode. - -## Use cases - -- Bootstrapping sBTC projects for local development -- Setting up initial test wallets for development diff --git a/content/_recipes/filter-items-from-a-list.mdx b/content/_recipes/filter-items-from-a-list.mdx deleted file mode 100644 index eb575c5aa..000000000 --- a/content/_recipes/filter-items-from-a-list.mdx +++ /dev/null @@ -1,14 +0,0 @@ -# Filter items from a list - -A read-only function that filters specific values from a list using `fold` and a tracker tuple, returning a new list with the filtered results. - -## Use cases - -- When you need to remove specific elements while preserving the order of remaining items - -## Resources - -**Clarity functions** - -- [`fold`](/stacks/clarity/functions/fold) [`merge`](/stacks/clarity/functions/merge) [`is-eq`](/stacks/clarity/functions/is-eq) -- [`as-max-len?`](/stacks/clarity/functions/as-max-len) [`append`](/stacks/clarity/functions/append) [`unwrap-panic`](/stacks/clarity/functions/unwrap-panic) diff --git a/content/_recipes/generate-a-secret-key.mdx b/content/_recipes/generate-a-secret-key.mdx deleted file mode 100644 index 10e9b87c3..000000000 --- a/content/_recipes/generate-a-secret-key.mdx +++ /dev/null @@ -1,13 +0,0 @@ -# Generate a secret key - -A script that generates BIP39 mnemonic phrases for use as wallet secret keys. - -## Use cases - -- Creating new wallets -- Generating backup phrases -- Testing wallet functionality - -## Resources - -- [Stacks.js](/stacks/stacks.js) diff --git a/content/_recipes/generate-a-wallet.mdx b/content/_recipes/generate-a-wallet.mdx deleted file mode 100644 index ee50e5ffe..000000000 --- a/content/_recipes/generate-a-wallet.mdx +++ /dev/null @@ -1,40 +0,0 @@ -# Generate a wallet from a seed phrase or private key - -A script that creates a Stacks wallet from a seed phrase or private key, with support for multiple accounts. - -## Use cases - -- Creating new wallets from existing seed phrases -- Restoring wallets from backups -- Managing multiple accounts within a single wallet - -## Example usage - -```typescript -import { generateWallet, generateNewAccount } from '@stacks/wallet-sdk'; - -const mnemonic = "twice kind fence tip hidden tilt action fragile skin nothing glory cousin green tomorrow spring wrist shed math olympic multiply hip blue scout claw" -const privateKey = "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601" - -let wallet = generateWallet({ - // !diff - - secretKey: mnemonic, - // !diff + - secretKey: privateKey, - password: "secret", -}); - -// !hover generate-new-account -wallet = generateNewAccount(wallet); - -const { account1, account2 } = wallet; -``` - -This example demonstrates: - -1. You can use either a seed phrase or private key to create a wallet. -2. The generateNewAccount function adds a new account to the wallet. - -## Resources - -- [Stacks.js](/stacks/stacks.js) \ No newline at end of file diff --git a/content/_recipes/generate-random-number.mdx b/content/_recipes/generate-random-number.mdx deleted file mode 100644 index a09f2ff0a..000000000 --- a/content/_recipes/generate-random-number.mdx +++ /dev/null @@ -1,27 +0,0 @@ -# Generate a random number with block-height - - - -A read-only function that generates a deterministic [_random_](tooltip "random") number by extracting and converting a portion of a block's id-header-hash to an unsigned integer. - -## !random - -This method produces deterministic pseudo-randomness, not true randomness. - -Since blockchain transactions **must** be reproducible and verifiable by all nodes, true randomness isn't possible. - - - -## Use cases - -- Creating verifiable random selections for on-chain games -- Implementing fair distribution mechanisms for NFT minting -- Building lottery or raffle systems that need deterministic randomness -- Generating pseudo-random seeds for other contract operations - -## Resources - -**Clarity functions** - -- [`get-stacks-block-info?`](/stacks/clarity/functions/get-stacks-block-info) [`buff-to-uint-be`](/stacks/clarity/functions/buff-to-uint-be) [`as-max-len?`](/stacks/clarity/functions/as-max-len) -- [`slice?`](/stacks/clarity/functions/slice) [`unwrap-panic`](/stacks/clarity/functions/unwrap-panic) [`unwrap!`](/stacks/clarity/functions/unwrap) diff --git a/content/_recipes/get-account-details-from-wallet.mdx b/content/_recipes/get-account-details-from-wallet.mdx deleted file mode 100644 index 859956070..000000000 --- a/content/_recipes/get-account-details-from-wallet.mdx +++ /dev/null @@ -1,13 +0,0 @@ -# Get account details from a wallet - -A script that extracts important account details like the STX address and private key from a wallet. - -## Use cases - -- Retrieving wallet addresses for constructing transactions -- Getting private keys for signing operations -- Managing multiple wallet accounts - -## Resources - -- [Stacks.js](/stacks/stacks.js) diff --git a/content/_recipes/helper-function-to-restrict-contract-calls.mdx b/content/_recipes/helper-function-to-restrict-contract-calls.mdx deleted file mode 100644 index 2d43932b0..000000000 --- a/content/_recipes/helper-function-to-restrict-contract-calls.mdx +++ /dev/null @@ -1,30 +0,0 @@ -# Create a helper function to restrict contract calls - -A pattern that uses principal-destruct? to verify the _clarity`contract-caller`_ is a standard principal (user address) rather than a contract principal (contract address), ensuring transactions remain visible in explorers and APIs. - -When contracts call other contracts, these transactions can be harder to track and monitor through standard blockchain explorers and APIs. By enforcing direct user calls, you ensure all interactions are easily auditable and visible in the blockchain's history. - -This becomes especially important in scenarios involving treasury operations, voting mechanisms, or other critical protocol operations. - -## Use cases - -- Preventing "_hidden_" transactions in governance functions -- Protecting sensitive functions from potential contract-based exploits - -## Example usage - -```clarity -n -(define-public (important-function) - (begin - ;; !mark[/(is-standard-principal-call)/] - (asserts! (is-standard-principal-call) (err u403)) - (ok true) - ) -) -``` - -## Resources - -**Clarity functions** - -- [`principal-destruct?`](/stacks/clarity/functions/principal-destruct) [`get`](/stacks/clarity/functions/get) [`is-none`](/stacks/clarity/functions/is-none) diff --git a/content/_recipes/integrate-api-keys-using-stacksjs.mdx b/content/_recipes/integrate-api-keys-using-stacksjs.mdx deleted file mode 100644 index 775b5f852..000000000 --- a/content/_recipes/integrate-api-keys-using-stacksjs.mdx +++ /dev/null @@ -1,34 +0,0 @@ -# Integrate your API keys using Stacks.js - -A script that integrates your API key authentication into Stacks.js network calls using middleware, allowing for authenticated requests to Stacks APIs that require rate limiting or premium access. - -This example is showing a simple STX transfer transaction, but the same approach can be used for any Stacks API request that requires authentication - so long as you are passing in your _typescript`customFetchFn`_ to the client within your transaction details. - -## Use cases - -- Accessing premium API endpoints with higher rate limits -- Building production applications that require reliable API access - -## Example usage - -```typescript -nc -import { AnchorMode } from "@stacks/transactions"; - -const txOptions = { - network: "testnet", - recipient: "", - amount: 12345n, - senderKey: "", // KEEP THIS SECRET! - memo: "some memo", // optional - anchorMode: AnchorMode.Any, - // !mark(1:3) - client: { - fetch: customFetchFn, - }, -}; -``` - -## Resources - -- [API keys](/stacks/api-keys) -- [Stacks.js / Transactions](/stacks/stacks.js/packages/transactions) \ No newline at end of file diff --git a/content/_recipes/return-an-entry-from-a-map.mdx b/content/_recipes/return-an-entry-from-a-map.mdx deleted file mode 100644 index 129de5914..000000000 --- a/content/_recipes/return-an-entry-from-a-map.mdx +++ /dev/null @@ -1,15 +0,0 @@ -# Return an entry from a map - -A script that fetches and deserializes map entries from Clarity smart contracts using the Hiro API and Stacks.js, converting between Clarity values and their hexadecimal representations. - -## Use cases - -- Reading user balances or state from on-chain maps -- Retrieving NFT metadata stored in contract maps -- Checking governance voting records or parameters -- Fetching configuration data stored in contract maps - -## Resources - -- [Stacks Node RPC](/stacks/rpc-api/smart-contracts/map-entry) -- [Stacks.js / Transactions](/stacks/stacks.js/packages/transactions) \ No newline at end of file diff --git a/content/_recipes/transfer-a-sip10-token.mdx b/content/_recipes/transfer-a-sip10-token.mdx deleted file mode 100644 index 5e72f06e1..000000000 --- a/content/_recipes/transfer-a-sip10-token.mdx +++ /dev/null @@ -1,18 +0,0 @@ -# Transfer a SIP-10 fungible token using Stacks.js - -A script that transfers SIP-010 fungible tokens using Stacks.js, implementing post-conditions to ensure the exact amount is transferred. - -The example uses _typescript`Pc.principal(...)`_ builder to create a post-condition for fungible tokens that verifies the token contract will send the exact amount of tokens as expected. - -Setting _typescript`postConditionMode: PostConditionMode.Deny`_ prevents the transaction from succeeding when the provided post-condition(s) are not met. - -## Use cases - -- Implementing secure token transfer functionality in dApps -- Building DEX or token swap interfaces -- Setting up automated token distribution mechanisms - -## Resources - -- [Stacks.js / Transactions](/stacks/stacks.js/packages/transactions) -- [Post-conditions](/stacks/stacks.js/guides/post-conditions) diff --git a/content/_recipes/transfer-stx.mdx b/content/_recipes/transfer-stx.mdx deleted file mode 100644 index d6d1c43ef..000000000 --- a/content/_recipes/transfer-stx.mdx +++ /dev/null @@ -1,13 +0,0 @@ -# Transfer STX tokens - -A script that creates and broadcasts an STX token transfer with post-conditions for secure transfers. - -## Use cases - -- Sending STX tokens between addresses -- Building payment functionality - -## Resources - -- [Stacks.js / Transactions](/stacks/stacks.js/packages/transactions) -- [Post-conditions](/stacks/stacks.js/guides/post-conditions) diff --git a/content/docs/apis/ordinals-api/index.mdx b/content/docs/apis/ordinals-api/index.mdx new file mode 100644 index 000000000..be289c320 --- /dev/null +++ b/content/docs/apis/ordinals-api/index.mdx @@ -0,0 +1,55 @@ +--- +title: Ordinals API +sidebarTitle: Overview +description: The Ordinals API provides you with fast, reliable data for Bitcoin ordinals and BRC-20 tokens via an easy-to-use REST interface. +llm: false +--- + +import { SecondaryCard } from '@/components/card'; + +The Ordinals API is a service that helps you with the complete ingestion of ordinals inscription data. Using our endpoints, you can retrieve metadata for a particular inscription, trading activity, all inscriptions held by a particular address, and more. + +The Ordinals API uses REST endpoints and cached responses in order to optimize performance and reduce unnecessary requests. Start integrating ordinals and BRC-20 tokens into your app with one of the most reliable APIs on the market today. + +## Popular endpoints + + + + + + + + + +## Related tools + +- **[Bitcoin Indexer](/tools/bitcoin-indexer)**: Want to run your own infra? [Set up your own Bitcoin Indexer](/tools/bitcoin-indexer), the indexer that powers the Ordinals API. +- **[Ordinals Explorer](https://ordinals.hiro.so/)**: The Ordinals API powers Hiro’s Ordinals Explorer, which lets you rapidly discover inscriptions and verify on-chain activity. + +
+ +:::callout +type: help +### Need help building with the Ordinals API? +Reach out to us on the #ordinals channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET. +::: diff --git a/content/docs/apis/ordinals-api/meta.json b/content/docs/apis/ordinals-api/meta.json new file mode 100644 index 000000000..fa3ee47ef --- /dev/null +++ b/content/docs/apis/ordinals-api/meta.json @@ -0,0 +1,10 @@ +{ + "title": "Ordinals API", + "root": true, + "pages": [ + "---Ordinals API---", + "index", + "---Reference---", + "...reference" + ] +} diff --git a/content/docs/apis/ordinals-api/reference/brc20/get-brc20-activity.mdx b/content/docs/apis/ordinals-api/reference/brc20/get-brc20-activity.mdx new file mode 100644 index 000000000..d40234918 --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/brc20/get-brc20-activity.mdx @@ -0,0 +1,12 @@ +--- +title: Get BRC-20 activity +sidebarTitle: BRC-20 activity +description: Retrieves BRC-20 activity filtered by ticker, address, operation, or block height. +full: true +--- + + diff --git a/content/docs/apis/ordinals-api/reference/brc20/get-brc20-balances.mdx b/content/docs/apis/ordinals-api/reference/brc20/get-brc20-balances.mdx new file mode 100644 index 000000000..a46807f96 --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/brc20/get-brc20-balances.mdx @@ -0,0 +1,12 @@ +--- +title: Get BRC-20 balances +sidebarTitle: BRC-20 balances +description: Retrieves BRC-20 token balances for a Bitcoin address. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/ordinals-api/reference/brc20/get-brc20-token-details.mdx b/content/docs/apis/ordinals-api/reference/brc20/get-brc20-token-details.mdx new file mode 100644 index 000000000..f083c9eb1 --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/brc20/get-brc20-token-details.mdx @@ -0,0 +1,12 @@ +--- +title: Get BRC-20 token details +sidebarTitle: BRC-20 token details +description: Retrieves information for a BRC-20 token, including supply and holders. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/ordinals-api/reference/brc20/get-brc20-token-holders.mdx b/content/docs/apis/ordinals-api/reference/brc20/get-brc20-token-holders.mdx new file mode 100644 index 000000000..c33e8acbb --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/brc20/get-brc20-token-holders.mdx @@ -0,0 +1,12 @@ +--- +title: Get BRC-20 token holders +sidebarTitle: BRC-20 token holders +description: Retrieves a list of holders and their balances for a particular BRC-20 token. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/ordinals-api/reference/brc20/get-brc20-tokens.mdx b/content/docs/apis/ordinals-api/reference/brc20/get-brc20-tokens.mdx new file mode 100644 index 000000000..3ac4d54ca --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/brc20/get-brc20-tokens.mdx @@ -0,0 +1,12 @@ +--- +title: Get BRC-20 tokens +sidebarTitle: BRC-20 tokens +description: Retrieves information for BRC-20 tokens. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/ordinals-api/reference/brc20/index.mdx b/content/docs/apis/ordinals-api/reference/brc20/index.mdx new file mode 100644 index 000000000..bb0d24b2a --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/brc20/index.mdx @@ -0,0 +1,6 @@ +--- +title: BRC-20 +index: true +full: true +description: Retrieves information about BRC-20 tokens. +--- diff --git a/content/docs/bitcoin/ordinals/api/brc20/meta.json b/content/docs/apis/ordinals-api/reference/brc20/meta.json similarity index 100% rename from content/docs/bitcoin/ordinals/api/brc20/meta.json rename to content/docs/apis/ordinals-api/reference/brc20/meta.json diff --git a/content/docs/apis/ordinals-api/reference/info/index.mdx b/content/docs/apis/ordinals-api/reference/info/index.mdx new file mode 100644 index 000000000..3062e329e --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/info/index.mdx @@ -0,0 +1,6 @@ +--- +title: Status +index: true +full: true +description: Retrieves information about the Ordinals API status, including the server version. +--- diff --git a/content/docs/bitcoin/ordinals/api/info/meta.json b/content/docs/apis/ordinals-api/reference/info/meta.json similarity index 100% rename from content/docs/bitcoin/ordinals/api/info/meta.json rename to content/docs/apis/ordinals-api/reference/info/meta.json diff --git a/content/docs/apis/ordinals-api/reference/info/status.mdx b/content/docs/apis/ordinals-api/reference/info/status.mdx new file mode 100644 index 000000000..cd20fa58e --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/info/status.mdx @@ -0,0 +1,12 @@ +--- +title: Get API status +sidebarTitle: API status +description: Retrieves the running status of the Ordinals API. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/ordinals-api/reference/inscriptions/get-inscription-content.mdx b/content/docs/apis/ordinals-api/reference/inscriptions/get-inscription-content.mdx new file mode 100644 index 000000000..6d629ea0b --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/inscriptions/get-inscription-content.mdx @@ -0,0 +1,12 @@ +--- +title: Get inscription content +sidebarTitle: Inscription content +description: Retrieves the content of a single inscription. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/ordinals-api/reference/inscriptions/get-inscription-transfers.mdx b/content/docs/apis/ordinals-api/reference/inscriptions/get-inscription-transfers.mdx new file mode 100644 index 000000000..8745ebc43 --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/inscriptions/get-inscription-transfers.mdx @@ -0,0 +1,12 @@ +--- +title: Get inscription transfers +sidebarTitle: Inscription transfers +description: Retrieves all transfers for a single inscription. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/ordinals-api/reference/inscriptions/get-inscription.mdx b/content/docs/apis/ordinals-api/reference/inscriptions/get-inscription.mdx new file mode 100644 index 000000000..203294c59 --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/inscriptions/get-inscription.mdx @@ -0,0 +1,12 @@ +--- +title: Get inscription +sidebarTitle: Inscription +description: Retrieves a single inscription. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/ordinals-api/reference/inscriptions/get-inscriptions.mdx b/content/docs/apis/ordinals-api/reference/inscriptions/get-inscriptions.mdx new file mode 100644 index 000000000..c5af78fd3 --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/inscriptions/get-inscriptions.mdx @@ -0,0 +1,12 @@ +--- +title: Get inscriptions +sidebarTitle: Inscriptions +description: Retrieves a list of inscriptions with options to filter and sort results. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/ordinals-api/reference/inscriptions/get-transfers-per-block.mdx b/content/docs/apis/ordinals-api/reference/inscriptions/get-transfers-per-block.mdx new file mode 100644 index 000000000..82792dcb6 --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/inscriptions/get-transfers-per-block.mdx @@ -0,0 +1,12 @@ +--- +title: Get transfers per block +sidebarTitle: Transfers per block +description: Retrieves a list of inscription transfers that ocurred at a specific Bitcoin block. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/ordinals-api/reference/inscriptions/index.mdx b/content/docs/apis/ordinals-api/reference/inscriptions/index.mdx new file mode 100644 index 000000000..0d9f50aec --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/inscriptions/index.mdx @@ -0,0 +1,6 @@ +--- +title: Inscriptions +index: true +full: true +description: Retrieves information about Ordinals inscriptions. +--- diff --git a/content/docs/bitcoin/ordinals/api/inscriptions/meta.json b/content/docs/apis/ordinals-api/reference/inscriptions/meta.json similarity index 100% rename from content/docs/bitcoin/ordinals/api/inscriptions/meta.json rename to content/docs/apis/ordinals-api/reference/inscriptions/meta.json diff --git a/content/docs/apis/ordinals-api/reference/satoshis/get-satoshi-inscriptions.mdx b/content/docs/apis/ordinals-api/reference/satoshis/get-satoshi-inscriptions.mdx new file mode 100644 index 000000000..eb0390448 --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/satoshis/get-satoshi-inscriptions.mdx @@ -0,0 +1,12 @@ +--- +title: Get satoshi inscriptions +sidebarTitle: Satoshi inscriptions +description: Retrieves all inscriptions associated with a single satoshi. +full: true +--- + + diff --git a/content/docs/apis/ordinals-api/reference/satoshis/get-satoshi.mdx b/content/docs/apis/ordinals-api/reference/satoshis/get-satoshi.mdx new file mode 100644 index 000000000..ac83eb207 --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/satoshis/get-satoshi.mdx @@ -0,0 +1,12 @@ +--- +title: Get satoshi ordinal +sidebarTitle: Satoshi ordinal +description: Retrieves ordinal information for a single satoshi. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/ordinals-api/reference/satoshis/index.mdx b/content/docs/apis/ordinals-api/reference/satoshis/index.mdx new file mode 100644 index 000000000..d1053cf27 --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/satoshis/index.mdx @@ -0,0 +1,6 @@ +--- +title: Satoshis +index: true +full: true +description: Retrieves ordinal information for satoshis. +--- diff --git a/content/docs/bitcoin/ordinals/api/satoshis/meta.json b/content/docs/apis/ordinals-api/reference/satoshis/meta.json similarity index 100% rename from content/docs/bitcoin/ordinals/api/satoshis/meta.json rename to content/docs/apis/ordinals-api/reference/satoshis/meta.json diff --git a/content/docs/apis/ordinals-api/reference/statistics/get-stats-inscription-count.mdx b/content/docs/apis/ordinals-api/reference/statistics/get-stats-inscription-count.mdx new file mode 100644 index 000000000..1c7c2285f --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/statistics/get-stats-inscription-count.mdx @@ -0,0 +1,12 @@ +--- +title: Get inscription count per block +sidebarTitle: Inscription count per block +description: Retrieves statistics on the number of inscriptions revealed per block. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/ordinals-api/reference/statistics/index.mdx b/content/docs/apis/ordinals-api/reference/statistics/index.mdx new file mode 100644 index 000000000..11a0a94e4 --- /dev/null +++ b/content/docs/apis/ordinals-api/reference/statistics/index.mdx @@ -0,0 +1,6 @@ +--- +title: Statistics +index: true +full: true +description: Retrieves stats on the number of inscriptions per block. +--- diff --git a/content/docs/bitcoin/ordinals/api/statistics/meta.json b/content/docs/apis/ordinals-api/reference/statistics/meta.json similarity index 100% rename from content/docs/bitcoin/ordinals/api/statistics/meta.json rename to content/docs/apis/ordinals-api/reference/statistics/meta.json diff --git a/content/docs/apis/ordinals-api/usage.mdx b/content/docs/apis/ordinals-api/usage.mdx new file mode 100644 index 000000000..cc22f7a85 --- /dev/null +++ b/content/docs/apis/ordinals-api/usage.mdx @@ -0,0 +1,12 @@ +--- +title: Usage +sidebarTitle: Usage +description: Create your first project in less than 2 minutes +--- + +The Usage section should focus on practical, hands-on instructions for getting started with the API. This includes: +Authentication: How to authenticate with the API (e.g., API keys, OAuth tokens). +Making Requests: Basic examples of making requests to the API, including request format, essential headers, and parameters. +Handling Responses: Information on response structure, understanding status codes, and error handling. +Rate Limits: If applicable, explain any rate limits and best practices for avoiding them. +The goal of the "Usage" section is to equip developers with the knowledge to make successful API calls and handle responses effectively. diff --git a/content/docs/apis/platform-api/index.mdx b/content/docs/apis/platform-api/index.mdx new file mode 100644 index 000000000..6698cf278 --- /dev/null +++ b/content/docs/apis/platform-api/index.mdx @@ -0,0 +1,53 @@ +--- +title: Platform API +sidebarTitle: Overview +description: Leverage programmatic API access in order to seamlessly interact with devnet and manage chainhooks. +llm: false +--- + +import { SecondaryCard } from '@/components/card'; + +The Platform API unlocks powerful automation opportunities in your application code, development and CI scripts, and more, via a familiar REST interface. + +In particular, this API lets you programmatically create, update, query, and delete chainhooks as well as interact with a platform-hosted devnet from your local machine. + +When you create a Platform account, you'll automatically receive an API key that's required to use these endpoints. You can also create additional API keys in the [Hiro Platform](/resources/guides/api-keys) as needed. + +## Popular endpoints + + + + + + + + +## Related tools + +- **[Hiro Platform](https://platform.hiro.so)**: A developer platform for building, deploying and scaling Bitcoin apps. +- **[Chainhook](/tools/chainhook)**: You don't need the platform to create event streams. Leverage chainhook independently, so your app can react to on-chain events in real time. +- **[Stacks Blockchain API](/apis/stacks-blockchain-api)**: Fetch on-chain data from the Stacks blockchain. +- **[Token Metadata API](/apis/token-metadata-api)**: Fetch fungible and non-fungible token data on the Stacks blockchain. + +
+ +:::callout +type: help +### Need help building with the Platform API? +Reach out to us on the #hiro-platform channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET. +::: + + + diff --git a/content/docs/apis/platform-api/meta.json b/content/docs/apis/platform-api/meta.json new file mode 100644 index 000000000..8e83ff779 --- /dev/null +++ b/content/docs/apis/platform-api/meta.json @@ -0,0 +1,10 @@ +{ + "title": "Platform API", + "root": true, + "pages": [ + "---Platform API---", + "index", + "---Reference---", + "...reference" + ] +} diff --git a/content/docs/apis/platform-api/reference/chainhooks/create.mdx b/content/docs/apis/platform-api/reference/chainhooks/create.mdx new file mode 100644 index 000000000..a11d40de6 --- /dev/null +++ b/content/docs/apis/platform-api/reference/chainhooks/create.mdx @@ -0,0 +1,12 @@ +--- +title: Create a chainhook +sidebarTitle: Create +description: Create a chainhook through the Hiro Platform. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/platform-api/reference/chainhooks/delete.mdx b/content/docs/apis/platform-api/reference/chainhooks/delete.mdx new file mode 100644 index 000000000..74e41b4a2 --- /dev/null +++ b/content/docs/apis/platform-api/reference/chainhooks/delete.mdx @@ -0,0 +1,12 @@ +--- +title: Delete a chainhook +sidebarTitle: Delete +description: Delete a chainhook through the Hiro Platform. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/platform-api/reference/chainhooks/get.mdx b/content/docs/apis/platform-api/reference/chainhooks/get.mdx new file mode 100644 index 000000000..45ec8266f --- /dev/null +++ b/content/docs/apis/platform-api/reference/chainhooks/get.mdx @@ -0,0 +1,12 @@ +--- +title: Get a specific chainhook +sidebarTitle: Get +description: Get a specific chainhook through the Hiro Platform. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/platform-api/reference/chainhooks/index.mdx b/content/docs/apis/platform-api/reference/chainhooks/index.mdx new file mode 100644 index 000000000..a677a9792 --- /dev/null +++ b/content/docs/apis/platform-api/reference/chainhooks/index.mdx @@ -0,0 +1,6 @@ +--- +title: Chainhooks +index: true +full: true +description: Retrieves information about the Platform Chainhooks API. +--- diff --git a/content/docs/apis/platform-api/reference/chainhooks/list.mdx b/content/docs/apis/platform-api/reference/chainhooks/list.mdx new file mode 100644 index 000000000..dab8ef3e7 --- /dev/null +++ b/content/docs/apis/platform-api/reference/chainhooks/list.mdx @@ -0,0 +1,12 @@ +--- +title: Get all chainhooks +sidebarTitle: List +description: Get all of your chainhooks through the Hiro Platform. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/stacks/platform-api/chainhooks/meta.json b/content/docs/apis/platform-api/reference/chainhooks/meta.json similarity index 100% rename from content/docs/stacks/platform-api/chainhooks/meta.json rename to content/docs/apis/platform-api/reference/chainhooks/meta.json diff --git a/content/docs/apis/platform-api/reference/chainhooks/status.mdx b/content/docs/apis/platform-api/reference/chainhooks/status.mdx new file mode 100644 index 000000000..bf0fe4f58 --- /dev/null +++ b/content/docs/apis/platform-api/reference/chainhooks/status.mdx @@ -0,0 +1,12 @@ +--- +title: Get a chainhook status +sidebarTitle: Status +description: Retrieve the status of a specific chainhook through the Hiro Platform. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/platform-api/reference/chainhooks/update.mdx b/content/docs/apis/platform-api/reference/chainhooks/update.mdx new file mode 100644 index 000000000..e457b4c40 --- /dev/null +++ b/content/docs/apis/platform-api/reference/chainhooks/update.mdx @@ -0,0 +1,12 @@ +--- +title: Update a chainhook +sidebarTitle: Update +description: Update a chainhook through the Hiro Platform. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/platform-api/reference/devnet/bitcoin-node.mdx b/content/docs/apis/platform-api/reference/devnet/bitcoin-node.mdx new file mode 100644 index 000000000..f5efdc098 --- /dev/null +++ b/content/docs/apis/platform-api/reference/devnet/bitcoin-node.mdx @@ -0,0 +1,12 @@ +--- +title: Bitcoin node +sidebarTitle: Bitcoin node +description: Proxy for the Bitcoin node on a development network (devnet). +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/platform-api/reference/devnet/index.mdx b/content/docs/apis/platform-api/reference/devnet/index.mdx new file mode 100644 index 000000000..76b0f2fec --- /dev/null +++ b/content/docs/apis/platform-api/reference/devnet/index.mdx @@ -0,0 +1,6 @@ +--- +title: Devnet +index: true +full: true +description: Retrieves information about the Platform Devnet services such as Stacks Blockchain API, Bitcoin node, and more. +--- diff --git a/content/docs/stacks/platform-api/devnet/meta.json b/content/docs/apis/platform-api/reference/devnet/meta.json similarity index 100% rename from content/docs/stacks/platform-api/devnet/meta.json rename to content/docs/apis/platform-api/reference/devnet/meta.json diff --git a/content/docs/apis/platform-api/reference/devnet/stacks-blockchain-api.mdx b/content/docs/apis/platform-api/reference/devnet/stacks-blockchain-api.mdx new file mode 100644 index 000000000..21f612739 --- /dev/null +++ b/content/docs/apis/platform-api/reference/devnet/stacks-blockchain-api.mdx @@ -0,0 +1,12 @@ +--- +title: Stacks Blockchain API +sidebarTitle: Stacks Blockchain API +description: Proxy for the Stacks Blockchain API on a development network (devnet). +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/platform-api/reference/devnet/start.mdx b/content/docs/apis/platform-api/reference/devnet/start.mdx new file mode 100644 index 000000000..9ff6069fe --- /dev/null +++ b/content/docs/apis/platform-api/reference/devnet/start.mdx @@ -0,0 +1,12 @@ +--- +title: Start devnet +sidebarTitle: Start devnet +description: Start a development network (devnet). +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/platform-api/reference/devnet/stop.mdx b/content/docs/apis/platform-api/reference/devnet/stop.mdx new file mode 100644 index 000000000..24ae7cedc --- /dev/null +++ b/content/docs/apis/platform-api/reference/devnet/stop.mdx @@ -0,0 +1,12 @@ +--- +title: Stop devnet +sidebarTitle: Stop devnet +description: Stop a development network (devnet). +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/runes-api/index.mdx b/content/docs/apis/runes-api/index.mdx new file mode 100644 index 000000000..83f6134a2 --- /dev/null +++ b/content/docs/apis/runes-api/index.mdx @@ -0,0 +1,39 @@ +--- +title: Runes API +sidebarTitle: Overview +description: The Runes API provides you with fast, reliable data for Bitcoin Runes via an easy-to-use REST interface. +llm: false +--- + +The Runes API is a service that helps you with the complete ingestion of Bitcoin Runes data. Using our endpoints, you can retrieve metadata for a particular rune, trading activity, all runes held by a particular address, and more. + +The Runes API uses REST endpoints and cached responses in order to optimize performance and reduce unnecessary requests. Reliable, consistent runes data, one request away. + +## Popular endpoints + + + + + + + +### Related tools + +- **[Ordinals API](/apis/ordinals-api)**: Looking for on-chain ordinals data without the front end? Leverage the Ordinals API. +- **[Ordinals Explorer](https://ordinals.hiro.so/)**: The Ordinals API powers Hiro’s Ordinals Explorer, which lets you rapidly discover inscriptions and verify on-chain activity. + +--- + +Need help building with Runes API? Reach out to us on the `#ordinals` channel on Discord. Or join us at our weekly office hours on Discord every Monday at 11am ET. diff --git a/content/docs/apis/runes-api/meta.json b/content/docs/apis/runes-api/meta.json new file mode 100644 index 000000000..633f8039a --- /dev/null +++ b/content/docs/apis/runes-api/meta.json @@ -0,0 +1,10 @@ +{ + "title": "Runes API", + "root": true, + "pages": [ + "---Runes API---", + "index", + "---Reference---", + "...reference" + ] +} diff --git a/content/docs/apis/runes-api/reference/activities/activity.mdx b/content/docs/apis/runes-api/reference/activities/activity.mdx new file mode 100644 index 000000000..8e70743f2 --- /dev/null +++ b/content/docs/apis/runes-api/reference/activities/activity.mdx @@ -0,0 +1,12 @@ +--- +title: Get all activity +sidebarTitle: All activity +description: Retrieves all activity for a Rune. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/runes-api/reference/activities/for-address.mdx b/content/docs/apis/runes-api/reference/activities/for-address.mdx new file mode 100644 index 000000000..4240e5d4e --- /dev/null +++ b/content/docs/apis/runes-api/reference/activities/for-address.mdx @@ -0,0 +1,12 @@ +--- +title: Get activity for an address +sidebarTitle: Activity for an address +description: Retrieves all Rune activity for a Bitcoin address. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/runes-api/reference/activities/for-block.mdx b/content/docs/apis/runes-api/reference/activities/for-block.mdx new file mode 100644 index 000000000..36428caea --- /dev/null +++ b/content/docs/apis/runes-api/reference/activities/for-block.mdx @@ -0,0 +1,12 @@ +--- +title: Get activity for a block +sidebarTitle: Activity for a block +description: Retrieves a paginated list of rune activity for a block. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/runes-api/reference/activities/for-transaction.mdx b/content/docs/apis/runes-api/reference/activities/for-transaction.mdx new file mode 100644 index 000000000..cc5c258ad --- /dev/null +++ b/content/docs/apis/runes-api/reference/activities/for-transaction.mdx @@ -0,0 +1,12 @@ +--- +title: Get activity for a transaction +sidebarTitle: Activity for a transaction +description: Retrieves a paginated list of rune activity for a transaction. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/runes-api/reference/activities/index.mdx b/content/docs/apis/runes-api/reference/activities/index.mdx new file mode 100644 index 000000000..bfdc06ca7 --- /dev/null +++ b/content/docs/apis/runes-api/reference/activities/index.mdx @@ -0,0 +1,6 @@ +--- +title: Activities +index: true +full: true +description: Retrieves information about Rune activities. +--- diff --git a/content/docs/bitcoin/runes/api/activities/meta.json b/content/docs/apis/runes-api/reference/activities/meta.json similarity index 100% rename from content/docs/bitcoin/runes/api/activities/meta.json rename to content/docs/apis/runes-api/reference/activities/meta.json diff --git a/content/docs/apis/runes-api/reference/balances/address.mdx b/content/docs/apis/runes-api/reference/balances/address.mdx new file mode 100644 index 000000000..ec8a7bb18 --- /dev/null +++ b/content/docs/apis/runes-api/reference/balances/address.mdx @@ -0,0 +1,12 @@ +--- +title: Get address balances +sidebarTitle: Address balances +description: Retrieves a paginated list of address balances. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/runes-api/reference/balances/holder-balance.mdx b/content/docs/apis/runes-api/reference/balances/holder-balance.mdx new file mode 100644 index 000000000..754e803f5 --- /dev/null +++ b/content/docs/apis/runes-api/reference/balances/holder-balance.mdx @@ -0,0 +1,12 @@ +--- +title: Get holder balance +sidebarTitle: Holder balance +description: Retrieves holder balance for a specific Rune. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/runes-api/reference/balances/holders.mdx b/content/docs/apis/runes-api/reference/balances/holders.mdx new file mode 100644 index 000000000..2e327d232 --- /dev/null +++ b/content/docs/apis/runes-api/reference/balances/holders.mdx @@ -0,0 +1,12 @@ +--- +title: Get rune holders +sidebarTitle: Rune holders +description: Retrieves a paginated list of holders for a Rune. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/runes-api/reference/balances/index.mdx b/content/docs/apis/runes-api/reference/balances/index.mdx new file mode 100644 index 000000000..bb73ce112 --- /dev/null +++ b/content/docs/apis/runes-api/reference/balances/index.mdx @@ -0,0 +1,6 @@ +--- +title: Balances +index: true +full: true +description: Retrieves information about Rune balances. +--- diff --git a/content/docs/bitcoin/runes/api/balances/meta.json b/content/docs/apis/runes-api/reference/balances/meta.json similarity index 100% rename from content/docs/bitcoin/runes/api/balances/meta.json rename to content/docs/apis/runes-api/reference/balances/meta.json diff --git a/content/docs/apis/runes-api/reference/etchings/get-etching.mdx b/content/docs/apis/runes-api/reference/etchings/get-etching.mdx new file mode 100644 index 000000000..679b861a1 --- /dev/null +++ b/content/docs/apis/runes-api/reference/etchings/get-etching.mdx @@ -0,0 +1,12 @@ +--- +title: Get etching +sidebarTitle: Etching +description: Retrieves information for a Rune etching. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/runes-api/reference/etchings/get-etchings.mdx b/content/docs/apis/runes-api/reference/etchings/get-etchings.mdx new file mode 100644 index 000000000..36dbf81d9 --- /dev/null +++ b/content/docs/apis/runes-api/reference/etchings/get-etchings.mdx @@ -0,0 +1,12 @@ +--- +title: Get etchings +sidebarTitle: Etchings +description: Retrieves a paginated list of rune etchings. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/runes-api/reference/etchings/index.mdx b/content/docs/apis/runes-api/reference/etchings/index.mdx new file mode 100644 index 000000000..b967d8712 --- /dev/null +++ b/content/docs/apis/runes-api/reference/etchings/index.mdx @@ -0,0 +1,6 @@ +--- +title: Etchings +index: true +full: true +description: Retrieves information about Rune etchings. +--- diff --git a/content/docs/bitcoin/runes/api/etchings/meta.json b/content/docs/apis/runes-api/reference/etchings/meta.json similarity index 100% rename from content/docs/bitcoin/runes/api/etchings/meta.json rename to content/docs/apis/runes-api/reference/etchings/meta.json diff --git a/content/docs/apis/runes-api/reference/info/index.mdx b/content/docs/apis/runes-api/reference/info/index.mdx new file mode 100644 index 000000000..294c0490a --- /dev/null +++ b/content/docs/apis/runes-api/reference/info/index.mdx @@ -0,0 +1,6 @@ +--- +title: Status +index: true +full: true +description: Retrieves information about the Rune API status. +--- diff --git a/content/docs/bitcoin/runes/api/info/meta.json b/content/docs/apis/runes-api/reference/info/meta.json similarity index 100% rename from content/docs/bitcoin/runes/api/info/meta.json rename to content/docs/apis/runes-api/reference/info/meta.json diff --git a/content/docs/apis/runes-api/reference/info/status.mdx b/content/docs/apis/runes-api/reference/info/status.mdx new file mode 100644 index 000000000..4b07e8769 --- /dev/null +++ b/content/docs/apis/runes-api/reference/info/status.mdx @@ -0,0 +1,12 @@ +--- +title: Get API Status +sidebarTitle: API Status +description: Retrieves the status of the API. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/runes-api/usage.mdx b/content/docs/apis/runes-api/usage.mdx new file mode 100644 index 000000000..cc22f7a85 --- /dev/null +++ b/content/docs/apis/runes-api/usage.mdx @@ -0,0 +1,12 @@ +--- +title: Usage +sidebarTitle: Usage +description: Create your first project in less than 2 minutes +--- + +The Usage section should focus on practical, hands-on instructions for getting started with the API. This includes: +Authentication: How to authenticate with the API (e.g., API keys, OAuth tokens). +Making Requests: Basic examples of making requests to the API, including request format, essential headers, and parameters. +Handling Responses: Information on response structure, understanding status codes, and error handling. +Rate Limits: If applicable, explain any rate limits and best practices for avoiding them. +The goal of the "Usage" section is to equip developers with the knowledge to make successful API calls and handle responses effectively. diff --git a/content/docs/apis/signer-metrics-api/index.mdx b/content/docs/apis/signer-metrics-api/index.mdx new file mode 100644 index 000000000..7f7d9d2f1 --- /dev/null +++ b/content/docs/apis/signer-metrics-api/index.mdx @@ -0,0 +1,42 @@ +--- +title: Signer Metrics API +sidebarTitle: Overview +description: Monitor and analyze signer behavior on the Stacks network. +llm: false +--- + +import { SecondaryCard } from '@/components/card'; + +The Signer Metrics API enables you to monitor signers on the Stacks network. With a familiar REST interface, you can easily fetch information about the signer network, such as lists of active signers in a particular PoX cycle and signer information for a particular block. + +This API also lets you analyze and evaluate the behavior of individual signers, such as their block acceptance rate, their average block push time, and more. + +## Popular endpoints + + + + + + +## Related tools + +- **[Stacks Blockchain API](/apis/stacks-blockchain-api)**: Fetch richer data from Hiro's Stacks Blockchain API. +- **[Token Metadata API](/apis/token-metadata-api)**: Fetch fungible and non-fungible token data on the Stacks blockchain. + +
+ +:::callout +type: help +### Need help building with the Stacks Blockchain API? +Reach out to us on the #api channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET. +::: + + diff --git a/content/docs/apis/signer-metrics-api/meta.json b/content/docs/apis/signer-metrics-api/meta.json new file mode 100644 index 000000000..dd58010b8 --- /dev/null +++ b/content/docs/apis/signer-metrics-api/meta.json @@ -0,0 +1,10 @@ +{ + "title": "Signer Metrics API", + "root": true, + "pages": [ + "---Signer Metrics API---", + "index", + "---Reference---", + "...reference" + ] +} diff --git a/content/docs/apis/signer-metrics-api/reference/block-proposals/index.mdx b/content/docs/apis/signer-metrics-api/reference/block-proposals/index.mdx new file mode 100644 index 000000000..d0c95e1e7 --- /dev/null +++ b/content/docs/apis/signer-metrics-api/reference/block-proposals/index.mdx @@ -0,0 +1,6 @@ +--- +title: Block proposals +description: Get information about block proposals. +full: true +index: true +--- \ No newline at end of file diff --git a/content/docs/stacks/signer-metrics-api/block-proposals/meta.json b/content/docs/apis/signer-metrics-api/reference/block-proposals/meta.json similarity index 100% rename from content/docs/stacks/signer-metrics-api/block-proposals/meta.json rename to content/docs/apis/signer-metrics-api/reference/block-proposals/meta.json diff --git a/content/docs/apis/signer-metrics-api/reference/block-proposals/signer-information-for-a-block.mdx b/content/docs/apis/signer-metrics-api/reference/block-proposals/signer-information-for-a-block.mdx new file mode 100644 index 000000000..e68b34596 --- /dev/null +++ b/content/docs/apis/signer-metrics-api/reference/block-proposals/signer-information-for-a-block.mdx @@ -0,0 +1,12 @@ +--- +title: Signer information for a block +sidebarTitle: Signer info for block proposal +description: Get signer information for a specific block. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/signer-metrics-api/reference/block-proposals/signer-information-for-most-recent-block-proposals.mdx b/content/docs/apis/signer-metrics-api/reference/block-proposals/signer-information-for-most-recent-block-proposals.mdx new file mode 100644 index 000000000..eabb0c576 --- /dev/null +++ b/content/docs/apis/signer-metrics-api/reference/block-proposals/signer-information-for-most-recent-block-proposals.mdx @@ -0,0 +1,12 @@ +--- +title: Signer information for most recent block proposals +sidebarTitle: Signer info for recent proposals +description: Get signer information for most recent block proposals. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/signer-metrics-api/reference/blocks/aggregated-signer-information-for-a-block.mdx b/content/docs/apis/signer-metrics-api/reference/blocks/aggregated-signer-information-for-a-block.mdx new file mode 100644 index 000000000..fe6488a3a --- /dev/null +++ b/content/docs/apis/signer-metrics-api/reference/blocks/aggregated-signer-information-for-a-block.mdx @@ -0,0 +1,12 @@ +--- +title: Aggregated signer information for a block +sidebarTitle: Signer info for block +description: Get aggregated signer information for a specific block. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/signer-metrics-api/reference/blocks/aggregated-signer-information-for-most-recent-blocks.mdx b/content/docs/apis/signer-metrics-api/reference/blocks/aggregated-signer-information-for-most-recent-blocks.mdx new file mode 100644 index 000000000..01f6f0d53 --- /dev/null +++ b/content/docs/apis/signer-metrics-api/reference/blocks/aggregated-signer-information-for-most-recent-blocks.mdx @@ -0,0 +1,12 @@ +--- +title: Aggregated signer information for most recent blocks +sidebarTitle: Signer info for recent blocks +description: Get aggregated signer information for most recent blocks. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/signer-metrics-api/reference/blocks/index.mdx b/content/docs/apis/signer-metrics-api/reference/blocks/index.mdx new file mode 100644 index 000000000..56fa1e4d4 --- /dev/null +++ b/content/docs/apis/signer-metrics-api/reference/blocks/index.mdx @@ -0,0 +1,6 @@ +--- +title: Blocks +description: Get aggregated signer information for blocks. +full: true +index: true +--- \ No newline at end of file diff --git a/content/docs/stacks/signer-metrics-api/blocks/meta.json b/content/docs/apis/signer-metrics-api/reference/blocks/meta.json similarity index 100% rename from content/docs/stacks/signer-metrics-api/blocks/meta.json rename to content/docs/apis/signer-metrics-api/reference/blocks/meta.json diff --git a/content/docs/apis/signer-metrics-api/reference/info/index.mdx b/content/docs/apis/signer-metrics-api/reference/info/index.mdx new file mode 100644 index 000000000..c5f921e75 --- /dev/null +++ b/content/docs/apis/signer-metrics-api/reference/info/index.mdx @@ -0,0 +1,6 @@ +--- +title: Info +description: Service status endpoints +full: true +index: true +--- \ No newline at end of file diff --git a/content/docs/stacks/signer-metrics-api/info/meta.json b/content/docs/apis/signer-metrics-api/reference/info/meta.json similarity index 100% rename from content/docs/stacks/signer-metrics-api/info/meta.json rename to content/docs/apis/signer-metrics-api/reference/info/meta.json diff --git a/content/docs/apis/signer-metrics-api/reference/info/status.mdx b/content/docs/apis/signer-metrics-api/reference/info/status.mdx new file mode 100644 index 000000000..5e252331e --- /dev/null +++ b/content/docs/apis/signer-metrics-api/reference/info/status.mdx @@ -0,0 +1,12 @@ +--- +title: API Status +sidebarTitle: API Status +description: Displays the status of the API and its current workload. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/signer-metrics-api/reference/signers/index.mdx b/content/docs/apis/signer-metrics-api/reference/signers/index.mdx new file mode 100644 index 000000000..e8ce390b9 --- /dev/null +++ b/content/docs/apis/signer-metrics-api/reference/signers/index.mdx @@ -0,0 +1,6 @@ +--- +title: Signers +description: Get information about signers on the Stacks blockchain. +full: true +index: true +--- \ No newline at end of file diff --git a/content/docs/stacks/signer-metrics-api/signers/meta.json b/content/docs/apis/signer-metrics-api/reference/signers/meta.json similarity index 100% rename from content/docs/stacks/signer-metrics-api/signers/meta.json rename to content/docs/apis/signer-metrics-api/reference/signers/meta.json diff --git a/content/docs/apis/signer-metrics-api/reference/signers/pox-cycle-signer.mdx b/content/docs/apis/signer-metrics-api/reference/signers/pox-cycle-signer.mdx new file mode 100644 index 000000000..0fdd6d184 --- /dev/null +++ b/content/docs/apis/signer-metrics-api/reference/signers/pox-cycle-signer.mdx @@ -0,0 +1,12 @@ +--- +title: PoX Cycle Signer +sidebarTitle: PoX Cycle Signer +description: Get stats for a specific signer in a given PoX cycle. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/signer-metrics-api/reference/signers/pox-cycle-signers.mdx b/content/docs/apis/signer-metrics-api/reference/signers/pox-cycle-signers.mdx new file mode 100644 index 000000000..1138aec96 --- /dev/null +++ b/content/docs/apis/signer-metrics-api/reference/signers/pox-cycle-signers.mdx @@ -0,0 +1,12 @@ +--- +title: PoX Cycle Signers +sidebarTitle: PoX Cycle Signers +description: Get a list of signers in a given PoX cycle. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/architecture.mdx b/content/docs/apis/stacks-blockchain-api/architecture.mdx new file mode 100644 index 000000000..31307bc24 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/architecture.mdx @@ -0,0 +1,56 @@ +--- +title: Architecture +description: Understand the architecture of the Stacks Blockchain API. +--- + +![Stacks Blockchain API architecture](/images/api/architecture.svg) + +## RPC Endpoints + +The `stacks-node` has its own minimal set of http endpoints referred to as `RPC endpoints`. + +- The `stacks-blockchain-api` allows clients to access RPC endpoints by proxying requests to a load-balanced pool of `stacks-nodes`. +- For more details on RPC endpoints, see: [RPC Endpoints Documentation](https://github.com/blockstack/stacks-blockchain/blob/master/docs/rpc-endpoints.md) +- Common RPC endpoints include: + - `POST /v2/transactions` - Broadcast a transaction + - `GET /v2/pox` - Retrieve current Proof of Transfer (PoX) relevant information + - `POST /v2/contracts/call-read//` - Evaluate and return the result of calling a Clarity function + - `POST /v2/fees/transaction` - Evaluate a given transaction and provide transaction fee estimation data + - `GET /v2/accounts/
` - Fetch the current nonce required for creating transactions + +## Additional Endpoints + +The Stacks Blockchain API implements additional endpoints that provide data unavailable directly from Stacks nodes due to various constraints. + +- The `stacks-node` may not persist certain data or may not serve it efficiently to many clients. For instance, while it can return the current STX balance of an account, it cannot provide a history of account transactions. +- The API implements the Rosetta specification by Coinbase, an open standard designed to simplify blockchain deployment and interaction. More information can be found at [Rosetta API](https://www.rosetta-api.org/). +- The API includes support for the Blockchain Naming System (BNS) endpoints. Details are available at [BNS Documentation](https://docs.stacks.co/clarity/example-contracts/bns). +- For Express.js routes, see the directory `/src/api/routes`. + +The API creates an "event observer" http server which listens for events from a stacks-node "event emitter". + +Events are HTTP POST requests containing: + - Blocks + - Transactions + +Byproducts of executed transactions such as: + - Asset transfers + - Smart-contract log data + - Execution cost data + +The API processes and stores these events as relational data in PostgreSQL. For the "event observer" code, see `/src/event-stream`. + +## OpenAPI and JSON Schema + +All http endpoints and responses are defined in OpenAPI and JSON Schema. + +- See `/docs/openapi.yaml` +- These are used to auto-generate the docs at https://hirosystems.github.io/stacks-blockchain-api/ +- JSON Schemas are converted into TypeScript interfaces, which are used internally by the db controller module to transform SQL query results into the correct object shapes. +- OpenAPI and JSON Schemas are also used to generate a standalone `@stacks/blockchain-api-client`. + +## Development Setup + +The easiest/quickest way to develop in this repo is using the VS Code debugger. It uses docker-compose to set up a stacks-node and Postgres instance. + +Alternatively, you can run `npm run dev:integrated` which does the same thing but without a debugger. diff --git a/content/docs/apis/stacks-blockchain-api/authentication.mdx b/content/docs/apis/stacks-blockchain-api/authentication.mdx new file mode 100644 index 000000000..acbcb7d42 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/authentication.mdx @@ -0,0 +1,19 @@ +--- +title: Authentication +description: Authenticate with the Stacks Blockchain API. +--- + +import { SecondaryCard } from '@/components/card'; + +The Stacks Blockchain API expands the intentionally minimal RPC endpoints available in Stacks nodes and indexes, cleans, and enriches on-chain data to put everything you need at your fingertips. Who knew getting reliable blockchain data could be this easy? + +## Popular endpoints + + +:::callout +type: help +### Need help building with the Stacks Blockchain API? +Reach out to us on the #api channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET. +::: + + diff --git a/content/docs/apis/stacks-blockchain-api/basic-usage.mdx b/content/docs/apis/stacks-blockchain-api/basic-usage.mdx new file mode 100644 index 000000000..693d34cef --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/basic-usage.mdx @@ -0,0 +1,18 @@ +--- +title: Basic usage +description: Get started with Hiro APIs. +--- + +import { SecondaryCard } from '@/components/card'; + +The Stacks Blockchain API expands the intentionally minimal RPC endpoints available in Stacks nodes and indexes, cleans, and enriches on-chain data to put everything you need at your fingertips. Who knew getting reliable blockchain data could be this easy? + +## Popular endpoints + +:::callout +type: help +### Need help building with the Stacks Blockchain API? +Reach out to us on the #api channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET. +::: + + diff --git a/content/docs/apis/stacks-blockchain-api/index.mdx b/content/docs/apis/stacks-blockchain-api/index.mdx new file mode 100644 index 000000000..e5f2a7f8c --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/index.mdx @@ -0,0 +1,40 @@ +--- +title: Stacks Blockchain API +sidebarTitle: Overview +description: The Stacks API provides fast, reliable data for the Stacks blockchain via an easy-to-use REST interface. +llm: false +--- + +The Stacks API is a service that helps you with the complete ingestion of Stacks blockchain data. Using our endpoints, you can retrieve transaction data, smart contract information, account balances, block details, and more. + +The Stacks API uses REST endpoints and cached responses in order to optimize performance and reduce unnecessary requests. Reliable, consistent blockchain data, one request away. + +## Popular endpoints + + + + + + + +## Related tools + +- **[Chainhook](/tools/chainhook)**: Want to stream custom blockchain events? Set up Chainhook to filter and stream contract deployments and other blockchain events. +- **[Clarinet](/tools/clarinet)**: Looking to develop and test smart contracts? Clarinet provides a local development environment for Stacks. +- **[Stacks Explorer](https://explorer.hiro.so/)**: The Stacks API powers Hiro's Stacks Explorer, which lets you rapidly discover transactions and verify on-chain activity. + +--- + +Need help building with Stacks API? Reach out to us on the `#stacks` channel on Discord. Or join us at our weekly office hours on Discord every Monday at 11am ET. diff --git a/content/docs/apis/stacks-blockchain-api/meta.json b/content/docs/apis/stacks-blockchain-api/meta.json new file mode 100644 index 000000000..fde45db1e --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/meta.json @@ -0,0 +1,16 @@ +{ + "title": "APIs", + "root": true, + "pages": [ + "---Stacks Blockchain API---", + "index", + "getting-started", + "architecture", + "authentication", + "pagination", + "none-handling", + "requesting-proofs", + "---Reference---", + "...reference" + ] +} diff --git a/content/docs/stacks/api/concepts/nonce-handling.mdx b/content/docs/apis/stacks-blockchain-api/nonce-handling.mdx similarity index 100% rename from content/docs/stacks/api/concepts/nonce-handling.mdx rename to content/docs/apis/stacks-blockchain-api/nonce-handling.mdx diff --git a/content/docs/stacks/api/concepts/pagination.mdx b/content/docs/apis/stacks-blockchain-api/pagination.mdx similarity index 99% rename from content/docs/stacks/api/concepts/pagination.mdx rename to content/docs/apis/stacks-blockchain-api/pagination.mdx index 32a4c81de..da1f8b9bb 100644 --- a/content/docs/stacks/api/concepts/pagination.mdx +++ b/content/docs/apis/stacks-blockchain-api/pagination.mdx @@ -3,6 +3,8 @@ title: Pagination description: Learn how to paginate through lists. --- +## Usage + To make API responses more compact, lists returned by the API are paginated. For lists, the response body includes: - `limit`: The number of list items return per response diff --git a/content/docs/apis/stacks-blockchain-api/reference/accounts/assets.mdx b/content/docs/apis/stacks-blockchain-api/reference/accounts/assets.mdx new file mode 100644 index 000000000..4fa1710cd --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/accounts/assets.mdx @@ -0,0 +1,12 @@ +--- +title: Get account assets +sidebarTitle: Assets +description: Retrieves a list of all asset events associated with an account or a contract identifier. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/accounts/balances.mdx b/content/docs/apis/stacks-blockchain-api/reference/accounts/balances.mdx new file mode 100644 index 000000000..372e4a9d0 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/accounts/balances.mdx @@ -0,0 +1,12 @@ +--- +title: Get account balances +sidebarTitle: Balances +description: Retrieves account balance information, including STX, fungible, and non-fungible tokens. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/accounts/inbound-stx-transfers.mdx b/content/docs/apis/stacks-blockchain-api/reference/accounts/inbound-stx-transfers.mdx new file mode 100644 index 000000000..8e60215a1 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/accounts/inbound-stx-transfers.mdx @@ -0,0 +1,12 @@ +--- +title: Get inbound STX transfers +sidebarTitle: Inbound STX transfers +description: Retrieves a list of STX transfers with memos to the given principal. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/accounts/info.mdx b/content/docs/apis/stacks-blockchain-api/reference/accounts/info.mdx new file mode 100644 index 000000000..8f243df9a --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/accounts/info.mdx @@ -0,0 +1,13 @@ +--- +title: Get account info +sidebarTitle: Info +description: Retrieves the account data for a given account or contract identifier. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/accounts/latest-nonce.mdx b/content/docs/apis/stacks-blockchain-api/reference/accounts/latest-nonce.mdx new file mode 100644 index 000000000..b96bafc6c --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/accounts/latest-nonce.mdx @@ -0,0 +1,12 @@ +--- +title: Get the latest nonce +sidebarTitle: Latest nonce +description: Retrieves the latest nonce values used by an account by inspecting the mempool and anchored transactions. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/accounts/meta.json b/content/docs/apis/stacks-blockchain-api/reference/accounts/meta.json new file mode 100644 index 000000000..e00ad0542 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/accounts/meta.json @@ -0,0 +1,15 @@ +{ + "title": "Accounts", + "pages": [ + "info", + "assets", + "balances", + "stx-balances", + "inbound-stx-transfers", + "transactions", + "transactions-with-transfers", + "transaction-with-transfers", + "latest-nonce" + ], + "defaultOpen": false +} \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/accounts/stx-balances.mdx b/content/docs/apis/stacks-blockchain-api/reference/accounts/stx-balances.mdx new file mode 100644 index 000000000..1fb09b7eb --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/accounts/stx-balances.mdx @@ -0,0 +1,12 @@ +--- +title: Get account STX balance +sidebarTitle: STX balance +description: Retrieves the STX token balance for a specified address or contract identifier. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/accounts/transaction-with-transfers.mdx b/content/docs/apis/stacks-blockchain-api/reference/accounts/transaction-with-transfers.mdx new file mode 100644 index 000000000..7e3186c67 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/accounts/transaction-with-transfers.mdx @@ -0,0 +1,12 @@ +--- +title: Get account transaction details with transfers +sidebarTitle: Transaction details with transfers +description: Retrieves transaction details for a specific transaction including STX transfers for each transaction. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/accounts/transactions-with-transfers.mdx b/content/docs/apis/stacks-blockchain-api/reference/accounts/transactions-with-transfers.mdx new file mode 100644 index 000000000..5873a647b --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/accounts/transactions-with-transfers.mdx @@ -0,0 +1,12 @@ +--- +title: Get account transactions with transfers +sidebarTitle: Transactions with transfers +description: Retrieves transactions for a specific account including STX transfers for each transaction. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/accounts/transactions.mdx b/content/docs/apis/stacks-blockchain-api/reference/accounts/transactions.mdx new file mode 100644 index 000000000..5b1213b65 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/accounts/transactions.mdx @@ -0,0 +1,12 @@ +--- +title: Get account transactions +sidebarTitle: Transactions +description: Retrieves transactions for a specific account. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/blocks/average-times.mdx b/content/docs/apis/stacks-blockchain-api/reference/blocks/average-times.mdx new file mode 100644 index 000000000..38a77a175 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/blocks/average-times.mdx @@ -0,0 +1,12 @@ +--- +title: Get average block times +sidebarTitle: Average times +description: Retrieves average block times. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/blocks/block-by-burn-block-hash.mdx b/content/docs/apis/stacks-blockchain-api/reference/blocks/block-by-burn-block-hash.mdx new file mode 100644 index 000000000..6ec1105bf --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/blocks/block-by-burn-block-hash.mdx @@ -0,0 +1,12 @@ +--- +title: Get block by burnchain block hash +sidebarTitle: Block by burn block hash +description: Retrieves block details of a specific block for a given burnchain block hash. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/blocks/block-by-burn-block-height.mdx b/content/docs/apis/stacks-blockchain-api/reference/blocks/block-by-burn-block-height.mdx new file mode 100644 index 000000000..9485c6cdd --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/blocks/block-by-burn-block-height.mdx @@ -0,0 +1,12 @@ +--- +title: Get block by burnchain block height +sidebarTitle: Block by burn block height +description: Retrieves block details of a specific block for a given burnchain block height. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/blocks/block-by-hash.mdx b/content/docs/apis/stacks-blockchain-api/reference/blocks/block-by-hash.mdx new file mode 100644 index 000000000..7183a33e3 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/blocks/block-by-hash.mdx @@ -0,0 +1,12 @@ +--- +title: Get block by hash +sidebarTitle: Block by hash +description: Retrieves block details of a specific block for a given chain height. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/blocks/block-by-height.mdx b/content/docs/apis/stacks-blockchain-api/reference/blocks/block-by-height.mdx new file mode 100644 index 000000000..d21f4526c --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/blocks/block-by-height.mdx @@ -0,0 +1,12 @@ +--- +title: Get block by height +sidebarTitle: Block by height +description: Retrieves block details of a specific block for a given chain height. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/blocks/block-proposal.mdx b/content/docs/apis/stacks-blockchain-api/reference/blocks/block-proposal.mdx new file mode 100644 index 000000000..5e9455640 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/blocks/block-proposal.mdx @@ -0,0 +1,13 @@ +--- +title: Validate proposed block +sidebarTitle: Block proposal +description: Validate a proposed Stacks block. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/blocks/get-block.mdx b/content/docs/apis/stacks-blockchain-api/reference/blocks/get-block.mdx new file mode 100644 index 000000000..e6be690de --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/blocks/get-block.mdx @@ -0,0 +1,12 @@ +--- +title: Get block +sidebarTitle: Block +description: Retrieves a single block. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/blocks/get-blocks-by-burn-block.mdx b/content/docs/apis/stacks-blockchain-api/reference/blocks/get-blocks-by-burn-block.mdx new file mode 100644 index 000000000..d1083c3db --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/blocks/get-blocks-by-burn-block.mdx @@ -0,0 +1,12 @@ +--- +title: Get blocks by burn block +sidebarTitle: Blocks by burn block +description: Retrieves a list of blocks confirmed by a specific burn block. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/blocks/get-blocks.mdx b/content/docs/apis/stacks-blockchain-api/reference/blocks/get-blocks.mdx new file mode 100644 index 000000000..3e2f0a54d --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/blocks/get-blocks.mdx @@ -0,0 +1,12 @@ +--- +title: Get blocks +sidebarTitle: Blocks +description: Retrieves a list of recently mined blocks. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/blocks/meta.json b/content/docs/apis/stacks-blockchain-api/reference/blocks/meta.json new file mode 100644 index 000000000..267349366 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/blocks/meta.json @@ -0,0 +1,16 @@ +{ + "title": "Blocks", + "pages": [ + "get-block", + "get-blocks", + "get-blocks-by-burn-block", + "average-times", + "recent-blocks", + "block-by-hash", + "block-by-height", + "block-by-burn-block-hash", + "block-by-burn-block-height", + "block-proposal" + ], + "defaultOpen": false +} \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/blocks/recent-blocks.mdx b/content/docs/apis/stacks-blockchain-api/reference/blocks/recent-blocks.mdx new file mode 100644 index 000000000..67110d661 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/blocks/recent-blocks.mdx @@ -0,0 +1,12 @@ +--- +title: Get recent blocks +sidebarTitle: Recent blocks +description: Retrieves a list of recently mined blocks. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/burn-blocks/get-burn-block.mdx b/content/docs/apis/stacks-blockchain-api/reference/burn-blocks/get-burn-block.mdx new file mode 100644 index 000000000..b000df29a --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/burn-blocks/get-burn-block.mdx @@ -0,0 +1,12 @@ +--- +title: Get burn block +sidebarTitle: Burn block +description: Retrieves a single burn block. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/burn-blocks/get-burn-blocks.mdx b/content/docs/apis/stacks-blockchain-api/reference/burn-blocks/get-burn-blocks.mdx new file mode 100644 index 000000000..3e78c83f0 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/burn-blocks/get-burn-blocks.mdx @@ -0,0 +1,12 @@ +--- +title: Get burn blocks +sidebarTitle: Burn blocks +description: Retrieves a list of recent burn blocks. +full: true +--- + + diff --git a/content/docs/stacks/api/burn-blocks/meta.json b/content/docs/apis/stacks-blockchain-api/reference/burn-blocks/meta.json similarity index 100% rename from content/docs/stacks/api/burn-blocks/meta.json rename to content/docs/apis/stacks-blockchain-api/reference/burn-blocks/meta.json diff --git a/content/docs/stacks/api/faucets/meta.json b/content/docs/apis/stacks-blockchain-api/reference/faucets/meta.json similarity index 100% rename from content/docs/stacks/api/faucets/meta.json rename to content/docs/apis/stacks-blockchain-api/reference/faucets/meta.json diff --git a/content/docs/apis/stacks-blockchain-api/reference/faucets/stx.mdx b/content/docs/apis/stacks-blockchain-api/reference/faucets/stx.mdx new file mode 100644 index 000000000..fde7043d6 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/faucets/stx.mdx @@ -0,0 +1,12 @@ +--- +title: STX Testnet tokens +sidebarTitle: STX +description: Delivers testnet STX tokens to a specified address. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/fees/estimate.mdx b/content/docs/apis/stacks-blockchain-api/reference/fees/estimate.mdx new file mode 100644 index 000000000..7807fd031 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/fees/estimate.mdx @@ -0,0 +1,13 @@ +--- +title: Get approximate fees for the given transaction +sidebarTitle: Estimate +description: Get an estimated fee for the supplied transaction. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/fees/fee-rate.mdx b/content/docs/apis/stacks-blockchain-api/reference/fees/fee-rate.mdx new file mode 100644 index 000000000..82454cc32 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/fees/fee-rate.mdx @@ -0,0 +1,12 @@ +--- +title: Get fee rate +sidebarTitle: Fee rate +description: Retrieves an estimated fee rate for transactions. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/fees/meta.json b/content/docs/apis/stacks-blockchain-api/reference/fees/meta.json new file mode 100644 index 000000000..722e8ddab --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/fees/meta.json @@ -0,0 +1,5 @@ +{ + "title": "Fees", + "pages": ["fee-rate", "estimate", "transfer-estimate"], + "defaultOpen": false +} \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/fees/transfer-estimate.mdx b/content/docs/apis/stacks-blockchain-api/reference/fees/transfer-estimate.mdx new file mode 100644 index 000000000..5e2fc4241 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/fees/transfer-estimate.mdx @@ -0,0 +1,13 @@ +--- +title: Get transfer fee estimate +sidebarTitle: Transfer estimate +description: Retrieves an estimated fee rate for STX transfer transactions. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/info/circulating-stx-supply-in-plain-text.mdx b/content/docs/apis/stacks-blockchain-api/reference/info/circulating-stx-supply-in-plain-text.mdx new file mode 100644 index 000000000..ccde6ba9e --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/info/circulating-stx-supply-in-plain-text.mdx @@ -0,0 +1,12 @@ +--- +title: Get circulating STX supply in plain text format +sidebarTitle: Circulating STX supply in plain text format +description: Retrieves the circulating STX supply as plain text. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/info/core-api.mdx b/content/docs/apis/stacks-blockchain-api/reference/info/core-api.mdx new file mode 100644 index 000000000..7c72656e9 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/info/core-api.mdx @@ -0,0 +1,13 @@ +--- +title: Get core API info +sidebarTitle: Core API info +description: Retrieves information about the Core API, including the server version. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/info/legacy-total-and-unlocked-stx-supply.mdx b/content/docs/apis/stacks-blockchain-api/reference/info/legacy-total-and-unlocked-stx-supply.mdx new file mode 100644 index 000000000..b23fcc5dc --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/info/legacy-total-and-unlocked-stx-supply.mdx @@ -0,0 +1,12 @@ +--- +title: Get total and unlocked STX supply (legacy) +sidebarTitle: Total and unlocked STX supply (legacy) +description: Retrieves the total and unlocked STX supply in legacy format 1.0 API. +full: true +--- + + diff --git a/content/docs/stacks/api/info/meta.json b/content/docs/apis/stacks-blockchain-api/reference/info/meta.json similarity index 100% rename from content/docs/stacks/api/info/meta.json rename to content/docs/apis/stacks-blockchain-api/reference/info/meta.json diff --git a/content/docs/apis/stacks-blockchain-api/reference/info/network-block-time.mdx b/content/docs/apis/stacks-blockchain-api/reference/info/network-block-time.mdx new file mode 100644 index 000000000..d81134907 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/info/network-block-time.mdx @@ -0,0 +1,12 @@ +--- +title: Get the network target block time +sidebarTitle: The network target block time +description: Retrieves the target block times for mainnet and testnet. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/info/network-given-block-time.mdx b/content/docs/apis/stacks-blockchain-api/reference/info/network-given-block-time.mdx new file mode 100644 index 000000000..c410f8842 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/info/network-given-block-time.mdx @@ -0,0 +1,12 @@ +--- +title: Get a given network's target block time +sidebarTitle: A given network's target block time +description: Retrieves the target block time for a given network. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/info/status.mdx b/content/docs/apis/stacks-blockchain-api/reference/info/status.mdx new file mode 100644 index 000000000..e6992fdc5 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/info/status.mdx @@ -0,0 +1,12 @@ +--- +title: Get API status +sidebarTitle: API status +description: Retrieves the running status of the Stacks Blockchain API. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/info/total-and-unlocked-stx-supply.mdx b/content/docs/apis/stacks-blockchain-api/reference/info/total-and-unlocked-stx-supply.mdx new file mode 100644 index 000000000..8e8be01aa --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/info/total-and-unlocked-stx-supply.mdx @@ -0,0 +1,12 @@ +--- +title: Get total and unlocked STX supply +sidebarTitle: Total and unlocked STX supply +description: Retrieves the total and unlocked STX supply. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/info/total-stx-supply-in-plain-text.mdx b/content/docs/apis/stacks-blockchain-api/reference/info/total-stx-supply-in-plain-text.mdx new file mode 100644 index 000000000..cbf3f999e --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/info/total-stx-supply-in-plain-text.mdx @@ -0,0 +1,12 @@ +--- +title: Get total STX supply in plain text format +sidebarTitle: Total STX supply in plain text format +description: Retrieves the total STX supply as plain text. +full: true +--- + + diff --git a/content/docs/stacks/api/mempool/meta.json b/content/docs/apis/stacks-blockchain-api/reference/mempool/meta.json similarity index 100% rename from content/docs/stacks/api/mempool/meta.json rename to content/docs/apis/stacks-blockchain-api/reference/mempool/meta.json diff --git a/content/docs/apis/stacks-blockchain-api/reference/mempool/transaction-fee-priorities.mdx b/content/docs/apis/stacks-blockchain-api/reference/mempool/transaction-fee-priorities.mdx new file mode 100644 index 000000000..819f22e26 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/mempool/transaction-fee-priorities.mdx @@ -0,0 +1,12 @@ +--- +title: Get transaction fee priorities +sidebarTitle: Transaction fee priorities +description: Retrieves estimated fee priorities (in micro-STX) for all transactions that are currently in the mempool. Also returns priorities separated by transaction type. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/nakamoto/meta.json b/content/docs/apis/stacks-blockchain-api/reference/nakamoto/meta.json new file mode 100644 index 000000000..1bcd2d42e --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/nakamoto/meta.json @@ -0,0 +1,9 @@ +{ + "title": "Nakamoto", + "pages": [ + "nakamoto-block", + "tenure-blocks", + "tenure-metadata" + ], + "defaultOpen": false +} \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/nakamoto/nakamoto-block.mdx b/content/docs/apis/stacks-blockchain-api/reference/nakamoto/nakamoto-block.mdx new file mode 100644 index 000000000..7e6448642 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/nakamoto/nakamoto-block.mdx @@ -0,0 +1,13 @@ +--- +title: Get Nakamoto block +sidebarTitle: Nakamoto block +description: Fetch a Nakamoto block by its index block hash. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/nakamoto/tenure-blocks.mdx b/content/docs/apis/stacks-blockchain-api/reference/nakamoto/tenure-blocks.mdx new file mode 100644 index 000000000..641aa75be --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/nakamoto/tenure-blocks.mdx @@ -0,0 +1,13 @@ +--- +title: Get Nakamoto tenure blocks +sidebarTitle: Nakamoto tenure blocks +description: Fetch a sequence of Nakamoto blocks in a tenure. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/nakamoto/tenure-metadata.mdx b/content/docs/apis/stacks-blockchain-api/reference/nakamoto/tenure-metadata.mdx new file mode 100644 index 000000000..d0881a189 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/nakamoto/tenure-metadata.mdx @@ -0,0 +1,13 @@ +--- +title: Get Nakamoto tenure metadata +sidebarTitle: Nakamoto tenure metadata +description: Fetch metadata about the ongoing Nakamoto tenure. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/names/historical-zonefile.mdx b/content/docs/apis/stacks-blockchain-api/reference/names/historical-zonefile.mdx new file mode 100644 index 000000000..7ebe1ae4f --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/names/historical-zonefile.mdx @@ -0,0 +1,12 @@ +--- +title: Get historical zone file +sidebarTitle: Historical zone file +description: Retrieves the historical zone file for a specific name. +full: true +--- + + diff --git a/content/docs/stacks/api/names/meta.json b/content/docs/apis/stacks-blockchain-api/reference/names/meta.json similarity index 100% rename from content/docs/stacks/api/names/meta.json rename to content/docs/apis/stacks-blockchain-api/reference/names/meta.json diff --git a/content/docs/apis/stacks-blockchain-api/reference/names/name-details.mdx b/content/docs/apis/stacks-blockchain-api/reference/names/name-details.mdx new file mode 100644 index 000000000..2f391f295 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/names/name-details.mdx @@ -0,0 +1,12 @@ +--- +title: Get name details +sidebarTitle: Name details +description: Retrieves details of a given name including the address, status and last transaction ID. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/names/name-subdomains.mdx b/content/docs/apis/stacks-blockchain-api/reference/names/name-subdomains.mdx new file mode 100644 index 000000000..f92217200 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/names/name-subdomains.mdx @@ -0,0 +1,12 @@ +--- +title: Get name subdomains +sidebarTitle: Name subdomains +description: Retrieves the list of subdomains for a specific name. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/names/name-zonefile.mdx b/content/docs/apis/stacks-blockchain-api/reference/names/name-zonefile.mdx new file mode 100644 index 000000000..40364f793 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/names/name-zonefile.mdx @@ -0,0 +1,12 @@ +--- +title: Get name zone file +sidebarTitle: Name zone file +description: Retrieves the zone file for a specific name. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/names/names.mdx b/content/docs/apis/stacks-blockchain-api/reference/names/names.mdx new file mode 100644 index 000000000..24a64c229 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/names/names.mdx @@ -0,0 +1,12 @@ +--- +title: Get all names +sidebarTitle: All names +description: Retrieves a list of all names known to the node. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/names/namespace-names.mdx b/content/docs/apis/stacks-blockchain-api/reference/names/namespace-names.mdx new file mode 100644 index 000000000..a4c1c7a91 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/names/namespace-names.mdx @@ -0,0 +1,12 @@ +--- +title: Get namespace names +sidebarTitle: Namespace names +description: Retrieves a list of names within a given namespace. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/names/namespaces.mdx b/content/docs/apis/stacks-blockchain-api/reference/names/namespaces.mdx new file mode 100644 index 000000000..91c2b530e --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/names/namespaces.mdx @@ -0,0 +1,12 @@ +--- +title: Get all namespaces +sidebarTitle: All namespaces +description: Retrieves a list of all namespaces known to the node. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/names/owned-by-address.mdx b/content/docs/apis/stacks-blockchain-api/reference/names/owned-by-address.mdx new file mode 100644 index 000000000..3d13ada3b --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/names/owned-by-address.mdx @@ -0,0 +1,12 @@ +--- +title: Get names owned by address +sidebarTitle: Names owned by address +description: Retrieves the list of names owned by a specific address. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/non-fungible-tokens/history.mdx b/content/docs/apis/stacks-blockchain-api/reference/non-fungible-tokens/history.mdx new file mode 100644 index 000000000..4e9c4f88f --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/non-fungible-tokens/history.mdx @@ -0,0 +1,12 @@ +--- +title: Get non-fungible token history +sidebarTitle: Non-fungible token history +description: Retrieves the history of a non-fungible token. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/non-fungible-tokens/holdings.mdx b/content/docs/apis/stacks-blockchain-api/reference/non-fungible-tokens/holdings.mdx new file mode 100644 index 000000000..8267e2523 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/non-fungible-tokens/holdings.mdx @@ -0,0 +1,12 @@ +--- +title: Get non-fungible token holdings +sidebarTitle: Non-fungible token holdings +description: Retrieves a list of non-fungible tokens owned by the given principal (STX address or smart contract ID). +full: true +--- + + diff --git a/content/docs/stacks/api/non-fungible-tokens/meta.json b/content/docs/apis/stacks-blockchain-api/reference/non-fungible-tokens/meta.json similarity index 100% rename from content/docs/stacks/api/non-fungible-tokens/meta.json rename to content/docs/apis/stacks-blockchain-api/reference/non-fungible-tokens/meta.json diff --git a/content/docs/apis/stacks-blockchain-api/reference/non-fungible-tokens/mints.mdx b/content/docs/apis/stacks-blockchain-api/reference/non-fungible-tokens/mints.mdx new file mode 100644 index 000000000..49f8af4ec --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/non-fungible-tokens/mints.mdx @@ -0,0 +1,12 @@ +--- +title: Get non-fungible token mints +sidebarTitle: Non-fungible token mints +description: Retrieves a list of non-fungible token mints for a given asset identifier. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/cycle.mdx b/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/cycle.mdx new file mode 100644 index 000000000..69f565c4b --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/cycle.mdx @@ -0,0 +1,12 @@ +--- +title: Get PoX cycle +sidebarTitle: PoX cycle +description: Retrieves details for a PoX cycle. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/cycles.mdx b/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/cycles.mdx new file mode 100644 index 000000000..cdce80004 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/cycles.mdx @@ -0,0 +1,12 @@ +--- +title: Get PoX cycles +sidebarTitle: PoX cycles +description: Retrieves a list of PoX cycles. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/meta.json b/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/meta.json new file mode 100644 index 000000000..604341a99 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/meta.json @@ -0,0 +1,13 @@ +{ + "title": "Proof of Transfer", + "pages": [ + "cycles", + "cycle", + "signers-in-cycle", + "signer-in-cycle", + "stackers-for-signer-in-cycle", + "pox-details", + "stacker-set" + ], + "defaultOpen": false +} \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/pox-details.mdx b/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/pox-details.mdx new file mode 100644 index 000000000..876f774bc --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/pox-details.mdx @@ -0,0 +1,13 @@ +--- +title: Get Proof-of-Transfer details +sidebarTitle: Proof-of-Transfer details +description: Retrieves Proof-of-Transfer (PoX) information. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/signer-in-cycle.mdx b/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/signer-in-cycle.mdx new file mode 100644 index 000000000..4bbe54a6c --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/signer-in-cycle.mdx @@ -0,0 +1,12 @@ +--- +title: Get signer in PoX cycle +sidebarTitle: Signer in PoX cycle +description: Retrieves details for a signer in a PoX cycle. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/signers-in-cycle.mdx b/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/signers-in-cycle.mdx new file mode 100644 index 000000000..5858bbd8f --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/signers-in-cycle.mdx @@ -0,0 +1,12 @@ +--- +title: Get signers in PoX cycle +sidebarTitle: Signers in PoX cycle +description: Retrieves a list of signers in a PoX cycle. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/stacker-set.mdx b/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/stacker-set.mdx new file mode 100644 index 000000000..a73203b45 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/stacker-set.mdx @@ -0,0 +1,13 @@ +--- +title: Get stacker and signer set information +sidebarTitle: Stacker and signer set information +description: Retrieves stacker and signer set information for a given cycle. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/stackers-for-signer-in-cycle.mdx b/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/stackers-for-signer-in-cycle.mdx new file mode 100644 index 000000000..69d088df7 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/proof-of-transfer/stackers-for-signer-in-cycle.mdx @@ -0,0 +1,12 @@ +--- +title: Get stackers for signer in PoX cycle +sidebarTitle: Stackers for signer in PoX cycle +description: Retrieves a list of stackers for a signer in a PoX cycle. +full: true +--- + + diff --git a/content/docs/stacks/api/search/meta.json b/content/docs/apis/stacks-blockchain-api/reference/search/meta.json similarity index 100% rename from content/docs/stacks/api/search/meta.json rename to content/docs/apis/stacks-blockchain-api/reference/search/meta.json diff --git a/content/docs/apis/stacks-blockchain-api/reference/search/search-by-id.mdx b/content/docs/apis/stacks-blockchain-api/reference/search/search-by-id.mdx new file mode 100644 index 000000000..a0a07a5a0 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/search/search-by-id.mdx @@ -0,0 +1,12 @@ +--- +title: Search by ID +sidebarTitle: Search by ID +description: Search blocks, transactions, contracts, or accounts by hash/ID. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/by-trait.mdx b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/by-trait.mdx new file mode 100644 index 000000000..19cffbc4b --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/by-trait.mdx @@ -0,0 +1,12 @@ +--- +title: Get contracts by trait +sidebarTitle: Contracts by trait +description: Retrieves a list of contracts based on the following traits listed in JSON format - functions, variables, maps, fungible tokens and non-fungible tokens. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/constants.mdx b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/constants.mdx new file mode 100644 index 000000000..dc3c4b518 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/constants.mdx @@ -0,0 +1,13 @@ +--- +title: Get constant value +sidebarTitle: Constant value +description: Get the value of a constant inside a contract. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/events.mdx b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/events.mdx new file mode 100644 index 000000000..3874abdf5 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/events.mdx @@ -0,0 +1,12 @@ +--- +title: Get contract events +sidebarTitle: Contract events +description: Retrieves a list of events that have been triggered by a given smart contract. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/info.mdx b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/info.mdx new file mode 100644 index 000000000..d61f7cfe4 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/info.mdx @@ -0,0 +1,12 @@ +--- +title: Get contract info +sidebarTitle: Contract info +description: Retrieves details for a specific smart contract. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/interface.mdx b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/interface.mdx new file mode 100644 index 000000000..d7c3c82b5 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/interface.mdx @@ -0,0 +1,13 @@ +--- +title: Get contract interface +sidebarTitle: Contract interface +description: Retrieves a list of functions, variables, maps, fungible tokens and non-fungible tokens for a given smart contract. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/map-entry.mdx b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/map-entry.mdx new file mode 100644 index 000000000..f0bcfdb15 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/map-entry.mdx @@ -0,0 +1,13 @@ +--- +title: Get contract map entry +sidebarTitle: Contract map entry +description: Retrieves a specific entry from a contract data map. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/meta.json b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/meta.json new file mode 100644 index 000000000..6a2f04274 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/meta.json @@ -0,0 +1,17 @@ +{ + "title": "Smart Contracts", + "pages": [ + "status", + "info", + "source", + "by-trait", + "interface", + "map-entry", + "read-only", + "events", + "constants", + "traits" + ], + "defaultOpen": false +} + diff --git a/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/read-only.mdx b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/read-only.mdx new file mode 100644 index 000000000..5213bac2b --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/read-only.mdx @@ -0,0 +1,13 @@ +--- +title: Call read-only function +sidebarTitle: Call read-only function +description: Calls a read-only public function on a given smart contract. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/source.mdx b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/source.mdx new file mode 100644 index 000000000..71782f25e --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/source.mdx @@ -0,0 +1,13 @@ +--- +title: Get contract source +sidebarTitle: Contract source +description: Retrieves the Clarity source code of a given contract, along with the block height it was published in, and the MARF proof for the data. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/status.mdx b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/status.mdx new file mode 100644 index 000000000..a764a517d --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/status.mdx @@ -0,0 +1,12 @@ +--- +title: Get contracts status +sidebarTitle: Contracts status +description: Retrieves the deployment status of multiple smart contracts. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/traits.mdx b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/traits.mdx new file mode 100644 index 000000000..34028b212 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/smart-contracts/traits.mdx @@ -0,0 +1,13 @@ +--- +title: Get trait implementation details +sidebarTitle: Trait implementation details +description: Determine whether or not a specified trait is implemented (either explicitly or implicitly) within a given contract. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/stacking-pool/members.mdx b/content/docs/apis/stacks-blockchain-api/reference/stacking-pool/members.mdx new file mode 100644 index 000000000..76bd9e06c --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/stacking-pool/members.mdx @@ -0,0 +1,12 @@ +--- +title: Get stacking pool members +sidebarTitle: Stacking pool members +description: Retrieves the list of stacking pool members for a given delegator principal. +full: true +--- + + diff --git a/content/docs/stacks/api/stacking-pool/meta.json b/content/docs/apis/stacks-blockchain-api/reference/stacking-pool/meta.json similarity index 100% rename from content/docs/stacks/api/stacking-pool/meta.json rename to content/docs/apis/stacks-blockchain-api/reference/stacking-pool/meta.json diff --git a/content/docs/stacks/api/stacking-rewards/meta.json b/content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/meta.json similarity index 100% rename from content/docs/stacks/api/stacking-rewards/meta.json rename to content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/meta.json diff --git a/content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/recent-burnchain-reward-recipient.mdx b/content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/recent-burnchain-reward-recipient.mdx new file mode 100644 index 000000000..72c000445 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/recent-burnchain-reward-recipient.mdx @@ -0,0 +1,12 @@ +--- +title: Get recent burnchain reward for the given recipient +sidebarTitle: Recent burnchain reward for the given recipient +description: Retrieves a list of recent burnchain (e.g. Bitcoin) rewards for the given recipient with the associated amounts and block info. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/recent-burnchain-reward-recipients.mdx b/content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/recent-burnchain-reward-recipients.mdx new file mode 100644 index 000000000..40abec579 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/recent-burnchain-reward-recipients.mdx @@ -0,0 +1,12 @@ +--- +title: Get recent burnchain reward recipients +sidebarTitle: Recent burnchain reward recipients +description: Retrieves a list of recent burnchain (e.g. Bitcoin) reward recipients with the associated amounts and block info. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/recent-reward-slot-holder-entries.mdx b/content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/recent-reward-slot-holder-entries.mdx new file mode 100644 index 000000000..35e20fca6 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/recent-reward-slot-holder-entries.mdx @@ -0,0 +1,12 @@ +--- +title: Get recent reward slot holder entries +sidebarTitle: Recent reward slot holder entries +description: Retrieves a list of the Bitcoin addresses that would validly receive Proof-of-Transfer commitments for a given reward slot holder recipient address. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/recent-reward-slot-holders.mdx b/content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/recent-reward-slot-holders.mdx new file mode 100644 index 000000000..cc9eb15a8 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/recent-reward-slot-holders.mdx @@ -0,0 +1,12 @@ +--- +title: Get recent reward slot holders +sidebarTitle: Recent reward slot holders +description: Retrieves a list of the Bitcoin addresses that would validly receive Proof-of-Transfer commitments. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/total-burnchain-rewards-for-recipient.mdx b/content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/total-burnchain-rewards-for-recipient.mdx new file mode 100644 index 000000000..fc4bd3183 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/stacking-rewards/total-burnchain-rewards-for-recipient.mdx @@ -0,0 +1,12 @@ +--- +title: Get total burnchain rewards for the given recipient +sidebarTitle: Total burnchain rewards for the given recipient +description: Retrieves the total burnchain (e.g. Bitcoin) rewards for a given recipient address. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/tokens/holders.mdx b/content/docs/apis/stacks-blockchain-api/reference/tokens/holders.mdx new file mode 100644 index 000000000..5907dd425 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/tokens/holders.mdx @@ -0,0 +1,12 @@ +--- +title: Get fungible token holders +sidebarTitle: Fungible token holders +description: Retrieves the list of fungible token holders for a given token ID. +full: true +--- + + diff --git a/content/docs/stacks/api/tokens/meta.json b/content/docs/apis/stacks-blockchain-api/reference/tokens/meta.json similarity index 100% rename from content/docs/stacks/api/tokens/meta.json rename to content/docs/apis/stacks-blockchain-api/reference/tokens/meta.json diff --git a/content/docs/apis/stacks-blockchain-api/reference/transactions/address-transactions.mdx b/content/docs/apis/stacks-blockchain-api/reference/transactions/address-transactions.mdx new file mode 100644 index 000000000..c4be01ead --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/transactions/address-transactions.mdx @@ -0,0 +1,12 @@ +--- +title: Get address transactions +sidebarTitle: Address transactions +description: Retrieves transactions sent or received by a STX address or smart contract ID. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/transactions/broadcast-transaction.mdx b/content/docs/apis/stacks-blockchain-api/reference/transactions/broadcast-transaction.mdx new file mode 100644 index 000000000..fba8b14dc --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/transactions/broadcast-transaction.mdx @@ -0,0 +1,13 @@ +--- +title: Broadcast transaction +sidebarTitle: Transaction +description: Broadcasts raw transactions on the network. +full: true +isRpc: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/transactions/details-for-transactions.mdx b/content/docs/apis/stacks-blockchain-api/reference/transactions/details-for-transactions.mdx new file mode 100644 index 000000000..5f8da7e17 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/transactions/details-for-transactions.mdx @@ -0,0 +1,12 @@ +--- +title: Get details for transactions +sidebarTitle: Details for transactions +description: Retrieves details for a list of transactions. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/transactions/events-for-an-address-transaction.mdx b/content/docs/apis/stacks-blockchain-api/reference/transactions/events-for-an-address-transaction.mdx new file mode 100644 index 000000000..2eb4c25f7 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/transactions/events-for-an-address-transaction.mdx @@ -0,0 +1,12 @@ +--- +title: Get events for an address transaction +sidebarTitle: Events for an address transaction +description: Retrieves events for a specific transaction. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/transactions/get-raw-transaction.mdx b/content/docs/apis/stacks-blockchain-api/reference/transactions/get-raw-transaction.mdx new file mode 100644 index 000000000..df6b0485c --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/transactions/get-raw-transaction.mdx @@ -0,0 +1,12 @@ +--- +title: Get raw transaction +sidebarTitle: Raw transaction +description: Retrieves a hex encoded serialized transaction for a given ID. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/transactions/get-transaction.mdx b/content/docs/apis/stacks-blockchain-api/reference/transactions/get-transaction.mdx new file mode 100644 index 000000000..a5da962f9 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/transactions/get-transaction.mdx @@ -0,0 +1,12 @@ +--- +title: Get transaction +sidebarTitle: Transaction +description: Retrieves details for a specific transaction. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/transactions/mempool-transactions.mdx b/content/docs/apis/stacks-blockchain-api/reference/transactions/mempool-transactions.mdx new file mode 100644 index 000000000..b1380d739 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/transactions/mempool-transactions.mdx @@ -0,0 +1,12 @@ +--- +title: Get mempool transactions +sidebarTitle: Mempool transactions +description: Retrieves all transactions that have been recently broadcast to the mempool. These are pending transactions awaiting confirmation. +full: true +--- + + diff --git a/content/docs/stacks/api/transactions/meta.json b/content/docs/apis/stacks-blockchain-api/reference/transactions/meta.json similarity index 100% rename from content/docs/stacks/api/transactions/meta.json rename to content/docs/apis/stacks-blockchain-api/reference/transactions/meta.json diff --git a/content/docs/apis/stacks-blockchain-api/reference/transactions/recent-transactions.mdx b/content/docs/apis/stacks-blockchain-api/reference/transactions/recent-transactions.mdx new file mode 100644 index 000000000..da5c4c922 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/transactions/recent-transactions.mdx @@ -0,0 +1,12 @@ +--- +title: Get recent transactions +sidebarTitle: Recent transactions +description: Retrieves all recently mined transactions. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/transactions/statistics-for-mempool-transactions.mdx b/content/docs/apis/stacks-blockchain-api/reference/transactions/statistics-for-mempool-transactions.mdx new file mode 100644 index 000000000..d380cb30a --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/transactions/statistics-for-mempool-transactions.mdx @@ -0,0 +1,13 @@ +--- +title: Get statistics for mempool transactions +sidebarTitle: Statistics for mempool transactions +description: Retrieves statistics for transactions in the mempool, such as counts, ages, and fees. +full: true +--- + + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/transactions/transaction-events.mdx b/content/docs/apis/stacks-blockchain-api/reference/transactions/transaction-events.mdx new file mode 100644 index 000000000..a6690ff7a --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/transactions/transaction-events.mdx @@ -0,0 +1,12 @@ +--- +title: Get transaction events +sidebarTitle: Transaction events +description: Retrieves events for a specific transaction. +full: true +--- + + diff --git a/content/docs/apis/stacks-blockchain-api/reference/transactions/transactions-by-block.mdx b/content/docs/apis/stacks-blockchain-api/reference/transactions/transactions-by-block.mdx new file mode 100644 index 000000000..84ca486c2 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/transactions/transactions-by-block.mdx @@ -0,0 +1,12 @@ +--- +title: Get transactions by block +sidebarTitle: Transactions by block +description: Retrieves transactions confirmed in a single block. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/stacks-blockchain-api/reference/transactions/transactions-for-address.mdx b/content/docs/apis/stacks-blockchain-api/reference/transactions/transactions-for-address.mdx new file mode 100644 index 000000000..78120cda6 --- /dev/null +++ b/content/docs/apis/stacks-blockchain-api/reference/transactions/transactions-for-address.mdx @@ -0,0 +1,12 @@ +--- +title: Get transactions for address +sidebarTitle: Transactions for address +description: Retrieves transactions for a specific address. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/stacks/api/concepts/requesting-proofs.mdx b/content/docs/apis/stacks-blockchain-api/requesting-proofs.mdx similarity index 98% rename from content/docs/stacks/api/concepts/requesting-proofs.mdx rename to content/docs/apis/stacks-blockchain-api/requesting-proofs.mdx index e06d4875d..595065714 100644 --- a/content/docs/stacks/api/concepts/requesting-proofs.mdx +++ b/content/docs/apis/stacks-blockchain-api/requesting-proofs.mdx @@ -3,6 +3,8 @@ title: Requesting proofs description: Understand proof requests from API endpoints. --- +## Overview + Several endpoints will request the [MARF Merkel Proof](https://github.com/stacksgov/sips/blob/main/sips/sip-004/sip-004-materialized-view.md#marf-merkle-proofs) by default. Provided with the proof, a client can verify the value, cumulative energy spent, and the number of confirmation for the response value provided by the API. diff --git a/content/docs/apis/token-metadata-api/index.mdx b/content/docs/apis/token-metadata-api/index.mdx new file mode 100644 index 000000000..8fa3588c4 --- /dev/null +++ b/content/docs/apis/token-metadata-api/index.mdx @@ -0,0 +1,40 @@ +--- +title: Token Metadata API +sidebarTitle: Overview +description: The Token Metadata API provides you with fast, reliable metadata for Stacks tokens via an easy-to-use REST interface. +llm: false +--- + +The Token Metadata API is a service that helps you with the complete ingestion of token metadata on the Stacks blockchain. Using our endpoints, you can retrieve metadata for fungible tokens, non-fungible tokens, token properties, and more. + +The Token Metadata API uses REST endpoints and cached responses in order to optimize performance and reduce unnecessary requests. Reliable, consistent token metadata, one request away. + +## Popular endpoints + + + + + + + +## Related tools + +- **[Chainhook](/tools/chainhook)**: Want to stream custom blockchain events? Set up Chainhook to filter and stream contract deployments and other blockchain events. +- **[Stacks API](/apis/stacks-blockchain-api)**: Looking for comprehensive blockchain data? The Stacks API provides transaction data, smart contract information, and account balances. +- **[Stacks Explorer](https://explorer.hiro.so/)**: The Token Metadata API powers Hiro's Stacks Explorer, which lets you rapidly discover tokens and verify metadata. + +--- + +Need help building with Token Metadata API? Reach out to us on the `#stacks` channel on Discord. Or join us at our weekly office hours on Discord every Monday at 11am ET. diff --git a/content/docs/apis/token-metadata-api/meta.json b/content/docs/apis/token-metadata-api/meta.json new file mode 100644 index 000000000..362f168c8 --- /dev/null +++ b/content/docs/apis/token-metadata-api/meta.json @@ -0,0 +1,9 @@ +{ + "title": "Token Metadata API", + "root": true, + "pages": [ + "index", + "---Reference---", + "...reference" + ] +} diff --git a/content/docs/apis/token-metadata-api/reference/info/index.mdx b/content/docs/apis/token-metadata-api/reference/info/index.mdx new file mode 100644 index 000000000..5bf7b0e10 --- /dev/null +++ b/content/docs/apis/token-metadata-api/reference/info/index.mdx @@ -0,0 +1,6 @@ +--- +title: Info +index: true +full: true +description: Retrieves information about the Token Metadata API, including the server version. +--- diff --git a/content/docs/stacks/token-metadata-api/info/meta.json b/content/docs/apis/token-metadata-api/reference/info/meta.json similarity index 100% rename from content/docs/stacks/token-metadata-api/info/meta.json rename to content/docs/apis/token-metadata-api/reference/info/meta.json diff --git a/content/docs/apis/token-metadata-api/reference/info/status.mdx b/content/docs/apis/token-metadata-api/reference/info/status.mdx new file mode 100644 index 000000000..b2fa3757e --- /dev/null +++ b/content/docs/apis/token-metadata-api/reference/info/status.mdx @@ -0,0 +1,12 @@ +--- +title: Get status +sidebarTitle: Status +description: Retrieves information about the Token Metadata API, including the server version. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/token-metadata-api/reference/tokens/fungible-token-metadata.mdx b/content/docs/apis/token-metadata-api/reference/tokens/fungible-token-metadata.mdx new file mode 100644 index 000000000..91b8177d6 --- /dev/null +++ b/content/docs/apis/token-metadata-api/reference/tokens/fungible-token-metadata.mdx @@ -0,0 +1,12 @@ +--- +title: Get fungible token metadata +sidebarTitle: Fungible token metadata +description: Retrieves metadata for a SIP-010 fungible token. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/token-metadata-api/reference/tokens/fungible-tokens.mdx b/content/docs/apis/token-metadata-api/reference/tokens/fungible-tokens.mdx new file mode 100644 index 000000000..eb4fcf809 --- /dev/null +++ b/content/docs/apis/token-metadata-api/reference/tokens/fungible-tokens.mdx @@ -0,0 +1,12 @@ +--- +title: Get fungible tokens +sidebarTitle: Fungible tokens +description: Retrieves information about fungible tokens. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/token-metadata-api/reference/tokens/index.mdx b/content/docs/apis/token-metadata-api/reference/tokens/index.mdx new file mode 100644 index 000000000..bd12ca078 --- /dev/null +++ b/content/docs/apis/token-metadata-api/reference/tokens/index.mdx @@ -0,0 +1,7 @@ +--- +title: Tokens +index: true +full: true +description: Retrieves information about tokens on the Stacks blockchain. +--- + diff --git a/content/docs/stacks/token-metadata-api/tokens/meta.json b/content/docs/apis/token-metadata-api/reference/tokens/meta.json similarity index 100% rename from content/docs/stacks/token-metadata-api/tokens/meta.json rename to content/docs/apis/token-metadata-api/reference/tokens/meta.json diff --git a/content/docs/apis/token-metadata-api/reference/tokens/non-fungible-token-metadata.mdx b/content/docs/apis/token-metadata-api/reference/tokens/non-fungible-token-metadata.mdx new file mode 100644 index 000000000..d9ad3cd9d --- /dev/null +++ b/content/docs/apis/token-metadata-api/reference/tokens/non-fungible-token-metadata.mdx @@ -0,0 +1,12 @@ +--- +title: Get non-fungible token metadata +sidebarTitle: Non-fungible token metadata +description: Retrieves metadata for a SIP-009 non-fungible token. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/apis/token-metadata-api/reference/tokens/semi-fungible-token-metadata.mdx b/content/docs/apis/token-metadata-api/reference/tokens/semi-fungible-token-metadata.mdx new file mode 100644 index 000000000..7b802d8ac --- /dev/null +++ b/content/docs/apis/token-metadata-api/reference/tokens/semi-fungible-token-metadata.mdx @@ -0,0 +1,12 @@ +--- +title: Get semi-fungible token metadata +sidebarTitle: Semi-fungible token metadata +description: Retrieves information about semi-fungible tokens. +full: true +--- + + \ No newline at end of file diff --git a/content/docs/bitcoin/api-keys.mdx b/content/docs/bitcoin/api-keys.mdx deleted file mode 100644 index 6799efe2c..000000000 --- a/content/docs/bitcoin/api-keys.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: API keys -description: For developers who need API requests beyond the standard rate limits. ---- - -import ApiKeysContent from '@/snippets/api-keys.mdx'; - - diff --git a/content/docs/bitcoin/contributors-guide.mdx b/content/docs/bitcoin/contributors-guide.mdx deleted file mode 100644 index 1848ec856..000000000 --- a/content/docs/bitcoin/contributors-guide.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: Contributors guide -description: Learn how to contribute to Hiro's documentation and content. ---- - -import ContributorsGuideContent from '@/snippets/contributors-guide.mdx'; - - diff --git a/content/docs/bitcoin/get-started.mdx b/content/docs/bitcoin/get-started.mdx deleted file mode 100644 index fa6cbf61b..000000000 --- a/content/docs/bitcoin/get-started.mdx +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Get started -description: The following guides cover ways to use Hiro tools to build with Ordinals, BRC-20, and Runes. -icon: Play -toc: false ---- - -import { SecondaryCard, SmallCard } from '@/components/card'; -import { API, Container, Chainhook, BitcoinIcon } from '@/components/ui/icon'; - -
- - - } - href="/bitcoin/ordinals/api" - title="Integrate ordinals data into your app" - description="Use the Ordinals API to get reliable data for Ordinals and BRC-20 tokens." - tag='Ordinals API' - /> - } - href="/bitcoin/indexer" - title="Stream custom blockchain events" - description="Use the Bitcoin Indexer to filter and stream for contract deployments." - tag='Bitcoin Indexer' - /> - } - href="/bitcoin/runes/api" - title="Get Runes data" - description="Use Runes API to get reliable data for Runes." - tag='Runes API' - /> - - - -For more, check out our [guides](/guides) section. - - -
diff --git a/content/docs/bitcoin/index.mdx b/content/docs/bitcoin/index.mdx deleted file mode 100644 index 5498714fc..000000000 --- a/content/docs/bitcoin/index.mdx +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: Home -icon: BitcoinIcon -toc: false ---- - -import { Card, SmallCard } from '@/components/card'; -import { ImageZoom } from 'fumadocs-ui/components/image-zoom'; -import { PageFooter } from '@/components/footer'; -import { Database, Play } from 'lucide-react'; -import { API, Backend, Chainhook, Newspaper, Ordinals, QuestionIcon, BugIcon, Pulse } from '@/components/ui/icon'; -import heroImage from '@/public/bitcoin-hero.svg'; - -
- -
- - -
- - ## Build with Bitcoin - - Find all the guides and resources you need to build on Ordinals and Runes. - -
-
- - - } - href="/bitcoin/get-started" - title="Get Started" - description="Get started with our end-to-end tutorials and quickstart guides across all Hiro's ordinals tools." - /> - } - href="/bitcoin/ordinals/api" - title="Ordinals API Reference" - description="Explore API endpoints for interacting with Ordinals and meta-protocols." - /> - - -
- -

- Explore Bitcoin -

- ---- - - - } - href="/bitcoin/indexer" - title="Bitcoin Indexer" - description="Use the Bitcoin Indexer to index and query Bitcoin blockchain data." - /> - } - href="/bitcoin/ordinals/api" - title="Ordinals API" - description="Fetch on-chain data for Ordinals and meta-protocols with our hosted API." - /> - } - href="https://ordinals.hiro.so/" - title="Ordinals Explorer" - description="View on-chain data for Ordinals and meta-protocols with our explorer." - /> - } - href="/bitcoin/runes/api" - title="Runes API" - description="Interact with the Runes protocol from your backend via our hosted API." - /> - - -
- -
- - \ No newline at end of file diff --git a/content/docs/bitcoin/indexer/guides/run-indexer.mdx b/content/docs/bitcoin/indexer/guides/run-indexer.mdx deleted file mode 100644 index b3ecb004b..000000000 --- a/content/docs/bitcoin/indexer/guides/run-indexer.mdx +++ /dev/null @@ -1,5 +0,0 @@ ---- -title: TBD -description: TBD ---- - diff --git a/content/docs/bitcoin/indexer/index.mdx b/content/docs/bitcoin/indexer/index.mdx deleted file mode 100644 index ff118f009..000000000 --- a/content/docs/bitcoin/indexer/index.mdx +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: Overview -description: The Bitcoin Indexer enables you to build ordinals event streams, so you can create accurate, lightweight databases that gracefully handle Bitcoin forks and reorgs. ---- - -import { SecondaryCard } from '@/components/card'; -import { Step, Steps } from 'fumadocs-ui/components/steps'; - -The Bitcoin Indexer is a reorg-aware indexer that automatically handles chain forks, so you don't need to waste time or resources reindexing your database yourself. - -You can customize what ordinals data you index in order to create lightweight databases for faster query responses and a better user experience. - -## Installation - -```terminal -$ git clone https://github.com/hirosystems/bitcoin-indexer.git -$ cd bitcoin-indexer -$ cargo bitcoin-indexer-install -``` - -Alternatively, you can use Docker images from [Docker Hub](https://hub.docker.com/r/hirosystems/bitcoin-indexer). - -## Get started - - - - - -## System Requirements - -Before running the indexer, ensure your system meets these requirements: - -- **CPU**: Multi-core support for parallel processing -- **Memory**: Minimum 16GB RAM -- **Storage**: SSD or NVMe recommended -- **OS**: Support for 4096+ open file descriptors -- **Postgres**: Version 17+ recommended - -## Related tools - -- **[Ordinals API](/bitcoin/ordinals/api)**: Skip the infrastructure setup and get the ordinals data you need from our Ordinals API, which is powered by the Bitcoin Indexer. -- **[Ordinals Explorer](https://ordinals.hiro.so/)**: Explore ordinals inscriptions and BRC-20 tokens rapidly in our Ordinals Explorer. - -
- - -Reach out to us on the #indexer channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET. - diff --git a/content/docs/bitcoin/indexer/meta.json b/content/docs/bitcoin/indexer/meta.json deleted file mode 100644 index 2493ef638..000000000 --- a/content/docs/bitcoin/indexer/meta.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "title": "Bitcoin Indexer", - "root": true, - "pages": [ - "---Bitcoin Indexer---", - "index", - "installation", - "quickstart" - ] -} diff --git a/content/docs/bitcoin/indexer/quickstart.mdx b/content/docs/bitcoin/indexer/quickstart.mdx deleted file mode 100644 index 64c7e2732..000000000 --- a/content/docs/bitcoin/indexer/quickstart.mdx +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Quickstart -description: Learn how to scan the Bitcoin blockchain for Ordinals activity. ---- - -import { Steps, Step } from 'fumadocs-ui/components/steps'; - -In this quickstart guide, you will set up the Bitcoin Indexer to index Ordinals or Runes activity on the Bitcoin blockchain. - - - - Clone the repository and install the indexer: - ```terminal - $ git clone https://github.com/hirosystems/bitcoin-indexer.git - $ cd bitcoin-indexer - $ cargo bitcoin-indexer-install - ``` - - - - Generate a new configuration file: - ```terminal - $ bitcoin-indexer config new - ``` - - Configure your Postgres database in the generated TOML file: - ```toml - [ordinals.db] - database = "metaprotocols" - host = "localhost" - port = 5432 - username = "postgres" - password = "postgres" - ``` - - - - Run the following command to start indexing Ordinals activity: - ```terminal - $ bitcoin-indexer ordinals service start --config-path - ``` - - For Runes indexing, use: - ```terminal - $ bitcoin-indexer runes service start --config-path - ``` - - - - - A fully synced Bitcoin node is required for indexing to start. - - -## Next steps - - - - - - \ No newline at end of file diff --git a/content/docs/bitcoin/meta.json b/content/docs/bitcoin/meta.json deleted file mode 100644 index 301226879..000000000 --- a/content/docs/bitcoin/meta.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "title": "bitcoin", - "root": true, - "pages": [ - "index", - "get-started", - "---Tools---", - "indexer", - "---APIs---", - "ordinals/api", - "runes/api", - "api-keys", - "rate-limiting", - "------", - "contributors-guide" - ] -} diff --git a/content/docs/bitcoin/ordinals/api/brc20/get-brc20-activity.mdx b/content/docs/bitcoin/ordinals/api/brc20/get-brc20-activity.mdx deleted file mode 100644 index 835be2513..000000000 --- a/content/docs/bitcoin/ordinals/api/brc20/get-brc20-activity.mdx +++ /dev/null @@ -1,218 +0,0 @@ ---- -title: Get BRC-20 activity -description: Retrieves BRC-20 activity filtered by ticker, address, operation, or block height. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - ObjectCollapsible, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## BRC-20 Activity - -Retrieves BRC-20 activity filtered by ticker, address, operation, or at a specific block height - -### Query Parameters - -"} required={false} deprecated={false}> - - - - - -Bitcoin block height - -Pattern: `"^[0-9]+$"` - - - -"} required={false} deprecated={false}> - - - - - -BRC-20 token operation. Note that a BRC-20 transfer is a two step process `transfer` (creating the inscription, which makes funds transferrable) and `transfer_send` (sending the inscription to a recipient, which moves the funds) - - - - - - - - - -Bitcoin address - - - - - -Result offset - -Minimum: `0` - - - - - -Results per page - -Minimum: `1` - -Maximum: `60` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/ordinals/v1/brc-20/activity?ticker=%5B%0A++%22string%22%0A%5D&block_height=string&operation=%5B%0A++%22deploy%22%0A%5D&address=string&offset=0&limit=1" -``` - - - - - -```js -fetch("https://api.hiro.so/ordinals/v1/brc-20/activity?ticker=%5B%0A++%22string%22%0A%5D&block_height=string&operation=%5B%0A++%22deploy%22%0A%5D&address=string&offset=0&limit=1", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "operation": "deploy", - "ticker": "PEPE", - "inscription_id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218i0", - "block_height": 778921, - "block_hash": "0000000000000000000452773967cdd62297137cdaf79950c5e8bb0c62075133", - "tx_id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218", - "location": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218:0:0", - "address": "bc1pvwh2dl6h388x65rqq47qjzdmsqgkatpt4hye6daf7yxvl0z3xjgq247aq8", - "timestamp": 1677733170000, - "mint": { - "amount": "1000000" - }, - "deploy": { - "max_supply": "21000000", - "mint_limit": "100000", - "decimals": 18 - }, - "transfer": { - "amount": "1000000", - "from_address": "bc1pvwh2dl6h388x65rqq47qjzdmsqgkatpt4hye6daf7yxvl0z3xjgq247aq8" - }, - "transfer_send": { - "amount": "1000000", - "from_address": "bc1pvwh2dl6h388x65rqq47qjzdmsqgkatpt4hye6daf7yxvl0z3xjgq247aq8", - "to_address": "bc1pvwh2dl6h388x65rqq47qjzdmsqgkatpt4hye6daf7yxvl0z3xjgq247aq8" - } - } - ] -} -``` - - - - - -```ts -export interface PaginatedBRC20ActivityResponse { - limit: number; - offset: number; - total: number; - results: { - operation: "deploy" | "mint" | "transfer" | "transfer_send"; - ticker: string; - inscription_id: string; - block_height: number; - block_hash: string; - tx_id: string; - location: string; - address: string; - timestamp: number; - mint?: { - amount: string | null; - }; - deploy?: { - max_supply: string; - mint_limit: string | null; - decimals: number; - }; - transfer?: { - amount: string; - from_address: string; - }; - transfer_send?: { - amount: string; - from_address: string; - to_address: string; - }; - }[]; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/ordinals/api/brc20/get-brc20-balances.mdx b/content/docs/bitcoin/ordinals/api/brc20/get-brc20-balances.mdx deleted file mode 100644 index d4fe92a75..000000000 --- a/content/docs/bitcoin/ordinals/api/brc20/get-brc20-balances.mdx +++ /dev/null @@ -1,161 +0,0 @@ ---- -title: Get BRC-20 balances -description: Retrieves BRC-20 token balances for a Bitcoin address. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## BRC-20 Balances - -Retrieves BRC-20 token balances for a Bitcoin address - -### Query Parameters - -"} required={false} deprecated={false}> - - - - - -Bitcoin block height - -Pattern: `"^[0-9]+$"` - - - - - -Result offset - -Minimum: `0` - - - - - -Results per page - -Minimum: `1` - -Maximum: `60` - - - -### Path Parameters - - - -Bitcoin address - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/ordinals/v1/brc-20/balances/string?ticker=%5B%0A++%22string%22%0A%5D&block_height=string&offset=0&limit=1" -``` - - - - - -```js -fetch("https://api.hiro.so/ordinals/v1/brc-20/balances/string?ticker=%5B%0A++%22string%22%0A%5D&block_height=string&offset=0&limit=1", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "ticker": "PEPE", - "available_balance": "1500.00000", - "transferrable_balance": "500.00000", - "overall_balance": "2000.00000" - } - ] -} -``` - - - - - -```ts -export interface PaginatedBRC20BalanceResponse { - limit: number; - offset: number; - total: number; - results: { - ticker: string; - available_balance: string; - transferrable_balance: string; - overall_balance: string; - }[]; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/ordinals/api/brc20/get-brc20-token-details.mdx b/content/docs/bitcoin/ordinals/api/brc20/get-brc20-token-details.mdx deleted file mode 100644 index 6da99a263..000000000 --- a/content/docs/bitcoin/ordinals/api/brc20/get-brc20-token-details.mdx +++ /dev/null @@ -1,175 +0,0 @@ ---- -title: Get BRC-20 token details -description: Retrieves information for a BRC-20 token, including supply and holders. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## BRC-20 Token Details - -Retrieves information for a BRC-20 token including supply and holders - -### Path Parameters - - - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | -| `404` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/ordinals/v1/brc-20/tokens/string" -``` - - - - - -```js -fetch("https://api.hiro.so/ordinals/v1/brc-20/tokens/string", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "token": { - "id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218i0", - "number": 248751, - "block_height": 752860, - "tx_id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218", - "address": "bc1pvwh2dl6h388x65rqq47qjzdmsqgkatpt4hye6daf7yxvl0z3xjgq247aq8", - "ticker": "PEPE", - "max_supply": "21000000", - "mint_limit": "100000", - "decimals": 18, - "deploy_timestamp": 1677733170000, - "minted_supply": "1000000", - "tx_count": 300000 - }, - "supply": { - "max_supply": "21000000", - "minted_supply": "1000000", - "holders": 240 - } -} -``` - - - - - -```ts -export interface BRC20TokenDetailsResponse { - token: BRC20TokenResponse; - supply: { - max_supply: string; - minted_supply: string; - holders: number; - }; -} -export interface BRC20TokenResponse { - id: string; - number: number; - block_height: number; - tx_id: string; - address: string; - ticker: string; - max_supply: string; - mint_limit: string | null; - decimals: number; - deploy_timestamp: number; - minted_supply: string; - tx_count: number; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "Not found" -} -``` - - - - - -```ts -export interface NotFoundResponse { - error: "Not found"; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/ordinals/api/brc20/get-brc20-token-holders.mdx b/content/docs/bitcoin/ordinals/api/brc20/get-brc20-token-holders.mdx deleted file mode 100644 index 103ea1057..000000000 --- a/content/docs/bitcoin/ordinals/api/brc20/get-brc20-token-holders.mdx +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: Get BRC-20 token holders -description: Retrieves a list of holders and their balances for a particular BRC-20 token. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## BRC-20 Token Holders - -Retrieves a list of holders and their balances for a BRC-20 token - -### Query Parameters - - - -Result offset - -Minimum: `0` - - - - - -Results per page - -Minimum: `1` - -Maximum: `60` - - - -### Path Parameters - - - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | -| `404` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/ordinals/v1/brc-20/tokens/string/holders?offset=0&limit=1" -``` - - - - - -```js -fetch("https://api.hiro.so/ordinals/v1/brc-20/tokens/string/holders?offset=0&limit=1", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "address": "bc1pvwh2dl6h388x65rqq47qjzdmsqgkatpt4hye6daf7yxvl0z3xjgq247aq8", - "overall_balance": "2000.00000" - } - ] -} -``` - - - - - -```ts -export interface PaginatedBRC20HoldersResponse { - limit: number; - offset: number; - total: number; - results: { - address: string; - overall_balance: string; - }[]; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "Not found" -} -``` - - - - - -```ts -export interface NotFoundResponse { - error: "Not found"; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/ordinals/api/brc20/get-brc20-tokens.mdx b/content/docs/bitcoin/ordinals/api/brc20/get-brc20-tokens.mdx deleted file mode 100644 index 1be281dbe..000000000 --- a/content/docs/bitcoin/ordinals/api/brc20/get-brc20-tokens.mdx +++ /dev/null @@ -1,168 +0,0 @@ ---- -title: Get BRC-20 tokens -description: Retrieves information for BRC-20 tokens. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## BRC-20 Tokens - -Retrieves information for BRC-20 tokens - -### Query Parameters - -"} required={false} deprecated={false}> - - - - - -Parameter to order results by - - - - - -Result offset - -Minimum: `0` - - - - - -Results per page - -Minimum: `1` - -Maximum: `60` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/ordinals/v1/brc-20/tokens?ticker=%5B%0A++%22string%22%0A%5D&order_by=tx_count&offset=0&limit=1" -``` - - - - - -```js -fetch("https://api.hiro.so/ordinals/v1/brc-20/tokens?ticker=%5B%0A++%22string%22%0A%5D&order_by=tx_count&offset=0&limit=1", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218i0", - "number": 248751, - "block_height": 752860, - "tx_id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218", - "address": "bc1pvwh2dl6h388x65rqq47qjzdmsqgkatpt4hye6daf7yxvl0z3xjgq247aq8", - "ticker": "PEPE", - "max_supply": "21000000", - "mint_limit": "100000", - "decimals": 18, - "deploy_timestamp": 1677733170000, - "minted_supply": "1000000", - "tx_count": 300000 - } - ] -} -``` - - - - - -```ts -export interface PaginatedBRC20TokenResponse { - limit: number; - offset: number; - total: number; - results: BRC20TokenResponse[]; -} -export interface BRC20TokenResponse { - id: string; - number: number; - block_height: number; - tx_id: string; - address: string; - ticker: string; - max_supply: string; - mint_limit: string | null; - decimals: number; - deploy_timestamp: number; - minted_supply: string; - tx_count: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/ordinals/api/brc20/index.mdx b/content/docs/bitcoin/ordinals/api/brc20/index.mdx deleted file mode 100644 index 6f080d8da..000000000 --- a/content/docs/bitcoin/ordinals/api/brc20/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: BRC-20 -index: true -toc: false -description: Retrieves information about BRC-20 tokens. ---- diff --git a/content/docs/bitcoin/ordinals/api/index.mdx b/content/docs/bitcoin/ordinals/api/index.mdx deleted file mode 100644 index ed2508d8b..000000000 --- a/content/docs/bitcoin/ordinals/api/index.mdx +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Overview -description: The Ordinals API provides you with fast, reliable data for Bitcoin ordinals and BRC-20 tokens via an easy-to-use REST interface. ---- - -import { SecondaryCard } from '@/components/card'; - -The Ordinals API is a service that helps you with the complete ingestion of ordinals inscription data. Using our endpoints, you can retrieve metadata for a particular inscription, trading activity, all inscriptions held by a particular address, and more. - -The Ordinals API uses REST endpoints and cached responses in order to optimize performance and reduce unnecessary requests. Start integrating ordinals and BRC-20 tokens into your app with one of the most reliable APIs on the market today. - -## Popular endpoints - - - - - - - - - -## Related tools - -- **[Bitcoin Indexer](/bitcoin/indexer)**: Want to run your own infra? [Set up your own Bitcoin Indexer](/bitcoin/indexer), the indexer that powers the Ordinals API. -- **[Ordinals Explorer](https://ordinals.hiro.so/)**: The Ordinals API powers Hiro’s Ordinals Explorer, which lets you rapidly discover inscriptions and verify on-chain activity. - -
- - -Reach out to us on the #ordinals channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET. - diff --git a/content/docs/bitcoin/ordinals/api/info/index.mdx b/content/docs/bitcoin/ordinals/api/info/index.mdx deleted file mode 100644 index a9ce0c187..000000000 --- a/content/docs/bitcoin/ordinals/api/info/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Status -index: true -toc: false -description: Retrieves information about the Ordinals API status, including the server version. ---- diff --git a/content/docs/bitcoin/ordinals/api/info/status.mdx b/content/docs/bitcoin/ordinals/api/info/status.mdx deleted file mode 100644 index 780e4b239..000000000 --- a/content/docs/bitcoin/ordinals/api/info/status.mdx +++ /dev/null @@ -1,111 +0,0 @@ ---- -title: Get API status -description: Retrieves the running status of the Ordinals API. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## API Status - -Displays the status of the API - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/ordinals/v1/" -``` - - - - - -```js -fetch("https://api.hiro.so/ordinals/v1/", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "server_version": "", - "status": "string", - "block_height": 0, - "max_inscription_number": 0, - "max_cursed_inscription_number": 0 -} -``` - - - - - -```ts -export interface ApiStatusResponse { - server_version: string; - status: string; - block_height?: number; - max_inscription_number?: number; - max_cursed_inscription_number?: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/ordinals/api/inscriptions/get-inscription-content.mdx b/content/docs/bitcoin/ordinals/api/inscriptions/get-inscription-content.mdx deleted file mode 100644 index 901d0815e..000000000 --- a/content/docs/bitcoin/ordinals/api/inscriptions/get-inscription-content.mdx +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: Get inscription content -description: Retrieves the content of a single inscription. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Inscription content - -Retrieves the contents of a single inscription - -### Path Parameters - - - -Inscription unique identifier (number or ID) - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | -| `404` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/ordinals/v1/inscriptions/38c46a8bf7ec90bc7f6b797e7dc84baa97f4e5fd4286b92fe1b50176d03b18dci0/content" -``` - - - - - -```js -fetch("https://api.hiro.so/ordinals/v1/inscriptions/38c46a8bf7ec90bc7f6b797e7dc84baa97f4e5fd4286b92fe1b50176d03b18dci0/content", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{} -``` - - - - - -```ts -export interface Response {} -``` - - - - - - - - - - - - - -```json -{ - "error": "Not found" -} -``` - - - - - -```ts -export interface NotFoundResponse { - error: "Not found"; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/ordinals/api/inscriptions/get-inscription-transfers.mdx b/content/docs/bitcoin/ordinals/api/inscriptions/get-inscription-transfers.mdx deleted file mode 100644 index 2dee370a1..000000000 --- a/content/docs/bitcoin/ordinals/api/inscriptions/get-inscription-transfers.mdx +++ /dev/null @@ -1,189 +0,0 @@ ---- -title: Get inscription transfers -description: Retrieves all transfers for a single inscription. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Inscription transfers - -Retrieves all transfers for a single inscription - -### Query Parameters - - - -Result offset - -Minimum: `0` - - - - - -Results per page - -Minimum: `1` - -Maximum: `60` - - - -### Path Parameters - - - -Inscription unique identifier (number or ID) - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | -| `404` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/ordinals/v1/inscriptions/38c46a8bf7ec90bc7f6b797e7dc84baa97f4e5fd4286b92fe1b50176d03b18dci0/transfers?offset=0&limit=1" -``` - - - - - -```js -fetch("https://api.hiro.so/ordinals/v1/inscriptions/38c46a8bf7ec90bc7f6b797e7dc84baa97f4e5fd4286b92fe1b50176d03b18dci0/transfers?offset=0&limit=1", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "block_height": 778921, - "block_hash": "0000000000000000000452773967cdd62297137cdaf79950c5e8bb0c62075133", - "address": "bc1pvwh2dl6h388x65rqq47qjzdmsqgkatpt4hye6daf7yxvl0z3xjgq247aq8", - "tx_id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218", - "location": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218:0:0", - "output": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218:0", - "value": "546", - "offset": "0", - "timestamp": 1677733170000 - } - ] -} -``` - - - - - -```ts -export interface PaginatedInscriptionLocationsResponse { - limit: number; - offset: number; - total: number; - results: InscriptionLocationResponse[]; -} -export interface InscriptionLocationResponse { - block_height: number; - block_hash: string; - address: string | null; - tx_id: string; - location: string; - output: string; - value: string | null; - offset: string | null; - timestamp: number; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "Not found" -} -``` - - - - - -```ts -export interface NotFoundResponse { - error: "Not found"; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/ordinals/api/inscriptions/get-inscription.mdx b/content/docs/bitcoin/ordinals/api/inscriptions/get-inscription.mdx deleted file mode 100644 index ee582a52c..000000000 --- a/content/docs/bitcoin/ordinals/api/inscriptions/get-inscription.mdx +++ /dev/null @@ -1,188 +0,0 @@ ---- -title: Get inscription -description: Retrieves a single inscription. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Specific Inscription - -Retrieves a single inscription - -### Path Parameters - - - -Inscription unique identifier (number or ID) - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | -| `404` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/ordinals/v1/inscriptions/38c46a8bf7ec90bc7f6b797e7dc84baa97f4e5fd4286b92fe1b50176d03b18dci0" -``` - - - - - -```js -fetch("https://api.hiro.so/ordinals/v1/inscriptions/38c46a8bf7ec90bc7f6b797e7dc84baa97f4e5fd4286b92fe1b50176d03b18dci0", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218i0", - "number": 248751, - "address": "bc1pvwh2dl6h388x65rqq47qjzdmsqgkatpt4hye6daf7yxvl0z3xjgq247aq8", - "genesis_address": "bc1pvwh2dl6h388x65rqq47qjzdmsqgkatpt4hye6daf7yxvl0z3xjgq247aq8", - "genesis_block_height": 778921, - "genesis_block_hash": "0000000000000000000452773967cdd62297137cdaf79950c5e8bb0c62075133", - "genesis_tx_id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218", - "genesis_fee": "3179", - "genesis_timestamp": 0, - "tx_id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218", - "location": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218:0:0", - "output": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218:0", - "value": "546", - "offset": "0", - "sat_ordinal": "1232735286933201", - "sat_rarity": "common", - "sat_coinbase_height": 430521, - "mime_type": "text/plain", - "content_type": "text/plain;charset=utf-8", - "content_length": 59, - "timestamp": 1677733170000, - "curse_type": "p2wsh", - "recursive": true, - "recursion_refs": [ - "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218i0" - ] -} -``` - - - - - -```ts -export interface InscriptionResponse { - id: string; - number: number; - address: string | null; - genesis_address: string | null; - genesis_block_height: number; - genesis_block_hash: string; - genesis_tx_id: string; - genesis_fee: string; - genesis_timestamp: number; - tx_id: string; - location: string; - output: string; - value: string | null; - offset: string | null; - sat_ordinal: string; - sat_rarity: string; - sat_coinbase_height: number; - mime_type: string; - content_type: string; - content_length: number; - timestamp: number; - curse_type: string | null; - recursive: boolean; - recursion_refs: string[] | null; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "Not found" -} -``` - - - - - -```ts -export interface NotFoundResponse { - error: "Not found"; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/ordinals/api/inscriptions/get-inscriptions.mdx b/content/docs/bitcoin/ordinals/api/inscriptions/get-inscriptions.mdx deleted file mode 100644 index db54e3e62..000000000 --- a/content/docs/bitcoin/ordinals/api/inscriptions/get-inscriptions.mdx +++ /dev/null @@ -1,372 +0,0 @@ ---- -title: Get inscriptions -description: Retrieves a list of inscriptions with options to filter and sort results. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - ObjectCollapsible, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## List of Inscriptions - -Retrieves a list of inscriptions with options to filter and sort results - -### Query Parameters - - - -Bitcoin block identifier (height or hash) - - - - - -Bitcoin block height - -Pattern: `"^[0-9]+$"` - - - - - -Bitcoin block height - -Pattern: `"^[0-9]+$"` - - - - - -Block UNIX epoch timestamp (milliseconds) - - - - - -Block UNIX epoch timestamp (milliseconds) - - - - - -Ordinal number that uniquely identifies a satoshi - -Minimum: `0` - - - - - -Ordinal number that uniquely identifies a satoshi - -Minimum: `0` - - - - - -Bitcoin block height - -Pattern: `"^[0-9]+$"` - - - - - -Bitcoin block height - -Pattern: `"^[0-9]+$"` - - - - - -Inscription number - - - - - -Inscription number - - - - - -Array of inscription IDs - -Example: `"/ordinals/v1/inscriptions?id={inscription_id}&id={inscription_id2}"` - - - - - -Array of inscription numbers - - - - - -An UTXO for a Bitcoin transaction - -Pattern: `"^[a-fA-F0-9]{64}:[0-9]+$"` - - - - - -Array of Bitcoin addresses - - - - - -Array of Bitcoin addresses - - - - - -Array of inscription MIME types - - - - - -Array of satoshi rarity values - - - - - -Rarity of a single satoshi according to Ordinal Theory - - - - - - - - - -Whether or not the inscription is recursive - - - - - -Whether or not the inscription is cursed - - - - - -Result offset - -Minimum: `0` - - - - - -Results per page - -Minimum: `1` - -Maximum: `60` - - - - - -Parameter to order results by - - - - - -Results order - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | -| `404` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/ordinals/v1/inscriptions?genesis_block=0000000000000000000452773967cdd62297137cdaf79950c5e8bb0c62075133&from_genesis_block_height=string&to_genesis_block_height=string&from_genesis_timestamp=0&to_genesis_timestamp=0&from_sat_ordinal=2099999997689999&to_sat_ordinal=2099999997689999&from_sat_coinbase_height=string&to_sat_coinbase_height=string&from_number=0&to_number=0&id=%5B%0A++%2238c46a8bf7ec90bc7f6b797e7dc84baa97f4e5fd4286b92fe1b50176d03b18dci0%22%0A%5D&number=%5B%0A++%2210500%22%0A%5D&output=string&address=%5B%0A++%22bc1p8aq8s3z9xl87e74twfk93mljxq6alv4a79yheadx33t9np4g2wkqqt8kc5%22%0A%5D&genesis_address=%5B%0A++%22bc1p8aq8s3z9xl87e74twfk93mljxq6alv4a79yheadx33t9np4g2wkqqt8kc5%22%0A%5D&mime_type=%5B%0A++%22image%2Fpng%22%0A%5D&rarity=%5B%0A++%22uncommon%22%0A%5D&recursive=true&cursed=true&offset=0&limit=1&order_by=number&order=asc" -``` - - - - - -```js -fetch("https://api.hiro.so/ordinals/v1/inscriptions?genesis_block=0000000000000000000452773967cdd62297137cdaf79950c5e8bb0c62075133&from_genesis_block_height=string&to_genesis_block_height=string&from_genesis_timestamp=0&to_genesis_timestamp=0&from_sat_ordinal=2099999997689999&to_sat_ordinal=2099999997689999&from_sat_coinbase_height=string&to_sat_coinbase_height=string&from_number=0&to_number=0&id=%5B%0A++%2238c46a8bf7ec90bc7f6b797e7dc84baa97f4e5fd4286b92fe1b50176d03b18dci0%22%0A%5D&number=%5B%0A++%2210500%22%0A%5D&output=string&address=%5B%0A++%22bc1p8aq8s3z9xl87e74twfk93mljxq6alv4a79yheadx33t9np4g2wkqqt8kc5%22%0A%5D&genesis_address=%5B%0A++%22bc1p8aq8s3z9xl87e74twfk93mljxq6alv4a79yheadx33t9np4g2wkqqt8kc5%22%0A%5D&mime_type=%5B%0A++%22image%2Fpng%22%0A%5D&rarity=%5B%0A++%22uncommon%22%0A%5D&recursive=true&cursed=true&offset=0&limit=1&order_by=number&order=asc", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218i0", - "number": 248751, - "address": "bc1pvwh2dl6h388x65rqq47qjzdmsqgkatpt4hye6daf7yxvl0z3xjgq247aq8", - "genesis_address": "bc1pvwh2dl6h388x65rqq47qjzdmsqgkatpt4hye6daf7yxvl0z3xjgq247aq8", - "genesis_block_height": 778921, - "genesis_block_hash": "0000000000000000000452773967cdd62297137cdaf79950c5e8bb0c62075133", - "genesis_tx_id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218", - "genesis_fee": "3179", - "genesis_timestamp": 0, - "tx_id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218", - "location": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218:0:0", - "output": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218:0", - "value": "546", - "offset": "0", - "sat_ordinal": "1232735286933201", - "sat_rarity": "common", - "sat_coinbase_height": 430521, - "mime_type": "text/plain", - "content_type": "text/plain;charset=utf-8", - "content_length": 59, - "timestamp": 1677733170000, - "curse_type": "p2wsh", - "recursive": true, - "recursion_refs": [ - "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218i0" - ] - } - ] -} -``` - - - - - -```ts -export interface PaginatedInscriptionsResponse { - limit: number; - offset: number; - total: number; - results: InscriptionResponse[]; -} -export interface InscriptionResponse { - id: string; - number: number; - address: string | null; - genesis_address: string | null; - genesis_block_height: number; - genesis_block_hash: string; - genesis_tx_id: string; - genesis_fee: string; - genesis_timestamp: number; - tx_id: string; - location: string; - output: string; - value: string | null; - offset: string | null; - sat_ordinal: string; - sat_rarity: string; - sat_coinbase_height: number; - mime_type: string; - content_type: string; - content_length: number; - timestamp: number; - curse_type: string | null; - recursive: boolean; - recursion_refs: string[] | null; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "Not found" -} -``` - - - - - -```ts -export interface NotFoundResponse { - error: "Not found"; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/ordinals/api/inscriptions/get-transfers-per-block.mdx b/content/docs/bitcoin/ordinals/api/inscriptions/get-transfers-per-block.mdx deleted file mode 100644 index 1432ccb81..000000000 --- a/content/docs/bitcoin/ordinals/api/inscriptions/get-transfers-per-block.mdx +++ /dev/null @@ -1,218 +0,0 @@ ---- -title: Get transfers per block -description: Retrieves a list of inscription transfers that ocurred at a specific Bitcoin block. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Transfers per block - -Retrieves a list of inscription transfers that ocurred at a specific Bitcoin block - -### Query Parameters - - - -Bitcoin block identifier (height or hash) - - - - - -Result offset - -Minimum: `0` - - - - - -Results per page - -Minimum: `1` - -Maximum: `60` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | -| `404` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/ordinals/v1/inscriptions/transfers?block=0000000000000000000452773967cdd62297137cdaf79950c5e8bb0c62075133&offset=0&limit=1" -``` - - - - - -```js -fetch("https://api.hiro.so/ordinals/v1/inscriptions/transfers?block=0000000000000000000452773967cdd62297137cdaf79950c5e8bb0c62075133&offset=0&limit=1", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218i0", - "number": 248751, - "from": { - "block_height": 778921, - "block_hash": "0000000000000000000452773967cdd62297137cdaf79950c5e8bb0c62075133", - "address": "bc1pvwh2dl6h388x65rqq47qjzdmsqgkatpt4hye6daf7yxvl0z3xjgq247aq8", - "tx_id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218", - "location": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218:0:0", - "output": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218:0", - "value": "546", - "offset": "0", - "timestamp": 1677733170000 - }, - "to": { - "block_height": 778921, - "block_hash": "0000000000000000000452773967cdd62297137cdaf79950c5e8bb0c62075133", - "address": "bc1pvwh2dl6h388x65rqq47qjzdmsqgkatpt4hye6daf7yxvl0z3xjgq247aq8", - "tx_id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218", - "location": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218:0:0", - "output": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218:0", - "value": "546", - "offset": "0", - "timestamp": 1677733170000 - } - } - ] -} -``` - - - - - -```ts -export interface PaginatedBlockTransfersResponse { - limit: number; - offset: number; - total: number; - results: { - id: string; - number: number; - from: InscriptionLocationResponse; - to: InscriptionLocationResponse1; - }[]; -} -export interface InscriptionLocationResponse { - block_height: number; - block_hash: string; - address: string | null; - tx_id: string; - location: string; - output: string; - value: string | null; - offset: string | null; - timestamp: number; -} -export interface InscriptionLocationResponse1 { - block_height: number; - block_hash: string; - address: string | null; - tx_id: string; - location: string; - output: string; - value: string | null; - offset: string | null; - timestamp: number; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "Not found" -} -``` - - - - - -```ts -export interface NotFoundResponse { - error: "Not found"; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/ordinals/api/inscriptions/index.mdx b/content/docs/bitcoin/ordinals/api/inscriptions/index.mdx deleted file mode 100644 index 83971be5f..000000000 --- a/content/docs/bitcoin/ordinals/api/inscriptions/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Inscriptions -index: true -toc: false -description: Retrieves information about Ordinals inscriptions. ---- diff --git a/content/docs/bitcoin/ordinals/api/meta.json b/content/docs/bitcoin/ordinals/api/meta.json deleted file mode 100644 index 62240a42e..000000000 --- a/content/docs/bitcoin/ordinals/api/meta.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "title": "Ordinals API", - "root": true, - "pages": [ - "---Ordinals API---", - "index", - "---API Reference---", - "inscriptions", - "satoshis", - "statistics", - "brc20", - "info" - ] -} diff --git a/content/docs/bitcoin/ordinals/api/satoshis/get-satoshi-inscriptions.mdx b/content/docs/bitcoin/ordinals/api/satoshis/get-satoshi-inscriptions.mdx deleted file mode 100644 index a3ba20055..000000000 --- a/content/docs/bitcoin/ordinals/api/satoshis/get-satoshi-inscriptions.mdx +++ /dev/null @@ -1,223 +0,0 @@ ---- -title: Get satoshi inscriptions -description: Retrieves all inscriptions associated with a single satoshi. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Satoshi Inscriptions - -Retrieves all inscriptions associated with a single satoshi - -### Query Parameters - - - -Result offset - -Minimum: `0` - - - - - -Results per page - -Minimum: `1` - -Maximum: `60` - - - -### Path Parameters - - - -Ordinal number that uniquely identifies a satoshi - -Minimum: `0` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | -| `400` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/ordinals/v1/sats/2099999997689999/inscriptions?offset=0&limit=1" -``` - - - - - -```js -fetch("https://api.hiro.so/ordinals/v1/sats/2099999997689999/inscriptions?offset=0&limit=1", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218i0", - "number": 248751, - "address": "bc1pvwh2dl6h388x65rqq47qjzdmsqgkatpt4hye6daf7yxvl0z3xjgq247aq8", - "genesis_address": "bc1pvwh2dl6h388x65rqq47qjzdmsqgkatpt4hye6daf7yxvl0z3xjgq247aq8", - "genesis_block_height": 778921, - "genesis_block_hash": "0000000000000000000452773967cdd62297137cdaf79950c5e8bb0c62075133", - "genesis_tx_id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218", - "genesis_fee": "3179", - "genesis_timestamp": 0, - "tx_id": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218", - "location": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218:0:0", - "output": "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218:0", - "value": "546", - "offset": "0", - "sat_ordinal": "1232735286933201", - "sat_rarity": "common", - "sat_coinbase_height": 430521, - "mime_type": "text/plain", - "content_type": "text/plain;charset=utf-8", - "content_length": 59, - "timestamp": 1677733170000, - "curse_type": "p2wsh", - "recursive": true, - "recursion_refs": [ - "1463d48e9248159084929294f64bda04487503d30ce7ab58365df1dc6fd58218i0" - ] - } - ] -} -``` - - - - - -```ts -export interface PaginatedSatoshiInscriptionsResponse { - limit: number; - offset: number; - total: number; - results: InscriptionResponse[]; -} -export interface InscriptionResponse { - id: string; - number: number; - address: string | null; - genesis_address: string | null; - genesis_block_height: number; - genesis_block_hash: string; - genesis_tx_id: string; - genesis_fee: string; - genesis_timestamp: number; - tx_id: string; - location: string; - output: string; - value: string | null; - offset: string | null; - sat_ordinal: string; - sat_rarity: string; - sat_coinbase_height: number; - mime_type: string; - content_type: string; - content_length: number; - timestamp: number; - curse_type: string | null; - recursive: boolean; - recursion_refs: string[] | null; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "Invalid satoshi ordinal number" -} -``` - - - - - -```ts -export interface InvalidSatoshiNumberResponse { - error: "Invalid satoshi ordinal number"; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/ordinals/api/satoshis/get-satoshi.mdx b/content/docs/bitcoin/ordinals/api/satoshis/get-satoshi.mdx deleted file mode 100644 index 695c450f7..000000000 --- a/content/docs/bitcoin/ordinals/api/satoshis/get-satoshi.mdx +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: Get satoshi ordinal -description: Retrieves ordinal information for a single satoshi. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Satoshi Ordinal - -Retrieves ordinal information for a single satoshi - -### Path Parameters - - - -Ordinal number that uniquely identifies a satoshi - -Minimum: `0` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | -| `400` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/ordinals/v1/sats/2099999997689999" -``` - - - - - -```js -fetch("https://api.hiro.so/ordinals/v1/sats/2099999997689999", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "coinbase_height": 752860, - "cycle": 0, - "decimal": "752860.20444193", - "degree": "0°122860′892″20444193‴", - "inscription_id": "ff4503ab9048d6d0ff4e23def81b614d5270d341ce993992e93902ceb0d4ed79i0", - "epoch": 3, - "name": "ahehcbywzae", - "offset": 20444193, - "percentile": "91.15654869285287%", - "period": 373, - "rarity": "common" -} -``` - - - - - -```ts -export interface SatoshiResponse { - coinbase_height: number; - cycle: number; - decimal: string; - degree: string; - inscription_id?: string; - epoch: number; - name: string; - offset: number; - percentile: string; - period: number; - rarity: "common" | "uncommon" | "rare" | "epic" | "legendary" | "mythic"; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "Invalid satoshi ordinal number" -} -``` - - - - - -```ts -export interface InvalidSatoshiNumberResponse { - error: "Invalid satoshi ordinal number"; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/ordinals/api/satoshis/index.mdx b/content/docs/bitcoin/ordinals/api/satoshis/index.mdx deleted file mode 100644 index 5ff4ced9b..000000000 --- a/content/docs/bitcoin/ordinals/api/satoshis/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Satoshis -index: true -toc: false -description: Retrieves ordinal information for satoshis. ---- diff --git a/content/docs/bitcoin/ordinals/api/statistics/get-stats-inscription-count.mdx b/content/docs/bitcoin/ordinals/api/statistics/get-stats-inscription-count.mdx deleted file mode 100644 index 51a418fe6..000000000 --- a/content/docs/bitcoin/ordinals/api/statistics/get-stats-inscription-count.mdx +++ /dev/null @@ -1,164 +0,0 @@ ---- -title: Get inscription count per block -description: Retrieves statistics on the number of inscriptions revealed per block. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Inscription Count per Block - -Retrieves statistics on the number of inscriptions revealed per block - -### Query Parameters - - - -Bitcoin block height - -Pattern: `"^[0-9]+$"` - - - - - -Bitcoin block height - -Pattern: `"^[0-9]+$"` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | -| `404` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/ordinals/v1/stats/inscriptions?from_block_height=string&to_block_height=string" -``` - - - - - -```js -fetch("https://api.hiro.so/ordinals/v1/stats/inscriptions?from_block_height=string&to_block_height=string", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "results": [ - { - "block_height": "778921", - "block_hash": "0000000000000000000452773967cdd62297137cdaf79950c5e8bb0c62075133", - "inscription_count": "100", - "inscription_count_accum": "3100", - "timestamp": 1677733170000 - } - ] -} -``` - - - - - -```ts -export interface Response { - results: { - block_height: string; - block_hash: string; - inscription_count: string; - inscription_count_accum: string; - timestamp: number; - }[]; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "Not found" -} -``` - - - - - -```ts -export interface NotFoundResponse { - error: "Not found"; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/ordinals/api/statistics/index.mdx b/content/docs/bitcoin/ordinals/api/statistics/index.mdx deleted file mode 100644 index 68cd35ded..000000000 --- a/content/docs/bitcoin/ordinals/api/statistics/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Statistics -index: true -toc: false -description: Retrieves stats on the number of inscriptions per block. ---- diff --git a/content/docs/bitcoin/ordinals/api/usage.mdx b/content/docs/bitcoin/ordinals/api/usage.mdx deleted file mode 100644 index cac19982d..000000000 --- a/content/docs/bitcoin/ordinals/api/usage.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Usage -description: Create your first project in less than 2 minutes ---- - -The Usage section should focus on practical, hands-on instructions for getting started with the API. This includes: -Authentication: How to authenticate with the API (e.g., API keys, OAuth tokens). -Making Requests: Basic examples of making requests to the API, including request format, essential headers, and parameters. -Handling Responses: Information on response structure, understanding status codes, and error handling. -Rate Limits: If applicable, explain any rate limits and best practices for avoiding them. -The goal of the "Usage" section is to equip developers with the knowledge to make successful API calls and handle responses effectively. diff --git a/content/docs/bitcoin/ordinals/explorer/guides/build-explorer.mdx b/content/docs/bitcoin/ordinals/explorer/guides/build-explorer.mdx deleted file mode 100644 index 6861d726b..000000000 --- a/content/docs/bitcoin/ordinals/explorer/guides/build-explorer.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: Build Ordinals Explorer ---- - -After installing and configuring your environment, you can run the Ordinals Explorer locally if you wish by running the followning `npm` command: - -`npm run dev` - -## Building for production - -You may also build a production version of the Ordinals Explorer. To do that, simply run the following command: - -`npm run build` - - - Running `npm run build` also run the default next.js build task. - diff --git a/content/docs/bitcoin/ordinals/explorer/index.mdx b/content/docs/bitcoin/ordinals/explorer/index.mdx deleted file mode 100644 index 4a367ed0f..000000000 --- a/content/docs/bitcoin/ordinals/explorer/index.mdx +++ /dev/null @@ -1,35 +0,0 @@ ---- -# The default id is the same as the one defined below. so not needed -title: Overview -description: Explore and verify ordinals and BRC-20 data on Bitcoin. ---- - -import Link from "next/link"; -import { Button } from "@/components/ui/button" - -The Ordinals Explorer lets you explore and verify Bitcoin Ordinals and BRC-20 token data. You can also use a variety of filters to discover inscriptions. We maintain and support the [Ordinals Explorer](https://ordinals.hiro.so) as a service for the community, but you can also run your own instance of the explorer if you so choose. - -
- - -
- -## Related tools - -- **[Ordinals API](/bitcoin/ordinals/api)**: Looking for on-chain data without the front end? Leverage the Ordinals API. -- **[Stacks Explorer](https://explorer.hiro.so)**: Looking for a front end to verify activity on the Stacks blockchain? Try the Stacks Explorer. - ---- - -Need help building with the Ordinals Explorer? Reach out to us on the `#ordinals` channel on Discord under the [Hiro Developer Tools section](https://stacks.chat/). There’s also a [weekly office hours](https://events.stacks.co/event/HD16484710) on Discord every Thursday at 11am ET. diff --git a/content/docs/bitcoin/ordinals/explorer/meta.json b/content/docs/bitcoin/ordinals/explorer/meta.json deleted file mode 100644 index 3f42be985..000000000 --- a/content/docs/bitcoin/ordinals/explorer/meta.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "title": "Explorer", - "root": true, - "pages": [ - "---Ordinals Explorer---", - "index" - ] -} diff --git a/content/docs/bitcoin/rate-limiting.mdx b/content/docs/bitcoin/rate-limiting.mdx deleted file mode 100644 index 8f07a848b..000000000 --- a/content/docs/bitcoin/rate-limiting.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: Rate limiting -description: Understand the rate limits for Hiro APIs and testnet faucets. ---- - -import RateLimitingContent from '@/snippets/rate-limiting.mdx'; - - diff --git a/content/docs/bitcoin/runes/api/activities/activity.mdx b/content/docs/bitcoin/runes/api/activities/activity.mdx deleted file mode 100644 index 943d9e953..000000000 --- a/content/docs/bitcoin/runes/api/activities/activity.mdx +++ /dev/null @@ -1,214 +0,0 @@ ---- -title: Get all activity -description: Retrieves all activity for a Rune. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Rune activity - -Retrieves all activity for a Rune - -### Query Parameters - - - -Result offset - -Minimum: `0` - - - - - -Results per page - -Minimum: `1` - -Maximum: `60` - - - -### Path Parameters - - - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/runes/v1/etchings/string/activity?offset=0&limit=1" -``` - - - - - -```js -fetch("https://api.hiro.so/runes/v1/etchings/string/activity?offset=0&limit=1", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "address": "bc1q7jd477wc5s88hsvenr0ddtatsw282hfjzg59wz", - "receiver_address": "bc1pgdrveee2v4ez95szaakw5gkd8eennv2dddf9rjdrlt6ch56lzrrsxgvazt", - "amount": "11000000000", - "operation": "etching", - "location": { - "block_hash": "00000000000000000000c9787573a1f1775a2b56b403a2d0c7957e9a5bc754bb", - "block_height": 840000, - "tx_id": "2bb85f4b004be6da54f766c17c1e855187327112c231ef2ff35ebad0ea67c69e", - "tx_index": 1, - "vout": 100, - "output": "2bb85f4b004be6da54f766c17c1e855187327112c231ef2ff35ebad0ea67c69e:100", - "timestamp": 1713571767 - } - } - ] -} -``` - - - - - -```ts -/** - * Bitcoin address which initiated this activity - */ -export type Address = string; -/** - * Bitcoin address which is receiving rune balance - */ -export type ReceiverAddress = string; -/** - * Rune amount relevat to this activity - */ -export type Amount = string; -/** - * Type of operation described in this activity - */ -export type Operation = "etching" | "mint" | "burn" | "send" | "receive"; -/** - * Bitcoin block hash - */ -export type BlockHash = string; -/** - * Bitcoin block height - */ -export type BlockHeight = number; -/** - * Bitcoin transaction ID - */ -export type TransactionID = string; -/** - * Index of this transaction in its Bitcoin block - */ -export type TransactionIndex = number; -/** - * Bitcoin transaction output number - */ -export type OutputNumber = number; -/** - * Bitcoin transaction output - */ -export type TransactionOutput = string; -/** - * Bitcoin transaction timestamp - */ -export type Timestamp = number; - -export interface PaginatedActivityResponse { - limit: number; - offset: number; - total: number; - results: { - address?: Address; - receiver_address?: ReceiverAddress; - amount?: Amount; - operation: Operation; - location: TransactionLocation; - }[]; -} -/** - * Location of the transaction which confirmed this operation - */ -export interface TransactionLocation { - block_hash: BlockHash; - block_height: BlockHeight; - tx_id: TransactionID; - tx_index: TransactionIndex; - vout?: OutputNumber; - output?: TransactionOutput; - timestamp: Timestamp; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/runes/api/activities/for-address.mdx b/content/docs/bitcoin/runes/api/activities/for-address.mdx deleted file mode 100644 index 8d61afe6e..000000000 --- a/content/docs/bitcoin/runes/api/activities/for-address.mdx +++ /dev/null @@ -1,220 +0,0 @@ ---- -title: Get activity for an address -description: Retrieves all Rune activity for a Bitcoin address. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Rune activity for address - -Retrieves all activity for a Rune address - -### Query Parameters - - - -Result offset - -Minimum: `0` - - - - - -Results per page - -Minimum: `1` - -Maximum: `60` - - - -### Path Parameters - - - - - - - -Bitcoin address - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/runes/v1/etchings/string/activity/string?offset=0&limit=1" -``` - - - - - -```js -fetch("https://api.hiro.so/runes/v1/etchings/string/activity/string?offset=0&limit=1", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "address": "bc1q7jd477wc5s88hsvenr0ddtatsw282hfjzg59wz", - "receiver_address": "bc1pgdrveee2v4ez95szaakw5gkd8eennv2dddf9rjdrlt6ch56lzrrsxgvazt", - "amount": "11000000000", - "operation": "etching", - "location": { - "block_hash": "00000000000000000000c9787573a1f1775a2b56b403a2d0c7957e9a5bc754bb", - "block_height": 840000, - "tx_id": "2bb85f4b004be6da54f766c17c1e855187327112c231ef2ff35ebad0ea67c69e", - "tx_index": 1, - "vout": 100, - "output": "2bb85f4b004be6da54f766c17c1e855187327112c231ef2ff35ebad0ea67c69e:100", - "timestamp": 1713571767 - } - } - ] -} -``` - - - - - -```ts -/** - * Bitcoin address which initiated this activity - */ -export type Address = string; -/** - * Bitcoin address which is receiving rune balance - */ -export type ReceiverAddress = string; -/** - * Rune amount relevat to this activity - */ -export type Amount = string; -/** - * Type of operation described in this activity - */ -export type Operation = "etching" | "mint" | "burn" | "send" | "receive"; -/** - * Bitcoin block hash - */ -export type BlockHash = string; -/** - * Bitcoin block height - */ -export type BlockHeight = number; -/** - * Bitcoin transaction ID - */ -export type TransactionID = string; -/** - * Index of this transaction in its Bitcoin block - */ -export type TransactionIndex = number; -/** - * Bitcoin transaction output number - */ -export type OutputNumber = number; -/** - * Bitcoin transaction output - */ -export type TransactionOutput = string; -/** - * Bitcoin transaction timestamp - */ -export type Timestamp = number; - -export interface PaginatedActivityResponse { - limit: number; - offset: number; - total: number; - results: { - address?: Address; - receiver_address?: ReceiverAddress; - amount?: Amount; - operation: Operation; - location: TransactionLocation; - }[]; -} -/** - * Location of the transaction which confirmed this operation - */ -export interface TransactionLocation { - block_hash: BlockHash; - block_height: BlockHeight; - tx_id: TransactionID; - tx_index: TransactionIndex; - vout?: OutputNumber; - output?: TransactionOutput; - timestamp: Timestamp; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/runes/api/activities/for-block.mdx b/content/docs/bitcoin/runes/api/activities/for-block.mdx deleted file mode 100644 index e7c4dcb85..000000000 --- a/content/docs/bitcoin/runes/api/activities/for-block.mdx +++ /dev/null @@ -1,242 +0,0 @@ ---- -title: Get activity for a block -description: Retrieves a paginated list of rune activity for a block. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - ObjectCollapsible, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Block activity - -Retrieves a paginated list of rune activity for a block - -### Query Parameters - - - -Result offset - -Minimum: `0` - - - - - -Results per page - -Minimum: `1` - -Maximum: `60` - - - -### Path Parameters - - - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/runes/v1/blocks/777678/activity?offset=0&limit=1" -``` - - - - - -```js -fetch("https://api.hiro.so/runes/v1/blocks/777678/activity?offset=0&limit=1", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "rune": { - "id": "840000:1", - "name": "ZZZZZFEHUZZZZZ", - "spaced_name": "Z•Z•Z•Z•Z•FEHU•Z•Z•Z•Z•Z" - }, - "address": "bc1q7jd477wc5s88hsvenr0ddtatsw282hfjzg59wz", - "receiver_address": "bc1pgdrveee2v4ez95szaakw5gkd8eennv2dddf9rjdrlt6ch56lzrrsxgvazt", - "amount": "11000000000", - "operation": "etching", - "location": { - "block_hash": "00000000000000000000c9787573a1f1775a2b56b403a2d0c7957e9a5bc754bb", - "block_height": 840000, - "tx_id": "2bb85f4b004be6da54f766c17c1e855187327112c231ef2ff35ebad0ea67c69e", - "tx_index": 1, - "vout": 100, - "output": "2bb85f4b004be6da54f766c17c1e855187327112c231ef2ff35ebad0ea67c69e:100", - "timestamp": 1713571767 - } - } - ] -} -``` - - - - - -```ts -/** - * Rune ID - */ -export type ID = string; -/** - * Rune name - */ -export type Name = string; -/** - * Rune name with spacers - */ -export type SpacedName = string; -/** - * Bitcoin address which initiated this activity - */ -export type Address = string; -/** - * Bitcoin address which is receiving rune balance - */ -export type ReceiverAddress = string; -/** - * Rune amount relevat to this activity - */ -export type Amount = string; -/** - * Type of operation described in this activity - */ -export type Operation = "etching" | "mint" | "burn" | "send" | "receive"; -/** - * Bitcoin block hash - */ -export type BlockHash = string; -/** - * Bitcoin block height - */ -export type BlockHeight = number; -/** - * Bitcoin transaction ID - */ -export type TransactionID = string; -/** - * Index of this transaction in its Bitcoin block - */ -export type TransactionIndex = number; -/** - * Bitcoin transaction output number - */ -export type OutputNumber = number; -/** - * Bitcoin transaction output - */ -export type TransactionOutput = string; -/** - * Bitcoin transaction timestamp - */ -export type Timestamp = number; - -export interface PaginatedActivityResponse { - limit: number; - offset: number; - total: number; - results: ({ - rune: RuneDetail; - } & { - address?: Address; - receiver_address?: ReceiverAddress; - amount?: Amount; - operation: Operation; - location: TransactionLocation; - })[]; -} -/** - * Details of the rune affected by this activity - */ -export interface RuneDetail { - id: ID; - name: Name; - spaced_name: SpacedName; -} -/** - * Location of the transaction which confirmed this operation - */ -export interface TransactionLocation { - block_hash: BlockHash; - block_height: BlockHeight; - tx_id: TransactionID; - tx_index: TransactionIndex; - vout?: OutputNumber; - output?: TransactionOutput; - timestamp: Timestamp; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/runes/api/activities/for-transaction.mdx b/content/docs/bitcoin/runes/api/activities/for-transaction.mdx deleted file mode 100644 index 8e2d9e750..000000000 --- a/content/docs/bitcoin/runes/api/activities/for-transaction.mdx +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: Get activity for a transaction -description: Retrieves a paginated list of rune activity for a transaction. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Transaction activity - -Retrieves a paginated list of rune activity for a transaction - -### Query Parameters - - - -Result offset - -Minimum: `0` - - - - - -Results per page - -Minimum: `1` - -Maximum: `60` - - - -### Path Parameters - - - -A transaction ID - -Pattern: `"^[a-fA-F0-9]{64}$"` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/runes/v1/transactions/string/activity?offset=0&limit=1" -``` - - - - - -```js -fetch("https://api.hiro.so/runes/v1/transactions/string/activity?offset=0&limit=1", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "rune": { - "id": "840000:1", - "name": "ZZZZZFEHUZZZZZ", - "spaced_name": "Z•Z•Z•Z•Z•FEHU•Z•Z•Z•Z•Z" - }, - "address": "bc1q7jd477wc5s88hsvenr0ddtatsw282hfjzg59wz", - "receiver_address": "bc1pgdrveee2v4ez95szaakw5gkd8eennv2dddf9rjdrlt6ch56lzrrsxgvazt", - "amount": "11000000000", - "operation": "etching", - "location": { - "block_hash": "00000000000000000000c9787573a1f1775a2b56b403a2d0c7957e9a5bc754bb", - "block_height": 840000, - "tx_id": "2bb85f4b004be6da54f766c17c1e855187327112c231ef2ff35ebad0ea67c69e", - "tx_index": 1, - "vout": 100, - "output": "2bb85f4b004be6da54f766c17c1e855187327112c231ef2ff35ebad0ea67c69e:100", - "timestamp": 1713571767 - } - } - ] -} -``` - - - - - -```ts -/** - * Rune ID - */ -export type ID = string; -/** - * Rune name - */ -export type Name = string; -/** - * Rune name with spacers - */ -export type SpacedName = string; -/** - * Bitcoin address which initiated this activity - */ -export type Address = string; -/** - * Bitcoin address which is receiving rune balance - */ -export type ReceiverAddress = string; -/** - * Rune amount relevat to this activity - */ -export type Amount = string; -/** - * Type of operation described in this activity - */ -export type Operation = "etching" | "mint" | "burn" | "send" | "receive"; -/** - * Bitcoin block hash - */ -export type BlockHash = string; -/** - * Bitcoin block height - */ -export type BlockHeight = number; -/** - * Bitcoin transaction ID - */ -export type TransactionID = string; -/** - * Index of this transaction in its Bitcoin block - */ -export type TransactionIndex = number; -/** - * Bitcoin transaction output number - */ -export type OutputNumber = number; -/** - * Bitcoin transaction output - */ -export type TransactionOutput = string; -/** - * Bitcoin transaction timestamp - */ -export type Timestamp = number; - -export interface PaginatedActivityResponse { - limit: number; - offset: number; - total: number; - results: ({ - rune: RuneDetail; - } & { - address?: Address; - receiver_address?: ReceiverAddress; - amount?: Amount; - operation: Operation; - location: TransactionLocation; - })[]; -} -/** - * Details of the rune affected by this activity - */ -export interface RuneDetail { - id: ID; - name: Name; - spaced_name: SpacedName; -} -/** - * Location of the transaction which confirmed this operation - */ -export interface TransactionLocation { - block_hash: BlockHash; - block_height: BlockHeight; - tx_id: TransactionID; - tx_index: TransactionIndex; - vout?: OutputNumber; - output?: TransactionOutput; - timestamp: Timestamp; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/runes/api/activities/index.mdx b/content/docs/bitcoin/runes/api/activities/index.mdx deleted file mode 100644 index 5e217ad15..000000000 --- a/content/docs/bitcoin/runes/api/activities/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Activities -index: true -toc: false -description: Retrieves information about Rune activities. ---- diff --git a/content/docs/bitcoin/runes/api/balances/address.mdx b/content/docs/bitcoin/runes/api/balances/address.mdx deleted file mode 100644 index f5d6f6f84..000000000 --- a/content/docs/bitcoin/runes/api/balances/address.mdx +++ /dev/null @@ -1,181 +0,0 @@ ---- -title: Get address balances -description: Retrieves a paginated list of address balances. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Address balances - -Retrieves a paginated list of address balances - -### Query Parameters - - - -Result offset - -Minimum: `0` - - - - - -Results per page - -Minimum: `1` - -Maximum: `60` - - - -### Path Parameters - - - -Bitcoin address - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/runes/v1/addresses/string/balances?offset=0&limit=1" -``` - - - - - -```js -fetch("https://api.hiro.so/runes/v1/addresses/string/balances?offset=0&limit=1", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "rune": { - "id": "840000:1", - "name": "ZZZZZFEHUZZZZZ", - "spaced_name": "Z•Z•Z•Z•Z•FEHU•Z•Z•Z•Z•Z" - }, - "address": "bc1q7jd477wc5s88hsvenr0ddtatsw282hfjzg59wz", - "balance": "11000000000" - } - ] -} -``` - - - - - -```ts -/** - * Rune ID - */ -export type ID = string; -/** - * Rune name - */ -export type Name = string; -/** - * Rune name with spacers - */ -export type SpacedName = string; -/** - * Bitcoin address which holds this balance - */ -export type Address = string; -/** - * Rune balance - */ -export type Balance = string; - -export interface PaginatedBalancesResponse { - limit: number; - offset: number; - total: number; - results: ({ - rune: RuneDetail; - } & { - address?: Address; - balance: Balance; - })[]; -} -/** - * Details of the rune affected by this activity - */ -export interface RuneDetail { - id: ID; - name: Name; - spaced_name: SpacedName; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/runes/api/balances/holder-balance.mdx b/content/docs/bitcoin/runes/api/balances/holder-balance.mdx deleted file mode 100644 index 6ad56dc49..000000000 --- a/content/docs/bitcoin/runes/api/balances/holder-balance.mdx +++ /dev/null @@ -1,155 +0,0 @@ ---- -title: Get holder balance -description: Retrieves holder balance for a specific Rune. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Rune holder balance - -Retrieves holder balance for a specific Rune - -### Path Parameters - - - - - - - -Bitcoin address - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | -| `404` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/runes/v1/etchings/string/holders/string" -``` - - - - - -```js -fetch("https://api.hiro.so/runes/v1/etchings/string/holders/string", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "address": "bc1q7jd477wc5s88hsvenr0ddtatsw282hfjzg59wz", - "balance": "11000000000" -} -``` - - - - - -```ts -/** - * Bitcoin address which holds this balance - */ -export type Address = string; -/** - * Rune balance - */ -export type Balance = string; - -export interface Response { - address?: Address; - balance: Balance; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "Not found" -} -``` - - - - - -```ts -export interface NotFoundResponse { - error: "Not found"; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/runes/api/balances/holders.mdx b/content/docs/bitcoin/runes/api/balances/holders.mdx deleted file mode 100644 index 409aae0ff..000000000 --- a/content/docs/bitcoin/runes/api/balances/holders.mdx +++ /dev/null @@ -1,152 +0,0 @@ ---- -title: Get rune holders -description: Retrieves a paginated list of holders for a Rune. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Rune holders - -Retrieves a paginated list of holders for a Rune - -### Query Parameters - - - -Result offset - -Minimum: `0` - - - - - -Results per page - -Minimum: `1` - -Maximum: `60` - - - -### Path Parameters - - - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/runes/v1/etchings/string/holders?offset=0&limit=1" -``` - - - - - -```js -fetch("https://api.hiro.so/runes/v1/etchings/string/holders?offset=0&limit=1", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "address": "bc1q7jd477wc5s88hsvenr0ddtatsw282hfjzg59wz", - "balance": "11000000000" - } - ] -} -``` - - - - - -```ts -/** - * Bitcoin address which holds this balance - */ -export type Address = string; -/** - * Rune balance - */ -export type Balance = string; - -export interface PaginatedHoldersResponse { - limit: number; - offset: number; - total: number; - results: { - address?: Address; - balance: Balance; - }[]; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/runes/api/balances/index.mdx b/content/docs/bitcoin/runes/api/balances/index.mdx deleted file mode 100644 index f9f893b4b..000000000 --- a/content/docs/bitcoin/runes/api/balances/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Balances -index: true -toc: false -description: Retrieves information about Rune balances. ---- diff --git a/content/docs/bitcoin/runes/api/etchings/get-etching.mdx b/content/docs/bitcoin/runes/api/etchings/get-etching.mdx deleted file mode 100644 index 66e133aac..000000000 --- a/content/docs/bitcoin/runes/api/etchings/get-etching.mdx +++ /dev/null @@ -1,329 +0,0 @@ ---- -title: Get etching -description: Retrieves information for a Rune etching. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Rune etching - -Retrieves information for a Rune etching - -### Path Parameters - - - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | -| `404` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/runes/v1/etchings/string" -``` - - - - - -```js -fetch("https://api.hiro.so/runes/v1/etchings/string", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "id": "840000:1", - "name": "ZZZZZFEHUZZZZZ", - "spaced_name": "Z•Z•Z•Z•Z•FEHU•Z•Z•Z•Z•Z", - "number": 1, - "divisibility": 2, - "symbol": "ᚠ", - "turbo": false, - "mint_terms": { - "amount": "100", - "cap": "1111111", - "height_start": 840000, - "height_end": 1050000, - "offset_start": 0, - "offset_end": 200 - }, - "supply": { - "current": "11274916350", - "minted": "274916100", - "total_mints": "250", - "mint_percentage": "59.4567", - "mintable": true, - "burned": "5100", - "total_burns": "17", - "premine": "11000000000" - }, - "location": { - "block_hash": "00000000000000000000c9787573a1f1775a2b56b403a2d0c7957e9a5bc754bb", - "block_height": 840000, - "tx_id": "2bb85f4b004be6da54f766c17c1e855187327112c231ef2ff35ebad0ea67c69e", - "tx_index": 1, - "vout": 100, - "output": "2bb85f4b004be6da54f766c17c1e855187327112c231ef2ff35ebad0ea67c69e:100", - "timestamp": 1713571767 - } -} -``` - - - - - -```ts -/** - * Rune ID - */ -export type ID = string; -/** - * Rune name - */ -export type Name = string; -/** - * Rune name with spacers - */ -export type SpacedName = string; -/** - * Rune number - */ -export type Number = number; -/** - * Rune decimal places - */ -export type Divisibility = number; -/** - * Rune symbol - */ -export type Symbol = string; -/** - * Rune upgradeability - */ -export type Turbo = boolean; -/** - * Amount awarded per mint - */ -export type MintAmount = string; -/** - * Maximum number of mints allowed - */ -export type MintCap = string; -/** - * Block height at which the mint period opens - */ -export type MintBlockHeightStart = number; -/** - * Block height at which the mint period closes - */ -export type MintBlockHeightEnd = number; -/** - * Block height etching offset at which the mint period opens - */ -export type MintBlockHeightOffsetStart = number; -/** - * Block height etching offset at which the mint period closes - */ -export type MintBlockHeightOffsetEnd = number; -/** - * Circulating supply including mints, burns and premine - */ -export type CurrentSupply = string; -/** - * Total minted amount - */ -export type MintedAmount = string; -/** - * Number of mints for this rune - */ -export type TotalMints = string; -/** - * Percentage of mints that have been claimed - */ -export type MintPercentage = string; -/** - * Whether or not this rune is mintable at this time - */ -export type Mintable = boolean; -/** - * Total burned amount - */ -export type BurnedAmount = string; -/** - * Number of burns for this rune - */ -export type TotalBurns = string; -/** - * Amount premined for this rune - */ -export type PremineAmount = string; -/** - * Bitcoin block hash - */ -export type BlockHash = string; -/** - * Bitcoin block height - */ -export type BlockHeight = number; -/** - * Bitcoin transaction ID - */ -export type TransactionID = string; -/** - * Index of this transaction in its Bitcoin block - */ -export type TransactionIndex = number; -/** - * Bitcoin transaction output number - */ -export type OutputNumber = number; -/** - * Bitcoin transaction output - */ -export type TransactionOutput = string; -/** - * Bitcoin transaction timestamp - */ -export type Timestamp = number; - -export interface Response { - id: ID; - name: Name; - spaced_name: SpacedName; - number: Number; - divisibility: Divisibility; - symbol: Symbol; - turbo: Turbo; - mint_terms: MintTerms; - supply: SupplyInformation; - location: TransactionLocation; -} -/** - * Rune mint terms - */ -export interface MintTerms { - amount: MintAmount | null; - cap: MintCap | null; - height_start: MintBlockHeightStart | null; - height_end: MintBlockHeightEnd | null; - offset_start: MintBlockHeightOffsetStart | null; - offset_end: MintBlockHeightOffsetEnd | null; -} -/** - * Rune supply information - */ -export interface SupplyInformation { - current: CurrentSupply; - minted: MintedAmount; - total_mints: TotalMints; - mint_percentage: MintPercentage; - mintable: Mintable; - burned: BurnedAmount; - total_burns: TotalBurns; - premine: PremineAmount; -} -/** - * Location of the transaction which confirmed this operation - */ -export interface TransactionLocation { - block_hash: BlockHash; - block_height: BlockHeight; - tx_id: TransactionID; - tx_index: TransactionIndex; - vout?: OutputNumber; - output?: TransactionOutput; - timestamp: Timestamp; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "Not found" -} -``` - - - - - -```ts -export interface NotFoundResponse { - error: "Not found"; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/runes/api/etchings/get-etchings.mdx b/content/docs/bitcoin/runes/api/etchings/get-etchings.mdx deleted file mode 100644 index bdf5b60d4..000000000 --- a/content/docs/bitcoin/runes/api/etchings/get-etchings.mdx +++ /dev/null @@ -1,326 +0,0 @@ ---- -title: Get etchings -description: Retrieves a paginated list of rune etchings. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Rune etchings - -Retrieves a paginated list of rune etchings - -### Query Parameters - - - -Result offset - -Minimum: `0` - - - - - -Results per page - -Minimum: `1` - -Maximum: `60` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/runes/v1/etchings?offset=0&limit=1" -``` - - - - - -```js -fetch("https://api.hiro.so/runes/v1/etchings?offset=0&limit=1", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "id": "840000:1", - "name": "ZZZZZFEHUZZZZZ", - "spaced_name": "Z•Z•Z•Z•Z•FEHU•Z•Z•Z•Z•Z", - "number": 1, - "divisibility": 2, - "symbol": "ᚠ", - "turbo": false, - "mint_terms": { - "amount": "100", - "cap": "1111111", - "height_start": 840000, - "height_end": 1050000, - "offset_start": 0, - "offset_end": 200 - }, - "supply": { - "current": "11274916350", - "minted": "274916100", - "total_mints": "250", - "mint_percentage": "59.4567", - "mintable": true, - "burned": "5100", - "total_burns": "17", - "premine": "11000000000" - }, - "location": { - "block_hash": "00000000000000000000c9787573a1f1775a2b56b403a2d0c7957e9a5bc754bb", - "block_height": 840000, - "tx_id": "2bb85f4b004be6da54f766c17c1e855187327112c231ef2ff35ebad0ea67c69e", - "tx_index": 1, - "vout": 100, - "output": "2bb85f4b004be6da54f766c17c1e855187327112c231ef2ff35ebad0ea67c69e:100", - "timestamp": 1713571767 - } - } - ] -} -``` - - - - - -```ts -/** - * Rune ID - */ -export type ID = string; -/** - * Rune name - */ -export type Name = string; -/** - * Rune name with spacers - */ -export type SpacedName = string; -/** - * Rune number - */ -export type Number = number; -/** - * Rune decimal places - */ -export type Divisibility = number; -/** - * Rune symbol - */ -export type Symbol = string; -/** - * Rune upgradeability - */ -export type Turbo = boolean; -/** - * Amount awarded per mint - */ -export type MintAmount = string; -/** - * Maximum number of mints allowed - */ -export type MintCap = string; -/** - * Block height at which the mint period opens - */ -export type MintBlockHeightStart = number; -/** - * Block height at which the mint period closes - */ -export type MintBlockHeightEnd = number; -/** - * Block height etching offset at which the mint period opens - */ -export type MintBlockHeightOffsetStart = number; -/** - * Block height etching offset at which the mint period closes - */ -export type MintBlockHeightOffsetEnd = number; -/** - * Circulating supply including mints, burns and premine - */ -export type CurrentSupply = string; -/** - * Total minted amount - */ -export type MintedAmount = string; -/** - * Number of mints for this rune - */ -export type TotalMints = string; -/** - * Percentage of mints that have been claimed - */ -export type MintPercentage = string; -/** - * Whether or not this rune is mintable at this time - */ -export type Mintable = boolean; -/** - * Total burned amount - */ -export type BurnedAmount = string; -/** - * Number of burns for this rune - */ -export type TotalBurns = string; -/** - * Amount premined for this rune - */ -export type PremineAmount = string; -/** - * Bitcoin block hash - */ -export type BlockHash = string; -/** - * Bitcoin block height - */ -export type BlockHeight = number; -/** - * Bitcoin transaction ID - */ -export type TransactionID = string; -/** - * Index of this transaction in its Bitcoin block - */ -export type TransactionIndex = number; -/** - * Bitcoin transaction output number - */ -export type OutputNumber = number; -/** - * Bitcoin transaction output - */ -export type TransactionOutput = string; -/** - * Bitcoin transaction timestamp - */ -export type Timestamp = number; - -export interface PaginatedEtchingsResponse { - limit: number; - offset: number; - total: number; - results: { - id: ID; - name: Name; - spaced_name: SpacedName; - number: Number; - divisibility: Divisibility; - symbol: Symbol; - turbo: Turbo; - mint_terms: MintTerms; - supply: SupplyInformation; - location: TransactionLocation; - }[]; -} -/** - * Rune mint terms - */ -export interface MintTerms { - amount: MintAmount | null; - cap: MintCap | null; - height_start: MintBlockHeightStart | null; - height_end: MintBlockHeightEnd | null; - offset_start: MintBlockHeightOffsetStart | null; - offset_end: MintBlockHeightOffsetEnd | null; -} -/** - * Rune supply information - */ -export interface SupplyInformation { - current: CurrentSupply; - minted: MintedAmount; - total_mints: TotalMints; - mint_percentage: MintPercentage; - mintable: Mintable; - burned: BurnedAmount; - total_burns: TotalBurns; - premine: PremineAmount; -} -/** - * Location of the transaction which confirmed this operation - */ -export interface TransactionLocation { - block_hash: BlockHash; - block_height: BlockHeight; - tx_id: TransactionID; - tx_index: TransactionIndex; - vout?: OutputNumber; - output?: TransactionOutput; - timestamp: Timestamp; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/runes/api/etchings/index.mdx b/content/docs/bitcoin/runes/api/etchings/index.mdx deleted file mode 100644 index 794b099d9..000000000 --- a/content/docs/bitcoin/runes/api/etchings/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Etchings -index: true -toc: false -description: Retrieves information about Rune etchings. ---- diff --git a/content/docs/bitcoin/runes/api/index.mdx b/content/docs/bitcoin/runes/api/index.mdx deleted file mode 100644 index 31001babb..000000000 --- a/content/docs/bitcoin/runes/api/index.mdx +++ /dev/null @@ -1,38 +0,0 @@ ---- -title: Overview -description: The Runes API provides you with fast, reliable data for Bitcoin Runes via an easy-to-use REST interface. ---- - -The Runes API is a service that helps you with the complete ingestion of Bitcoin Runes data. Using our endpoints, you can retrieve metadata for a particular rune, trading activity, all runes held by a particular address, and more. - -The Runes API uses REST endpoints and cached responses in order to optimize performance and reduce unnecessary requests. Reliable, consistent runes data, one request away. - -## Popular endpoints - - - - - - - -### Related tools - -{/* - **[Runehook](/bitcoin/runes/runeshook)**: Want to run your own infra? [Set up your own Runehook](/bitcoin/runes/runeshook/guides/runehook-as-a-service), the indexer that powers the Rune API. */} -- **[Ordinals API](/bitcoin/ordinals/api)**: Looking for on-chain ordinals data without the front end? Leverage the Ordinals API. -- **[Ordinals Explorer](https://ordinals.hiro.so/)**: The Ordinals API powers Hiro’s Ordinals Explorer, which lets you rapidly discover inscriptions and verify on-chain activity. - ---- - -Need help building with Runes API? Reach out to us on the `#ordinals` channel on Discord. Or join us at our weekly office hours on Discord every Monday at 11am ET. diff --git a/content/docs/bitcoin/runes/api/info/index.mdx b/content/docs/bitcoin/runes/api/info/index.mdx deleted file mode 100644 index fcce4b16d..000000000 --- a/content/docs/bitcoin/runes/api/info/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Status -index: true -toc: false -description: Retrieves information about the Rune API status. ---- diff --git a/content/docs/bitcoin/runes/api/info/status.mdx b/content/docs/bitcoin/runes/api/info/status.mdx deleted file mode 100644 index 7abc0108c..000000000 --- a/content/docs/bitcoin/runes/api/info/status.mdx +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: Get API Status -description: Retrieves the status of the API. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## API Status - -Displays the status of the API - -| Status code | Description | -| :------ | :------ | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/runes/v1/" -``` - - - - - -```js -fetch("https://api.hiro.so/runes/v1/", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "server_version": "", - "status": "string", - "block_height": 0 -} -``` - - - - - -```ts -export interface ApiStatusResponse { - server_version: string; - status: string; - block_height?: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/bitcoin/runes/api/meta.json b/content/docs/bitcoin/runes/api/meta.json deleted file mode 100644 index e776a606c..000000000 --- a/content/docs/bitcoin/runes/api/meta.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "title": "Runes API", - "root": true, - "pages": [ - "---Runes API---", - "index", - "---API Reference---", - "etchings", - "activities", - "balances", - "info" - ] -} diff --git a/content/docs/bitcoin/runes/api/usage.mdx b/content/docs/bitcoin/runes/api/usage.mdx deleted file mode 100644 index cac19982d..000000000 --- a/content/docs/bitcoin/runes/api/usage.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Usage -description: Create your first project in less than 2 minutes ---- - -The Usage section should focus on practical, hands-on instructions for getting started with the API. This includes: -Authentication: How to authenticate with the API (e.g., API keys, OAuth tokens). -Making Requests: Basic examples of making requests to the API, including request format, essential headers, and parameters. -Handling Responses: Information on response structure, understanding status codes, and error handling. -Rate Limits: If applicable, explain any rate limits and best practices for avoiding them. -The goal of the "Usage" section is to equip developers with the knowledge to make successful API calls and handle responses effectively. diff --git a/content/docs/bitcoin/runes/explorer/guides/build-explorer.mdx b/content/docs/bitcoin/runes/explorer/guides/build-explorer.mdx deleted file mode 100644 index 18e66abab..000000000 --- a/content/docs/bitcoin/runes/explorer/guides/build-explorer.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: Build Ordinals Explorer ---- - -After installing and configuring your environment, you can run the Ordinals Explorer locally if you wish by running the followning `npm` command: - -`npm run dev` - -## Building for production - -You may also build a production version of the Ordinals Explorer. To do that, simply run the following command: - -`npm run build` - - - Running `npm run build` also run the default next.js build task. - diff --git a/content/docs/bitcoin/runes/explorer/index.mdx b/content/docs/bitcoin/runes/explorer/index.mdx deleted file mode 100644 index d747b9291..000000000 --- a/content/docs/bitcoin/runes/explorer/index.mdx +++ /dev/null @@ -1,35 +0,0 @@ ---- -# The default id is the same as the one defined below. so not needed -title: Overview -description: Explore and verify ordinals and BRC-20 data on Bitcoin. ---- - -import Link from "next/link"; -import { Button } from "@/components/ui/button" - -The Ordinals Explorer lets you explore and verify Bitcoin Ordinals and BRC-20 token data. You can also use a variety of filters to discover inscriptions. We maintain and support the [Ordinals Explorer](https://ordinals.hiro.so) as a service for the community, but you can also run your own instance of the explorer if you so choose. - -
- - -
- -### Related tools - -- **[Ordinals API](/bitcoin/ordinals/api)**: Looking for on-chain data without the front end? Leverage the Ordinals API. -- **[Stacks Explorer](https://explorer.hiro.so)**: Looking for a front end to verify activity on the Stacks blockchain? Try the Stacks Explorer. - ---- - -Need help building with the Ordinals Explorer? Reach out to us on the `#ordinals` channel on Discord under the [Hiro Developer Tools section](https://stacks.chat/). There’s also a [weekly office hours](https://events.stacks.co/event/HD16484710) on Discord every Thursday at 11am ET. diff --git a/content/docs/bitcoin/runes/explorer/meta.json b/content/docs/bitcoin/runes/explorer/meta.json deleted file mode 100644 index 3f42be985..000000000 --- a/content/docs/bitcoin/runes/explorer/meta.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "title": "Explorer", - "root": true, - "pages": [ - "---Ordinals Explorer---", - "index" - ] -} diff --git a/content/docs/bitcoin/runes/runehook/index.mdx b/content/docs/bitcoin/runes/runehook/index.mdx deleted file mode 100644 index 02d8b226c..000000000 --- a/content/docs/bitcoin/runes/runehook/index.mdx +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: Overview -description: Runehook enables you to build Rune event streams, so you can create accurate, lightweight databases that gracefully handle Bitcoin forks and reorgs. ---- - -import { Step, Steps } from 'fumadocs-ui/components/steps'; - -Runehook is a reorg-aware indexer that automatically handles chain forks, so you don’t need to waste time or resources reindexing your database yourself. - -With a familiar event-driven framework, you can customize what Rune data you index in order to create lightweight databases for faster query responses and a better user experience. - -### Create event streams - - -### Related tools - -- **[Runes API](/bitcoin/runes/api)**: Skip the infrastructure setup and get the runes data you need from our Runes API, which is powered by Runehook. -- **[Ordinals Explorer](/ordinals/explorer)**: Explore Ordinals inscriptions and BRC-20 tokens rapidly in our Ordinals Explorer. - ---- - -_Need help building with Runehook?_ Reach out to us on the `#chainhook` channel on Discord under **Hiro Developer Tools** section. We also host a weekly office hours on Discord every Monday at 11am ET. diff --git a/content/docs/bitcoin/runes/runehook/installation.mdx b/content/docs/bitcoin/runes/runehook/installation.mdx deleted file mode 100644 index 97a2e068c..000000000 --- a/content/docs/bitcoin/runes/runehook/installation.mdx +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Installation -description: Runehook was developed to be environment-agnostic. Below are the different ways to install and build the Bitcoin Indexer on your machine. -toc: false ---- -Clone the [Runehook repository](https://github.com/hirosystems/runehook) to your local machine and install via `cargo`. - -```terminal -$ git clone https://github.com/hirosystems/runehook.git -$ cd runehook -$ cargo runehook-install -``` \ No newline at end of file diff --git a/content/docs/bitcoin/runes/runehook/meta.json b/content/docs/bitcoin/runes/runehook/meta.json deleted file mode 100644 index 9083009a7..000000000 --- a/content/docs/bitcoin/runes/runehook/meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "title": "Runehook", - "root": true, - "pages": [ - "---Runehook---", - "index", - "installation", - "quickstart", - "---Guides---" - ] -} diff --git a/content/docs/bitcoin/runes/runehook/quickstart.mdx b/content/docs/bitcoin/runes/runehook/quickstart.mdx deleted file mode 100644 index 8edd6ee0b..000000000 --- a/content/docs/bitcoin/runes/runehook/quickstart.mdx +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Quickstart -description: Learn how to scan the Bitcoin blockchain for Runes activity. ---- - -import { ChevronRight, Code, Terminal } from 'lucide-react'; -import { File, Folder, Files } from 'fumadocs-ui/components/files'; -import { Step } from 'fumadocs-ui/components/steps'; -import { SmallCard } from '@/components/card'; - -In this quickstart guide, you will set up `runehook` to explore and index Rune activity on the Bitcoin blockchain. You will learn how to install, configure, and run basic commands to scan and stream Rune inscriptions and transfers. - -{/* Check out the [Runehook as a service](/bitcoin/runehook/guides/runehook-as-a-service) for a more advanced use case. */} - ---- - -### Prerequisites - -Before starting, ensure you have `runehook` installed. If you haven't already, check out the [installation](/bitcoin/runehook/installation) guide. - ---- - -### Next steps - - - } - href="/bitcoin/runes/api" - title="Integrate runes data into your app" - description="Use the Runes API to get reliable data for Runes and BRC-20 tokens." - tag='Runes API' - /> - diff --git a/content/docs/guides/api-keys.mdx b/content/docs/guides/api-keys.mdx deleted file mode 100644 index 6799efe2c..000000000 --- a/content/docs/guides/api-keys.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: API keys -description: For developers who need API requests beyond the standard rate limits. ---- - -import ApiKeysContent from '@/snippets/api-keys.mdx'; - - diff --git a/content/docs/guides/contributors-guide.mdx b/content/docs/guides/contributors-guide.mdx deleted file mode 100644 index 1848ec856..000000000 --- a/content/docs/guides/contributors-guide.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: Contributors guide -description: Learn how to contribute to Hiro's documentation and content. ---- - -import ContributorsGuideContent from '@/snippets/contributors-guide.mdx'; - - diff --git a/content/docs/guides/index.mdx b/content/docs/guides/index.mdx deleted file mode 100644 index f30f85a7d..000000000 --- a/content/docs/guides/index.mdx +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Home -toc: false ---- - -import Link from "fumadocs-core/link"; -import { ImageZoom } from 'fumadocs-ui/components/image-zoom'; -import { SecondaryCard } from "@/components/card" -import guidesImage from '@/public/guides.svg'; -import data from '@/utils/all-guides.json'; - -
-
- -
- - - {data.guides.map(guide => { - return ( - - ) - })} - -
\ No newline at end of file diff --git a/content/docs/guides/installing-docker.mdx b/content/docs/guides/installing-docker.mdx deleted file mode 100644 index ea13effcd..000000000 --- a/content/docs/guides/installing-docker.mdx +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: How to install Docker -description: Install Docker to run a local devnet. ---- - - - - 1. Go to the [Docker Desktop for Mac](https://www.docker.com/products/docker-desktop/) page. - 2. Download the .dmg file. - 3. Open the downloaded .dmg file. - 4. Drag the Docker icon to the Applications folder. - 5. Open Docker from the Applications folder. - 6. Grant the necessary permissions if prompted. - 7. Docker Desktop icon will appear in the menu bar indicating that Docker is running. - - To verify installation, run `docker --version` in your terminal. You should see the Docker version information. - - - - 1. Go to the [Docker Desktop for Windows](https://www.docker.com/products/docker-desktop/) page. - 2. Download the executable. - 3. Run the downloaded executable. - 4. Follow the installation wizard steps (you may need to restart your computer). - 5. Ensure the WSL 2 (Windows Subsystem for Linux) backend is checked during installation, if applicable. - 6. Open Docker Desktop from the Start menu. - 7. Grant the necessary permissions if prompted. - 8. Docker icon will appear in the system tray indicating Docker is running. - - To verify installation, run `docker --version` in your terminal. You should see the Docker version information. - - - You might need to install additional Windows components like Hyper-V or WSL 2. - - - - ---- - -## Next steps - - - - - \ No newline at end of file diff --git a/content/docs/guides/meta.json b/content/docs/guides/meta.json deleted file mode 100644 index 6c4f376fc..000000000 --- a/content/docs/guides/meta.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "title": "guides", - "root": true, - "pages": [ - "index", - "-------", - "build-an-nft-marketplace", - "build-a-decentralized-kickstarter", - "using-clarity-values", - "no-loss-lottery", - "---Other---", - "installing-docker", - "sync-a-bitcoin-node", - "sync-a-stacks-node", - "------", - "api-keys", - "rate-limiting", - "contributors-guide" - ] -} diff --git a/content/docs/guides/rate-limiting.mdx b/content/docs/guides/rate-limiting.mdx deleted file mode 100644 index 6fd441850..000000000 --- a/content/docs/guides/rate-limiting.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: Rate limiting -description: Understand the rate limits for Hiro APIs and the STX Faucet. ---- - -import RateLimitingContent from '@/snippets/rate-limiting.mdx'; - - diff --git a/content/docs/guides/sync-a-bitcoin-node.mdx b/content/docs/guides/sync-a-bitcoin-node.mdx deleted file mode 100644 index b3c01de2a..000000000 --- a/content/docs/guides/sync-a-bitcoin-node.mdx +++ /dev/null @@ -1,150 +0,0 @@ ---- -title: How to sync a Bitcoin node -description: Learn how to sync a Bitcoin node for building Bitcoin applications. ---- - -import { InlineCode } from '@/components/inline-code'; - -Syncing a Bitcoin node is often one of the first steps a developer takes when building a Bitcoin application. It's a great introduction to the Bitcoin developer ecosystem, and if you're relying on on-chain data, there's no safer way to get that data than doing it yourself. - -In this guide, you will learn how to: - -1. Download Bitcoin Core daemon on your machine -2. Configure `bitcoind` -3. Start syncing your node -4. Properly shutdown and restart your node - - -To get started, we first need to download `bitcoind`. In our example, we'll be using version 25.0. You can select a software version compatible with your device [from this list](https://bitcoincore.org/bin/bitcoin-core-25.0). - - ---- - -## Configure bitcoind - -Once your download is complete, make note of your path to the `bitcoind` executable. - - -When you sync your node, we'll be running the program at `/bitcoin-25.0/bin/bitcoin`, which is where the `bitcoind` executable is located. - - -Next up is a couple configuration steps. - -1. Select or create a directory to store your Bitcoin data. -2. Update the `bitcoin.conf` file to include the path to your Bitcoin data directory. - -The Bitcoin chainstate is pretty large, and you need a place to store it. In this example, we are going to set up a directory called `bitcoin-data` on an external hard drive that we have mounted at `/Volumes/SSD`. - - - This folder, `bitcoin-data`, can be named whatever you like, and can exist locally or in an external hard drive. - - The most important thing is that it should exist in a place that has enough storage to hold all the Bitcoin data we will be receiving once it starts to sync. - - -Now navigate to your `bitcoin.conf` file, which is located in your `/path/to/bitcoin` directory and update the `datadir` field with your directory. - -In this example, it would look like this: - -```bash bitcoin.conf -datadir=/Volumes/SSD/bitcoin-data/ -``` - - - -You can override the default configuration with the following, including the path to where you will be storing all of the Bitcoin data once it starts syncing: - -```bash -datadir=/your-path-to/bitcoin-data/ -server=1 -rpcuser=devnet -rpcpassword=devnet -rpcport=8332 -rpcallowip=0.0.0.0/0 -rpcallowip=::/0 -txindex=1 -listen=1 -discover=0 -dns=0 -dnsseed=0 -listenonion=0 -rpcserialversion=1 -disablewallet=0 -fallbackfee=0.00001 -rpcthreads=8 -blocksonly=1 -dbcache=4096 - -# Start zeromq -zmqpubhashblock=tcp://0.0.0.0:18543 -``` - - - -If you plan to use your node to receive transactions, you will need to make note of the `username` and `password` fields for your node. - - -In the example `bitcoin.conf` above, `devnet` is listed as the default `username` and `password`. - - -## Run the node - -With a finished `bitcoin.conf` file, it's time to start up your node. - -This takes the form of `path/to/bitcoind -conf=path/to/bitcoin.conf`, which in this example looks like: - -```terminal -$ /Volumes/SSD/bitcoin-25.0/bin/bitcoind -conf=/Volumes/SSD/bitcoin-25.0/bitcoin.conf -``` - -After running this command, you will see `zmq_url` entries in your console's stdout, displaying ZeroMQ logs from your Bitcoin node. Congrats! You're now syncing! - - -It might take anywhere from a few hours to a few days to run and fully sync, depending on if it's your first time syncing a node. - - -## Proper shutdown and restart procedure - -1. Shutting down your node -2. Restarting your node - -To shut down your node safely, use the `bitcoin-cli` executable, located inside of the `bin` directory, and run the `stop` command: - -```terminal -$ /path/to/bitcoin-cli \ - --conf=/path/to/bitcoin.conf \ - --rpcuser={{your-rpc-username}} \ - --rpcpassword={{your-rpc-password}} stop -``` - -To start your node back up, all you need to do is refer to the previous steps from above by running `path/to/bitcoind -conf=path/to/bitcoin.conf`. - - - - - 1. Go to the Finder, then the sidebar, and select the disk you want to eject under “Devices”. Click on the eject icon next to the name. - 2. Wait for a confirmation message saying it's safe to eject the device before you unplug the drive. - - - - 1. Open File Explorer, select the drive from the list under “This PC” (PC > Devices and Drives), and click the “Eject” button. - 2. Wait for a confirmation message saying it's safe to eject the device before you unplug the drive. - - - - ---- - -## Next steps - - - - - diff --git a/content/docs/guides/sync-a-stacks-node.mdx b/content/docs/guides/sync-a-stacks-node.mdx deleted file mode 100644 index 2a17308b1..000000000 --- a/content/docs/guides/sync-a-stacks-node.mdx +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: How to sync a Stacks node -description: Learn how to sync a Stacks node for running a local devnet or mainnet. ---- - -import { Code, Terminal } from 'lucide-react'; -import { SmallCard } from '@/components/card'; -import { InlineCode } from '@/components/inline-code'; - -Running a Stacks node is crucial for developers aiming to interact directly with the Stacks blockchain. It allows for the verification of transactions, ensures decentralized operations, and enhances blockchain security. - -In this guide, you will learn how to: - -1. [Clone the Stacks blockchain Docker repository](#clone-the-stacks-blockchain-docker-repository). -2. [Start the service](#start-the-service). -3. [Monitor the node's synchronization process](#monitor-the-nodes-synchronization-process). - ---- - -## Clone the Stacks blockchain Docker repository - -Clone the Stacks blockchain Docker repository from GitHub: - -```terminal -$ git clone git@github.com:hirosystems/stacks-blockchain-docker.git -$ cd stacks-blockchain-docker -``` - -## Start the service - -Inside of the `stacks-blockchain-docker` directory, run the following command to start the Stacks node: - -```terminal -$ chmod +x manage.sh -$ ./manage.sh -n -a start -``` - -The `` placeholder used below can be replaced with one of: - -- `mainnet` -- `testnet` -- `mocknet` - -## Monitor the node's synchronization process - -To follow the logs for the Stacks node, run the following command: - -```terminal -$ ./manage.sh -n -a logs -``` - -For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. - ---- - -## Next steps - - - - - diff --git a/content/docs/meta.json b/content/docs/meta.json new file mode 100644 index 000000000..f73a14add --- /dev/null +++ b/content/docs/meta.json @@ -0,0 +1,10 @@ +{ + "title": "hiro", + "root": true, + "pages": [ + "...tools", + "...apis", + "...reference", + "...resources" + ] +} diff --git a/content/docs/reference/stacks.js/(connect)/broadcast-transactions.mdx b/content/docs/reference/stacks.js/(connect)/broadcast-transactions.mdx new file mode 100644 index 000000000..b8fbe4d4c --- /dev/null +++ b/content/docs/reference/stacks.js/(connect)/broadcast-transactions.mdx @@ -0,0 +1,164 @@ +--- +title: Broadcast transactions +description: Prompt users to sign transactions and broadcast them to the Stacks blockchain. +--- + +import { Badge } from '@/components/ui/badge'; +import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; + +import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; +import { ChevronRight, Code, Terminal } from 'lucide-react'; +import { File, Folder, Files } from 'fumadocs-ui/components/files'; + +The process of broadcasting transactions is fundamental for interacting with blockchains, whether you're transferring tokens, deploying contracts, or executing contract functions. + +In this guide, you will learn how to: + +1. [Install the necessary packages](#setup-and-installation) +2. [Connect to a user's wallet](#connect-to-a-users-wallet) +3. [Sign and broadcast transactions](#sign-and-broadcast-transactions) +4. [Handle transaction results](#handle-transaction-results) + +--- + +## Setup and installation + +Install the required packages to start building and broadcasting transactions: + +```package-install +@stacks/connect @stacks/transactions +``` + +## Connect to a user's wallet + +Before signing transactions, users need to connect their wallet to your application. Use the `connect` function to initiate a wallet connection: + +```ts +import { connect, isConnected } from '@stacks/connect'; + +async function connectWallet() { + if (!isConnected()) { + const response = await connect(); + console.log('Connected with addresses:', response); + } +} +``` + +## Sign and broadcast transactions + +There are three types of transactions you can create: STX transfers, contract deployments, and contract calls. + + + + + STX transfer + + + Contract deployment + + + Contract execution + + + + To transfer STX tokens, use the `request` method with `stx_transferStx`: + + ```ts + import { request } from '@stacks/connect'; + + async function transferStx() { + const response = await request('stx_transferStx', { + recipient: 'ST2EB9WEQNR9P0K28D2DC352TM75YG3K0GT7V13CV', + amount: '100', // in micro-STX (1 STX = 1,000,000 micro-STX) + memo: 'Reimbursement', // optional + }); + + console.log('Transaction ID:', response.txId); + } + ``` + + + To deploy a smart contract, use the `request` method with `stx_deployContract`: + + ```ts + import { request } from '@stacks/connect'; + + async function deployContract() { + const codeBody = '(define-public (say-hi) (ok "hello world"))'; + + const response = await request('stx_deployContract', { + name: 'my-contract', + code: codeBody, + clarityVersion: 3, // optional, defaults to latest version + }); + + console.log('Transaction ID:', response.txId); + } + ``` + + Contracts will deploy to the Stacks address of the connected wallet. + + + To call a contract function, use the `request` method with 'stx_callContract'. Here's an example using a simple contract: + + ```clarity + (define-public (say-hi) + (print "hi") + (ok u0) + ) + ``` + + Here's how to call this function: + + ```ts + import { request } from '@stacks/connect'; + import { Cl } from '@stacks/transactions'; + + async function callContract() { + const response = await request('stx_callContract', { + contractAddress: 'ST22T6ZS7HVWEMZHHFK77H4GTNDTWNPQAX8WZAKHJ', + contractName: 'my-contract', + functionName: 'say-hi', + functionArgs: [], // array of Clarity values + }); + + console.log('Transaction ID:', response.txId); + } + ``` + + For functions that take arguments, you can use the `Cl` namespace to construct Clarity values: + + ```ts + const functionArgs = [ + Cl.uint(123), + Cl.stringAscii("hello"), + Cl.standardPrincipalCV("ST1X.."), + ]; + ``` + + + +## Handle transaction results + +When a transaction is signed and broadcast, the `request` method returns a response object containing information about the transaction: + +```ts +interface TransactionResponse { + txId: string; // The transaction ID + txRaw: string; // The raw transaction hex +} +``` + +You can use the transaction ID to create a link to view the transaction in the explorer: + +```ts +async function handleTransaction() { + const response = await request('stx_transferStx', { + recipient: 'ST2EB9WEQNR9P0K28D2DC352TM75YG3K0GT7V13CV', + amount: '100', + }); + + const explorerUrl = `https://explorer.stacks.co/txid/${response.txId}`; + console.log('View transaction in explorer:', explorerUrl); +} +``` \ No newline at end of file diff --git a/content/docs/reference/stacks.js/(connect)/connect-wallet.mdx b/content/docs/reference/stacks.js/(connect)/connect-wallet.mdx new file mode 100644 index 000000000..1e819bf9a --- /dev/null +++ b/content/docs/reference/stacks.js/(connect)/connect-wallet.mdx @@ -0,0 +1,131 @@ +--- +title: Connect wallet +description: Learn how to connect to Stacks wallets and authenticate users. +--- + +Learn how to integrate wallet connections into your Stacks application. Connecting a wallet authenticates users and enables blockchain interactions like transfers and contract calls. + +:::objectives +- Install the `@stacks/connect` package +- Connect to a wallet and authenticate users +- Manage authentication state +- Access user account data +::: + +:::prerequisites +- Node.js installed on your machine +- A web application setup (React, Vue, or vanilla JS) +- Basic understanding of async/await +::: + +## Quickstart + + + + ### Install package + + Add the Stacks Connect package to your project. + + ```package-install + @stacks/connect + ``` + + This package provides all the functions needed for wallet connections and user authentication. + + + + ### Connect and authenticate + + The `connect` function initiates wallet connection and stores user data in local storage for session persistence. + + ```ts + import { connect, isConnected } from '@stacks/connect'; + + async function connectWallet() { + // Check if already connected + if (isConnected()) { + console.log('Already authenticated'); + return; + } + + // Connect to wallet + const response = await connect(); + console.log('Connected:', response.addresses); + } + ``` + + Manage the authentication state throughout your app. + + ```ts + import { disconnect, isConnected } from '@stacks/connect'; + + // Check authentication status + const authenticated = isConnected(); + + // Logout function + function logout() { + disconnect(); // Clears storage and wallet selection + console.log('User disconnected'); + } + ``` + + + + ### Access user data + + Retrieve stored addresses and request detailed account information. + + ```ts + import { getLocalStorage, request } from '@stacks/connect'; + + // Get stored addresses from local storage + const userData = getLocalStorage(); + if (userData?.addresses) { + const stxAddress = userData.addresses.stx[0].address; + const btcAddress = userData.addresses.btc[0].address; + console.log('STX:', stxAddress); + console.log('BTC:', btcAddress); + } + ``` + + Get detailed account information including public keys. + + ```ts + // Request full account details + const accounts = await request('stx_getAccounts'); + const account = accounts.addresses[0]; + + console.log('Address:', account.address); + console.log('Public key:', account.publicKey); + console.log('Gaia URL:', account.gaiaHubUrl); + ``` + + + + ### Make your first transaction + + Use the authenticated connection to send STX tokens. + + ```ts + import { request } from '@stacks/connect'; + + async function sendTransaction() { + const response = await request('stx_transferStx', { + amount: '1000000', // 1 STX in micro-STX + recipient: 'SP2MF04VAGYHGAZWGTEDW5VYCPDWWSY08Z1QFNDSN', + memo: 'First transfer', // optional + }); + + console.log('Transaction ID:', response.txid); + } + ``` + + The wallet will prompt the user to approve the transaction before broadcasting. + + + + +:::next-steps +- [Sign messages](/reference/stacks.js/message-signing): Prove address ownership +- [Broadcast transactions](/reference/stacks.js/broadcast-transactions): Learn about different transaction types +::: \ No newline at end of file diff --git a/content/docs/reference/stacks.js/(connect)/message-signing.mdx b/content/docs/reference/stacks.js/(connect)/message-signing.mdx new file mode 100644 index 000000000..3b2de4b79 --- /dev/null +++ b/content/docs/reference/stacks.js/(connect)/message-signing.mdx @@ -0,0 +1,198 @@ +--- +title: Sign messages +description: Learn how to sign and verify messages to prove address ownership and authorize actions +--- + +Learn how to implement message signing in your Stacks application. Message signing allows users to cryptographically prove they control an address without making an on-chain transaction, enabling authentication, authorization, and verifiable statements. + +:::objectives +- Connect to a user's wallet and request message signatures +- Sign both simple text messages and structured data +- Verify signatures to ensure authenticity +::: + +:::prerequisites +- Node.js installed on your machine +- A code editor like VS Code +::: + +## Installation + +Install the required packages for message signing and verification. + +```package-install +@stacks/connect @stacks/encryption +``` + +## Connect to wallet + +Before signing messages, establish a connection to the user's wallet. The connection persists across page reloads. + +```ts +import { connect, isConnected } from '@stacks/connect'; + +async function connectWallet() { + if (!isConnected()) { + const response = await connect(); + console.log('Connected addresses:', response.addresses); + } +} +``` + +Call this function when your app loads or when the user clicks a connect button. + +## Sign text messages + +Request a signature for a simple text message using the `request` method. + +```ts +import { request } from '@stacks/connect'; + +async function signMessage() { + const message = 'Hello World'; + + const response = await request('stx_signMessage', { + message, + }); + + console.log('Signature:', response.signature); + console.log('Public key:', response.publicKey); + + return response; +} +``` + +The wallet will display the message to the user for approval before signing. + +## Sign structured data + +For more complex data, use structured message signing with Clarity values. + +```ts +import { request } from '@stacks/connect'; +import { Cl } from '@stacks/transactions'; + +async function signStructuredMessage() { + const message = Cl.tuple({ + action: Cl.stringAscii('transfer'), + amount: Cl.uint(1000), + recipient: Cl.stringAscii('alice.btc') + }); + + const domain = Cl.tuple({ + name: Cl.stringAscii('My App'), + version: Cl.stringAscii('1.0.0'), + 'chain-id': Cl.uint(1) // 1 for mainnet + }); + + const response = await request('stx_signStructuredMessage', { + message, + domain + }); + + return response; +} +``` + +Structured messages provide better type safety and are easier to parse on-chain. + +## Verify signatures + +Validate signatures to ensure they match the expected message and public key. + +```ts +import { verifyMessageSignatureRsv } from '@stacks/encryption'; + +async function verifySignature( + message: string, + signature: string, + publicKey: string +): Promise { + const isValid = verifyMessageSignatureRsv({ + message, + signature, + publicKey + }); + + if (isValid) { + console.log('✓ Signature verified successfully'); + } else { + console.log('✗ Invalid signature'); + } + + return isValid; +} +``` + +Always verify signatures before trusting the signed data. + +### Complete verification flow + +```ts +async function signAndVerify() { + // Request signature + const message = 'Authorize login at ' + new Date().toISOString(); + const signResponse = await request('stx_signMessage', { message }); + + // Verify immediately + const isValid = await verifySignature( + message, + signResponse.signature, + signResponse.publicKey + ); + + if (isValid) { + // Proceed with authenticated action + console.log('Authentication successful'); + } +} +``` + +## Try it out + +Create a simple authentication system using message signatures. + +```ts +// Generate a unique challenge +function generateChallenge(): string { + const nonce = Math.random().toString(36).substring(7); + const timestamp = Date.now(); + return `Sign this message to authenticate:\nNonce: ${nonce}\nTime: ${timestamp}`; +} + +// Complete auth flow +async function authenticate() { + const challenge = generateChallenge(); + + try { + const response = await request('stx_signMessage', { + message: challenge + }); + + const isValid = verifyMessageSignatureRsv({ + message: challenge, + signature: response.signature, + publicKey: response.publicKey + }); + + if (isValid) { + // Store auth token or session + localStorage.setItem('auth', JSON.stringify({ + publicKey: response.publicKey, + timestamp: Date.now() + })); + + return { success: true }; + } + } catch (error) { + console.error('Authentication failed:', error); + } + + return { success: false }; +} +``` + +:::next-steps +- [Broadcast transactions](/reference/stacks.js/broadcast-transactions): Learn how to sign and broadcast transactions +- [Connect API reference](/reference/stacks.js/packages/connect): Explore all available methods +::: \ No newline at end of file diff --git a/content/docs/reference/stacks.js/(connect)/meta.json b/content/docs/reference/stacks.js/(connect)/meta.json new file mode 100644 index 000000000..1968abfa1 --- /dev/null +++ b/content/docs/reference/stacks.js/(connect)/meta.json @@ -0,0 +1,11 @@ +{ + "title": "Stacks Connect", + "defaultOpen": false, + "pages": [ + "connect-wallet", + "broadcast-transactions", + "message-signing", + "migration-guide", + "wallet-support" + ] +} \ No newline at end of file diff --git a/content/docs/reference/stacks.js/(connect)/migration-guide.mdx b/content/docs/reference/stacks.js/(connect)/migration-guide.mdx new file mode 100644 index 000000000..cc68e2e6b --- /dev/null +++ b/content/docs/reference/stacks.js/(connect)/migration-guide.mdx @@ -0,0 +1,105 @@ +--- +title: Migration Guide +description: How to migrate from v7.x.x to v8.x.x of @stacks/connect +--- + +import { Steps, Step } from 'fumadocs-ui/components/steps' + + +For a while now, the Stacks community has been working on a new standard for wallet-to-dapp communication. +Stacks Connect and related projects now use standards like [WBIPs](https://wbips.netlify.app/) and [SIP-030](https://github.com/janniks/sips/blob/main/sips/sip-030/sip-030-wallet-interface.md) to allow wallets to communicate with dapps in a more simplified and flexible way. + +:::callout +### Migration Status +Please be patient during this latest migration. +There has been a long-running effort together with wallets to modernize and move forward the Stacks web ecosystem. +It is now culminating in [SIP-030](https://github.com/janniks/sips/blob/main/sips/sip-030/sip-030-wallet-interface.md) and the new `request` method in Stacks Connect `8.x.x`. +Bear with us during this migration. +Wallets are still working through some bugs, details, and improvements. + +**Feel free to continue using Stacks Connect `7.x.x` while things stabilize.** +The `7.x.x` version may still be more well supported by some wallets. + +For the legacy version of `@stacks/connect` using JWT tokens, you can use: + +```sh +npm install @stacks/connect@7.10.1 +``` +::: + +## Deprecations + +The following classes, methods, and types are deprecated in favor of the new `request` RPC methods: + +- `show...` and `open...` methods +- `authenticate` method +- `UserSession` class and related functionality +- `AppConfig` class +- `SessionOptions` interface +- `SessionData` interface +- `UserData` interface +- `SessionDataStore` class +- `InstanceDataStore` class +- `LocalStorageStore` class + +:::callout +### Backwards Compatibility +To make migrating easier, the familiar `UserSession` & `AppConfig` class still exists and is semi-backwards compatible for the `8.x.x` release. +It will "cache" the user's address in local storage and allow access to it via the `loadUserData` method (as previously done). +::: + +## Migration Steps + +To update from `<=7.x.x` to latest/`8.x.x`, follow these steps: + + + + ```sh + npm install @stacks/connect@latest + ``` + + + + Switch from `showXyz`, `openXyz`, `doXyz` methods to the `request` method: + + - `request` follows the pattern `request(method: string, params: object)`, see [Usage](#usage) for more details + - `request` is an async function, so replace the `onFinish` and `onCancel` callbacks with `.then().catch()` or `try & await` + + Examples: + - `showConnect()`, `authenticate()` → `connect()` + - `useConnect().doContractCall({})` → `request("stx_callContract", {})` + - `openContractDeploy()` → `request("stx_deployContract", {})` + + + + Switch from `showConnect` or `authenticate` to `connect()` methods: + + - `connect()` is an alias for `request({forceWalletSelect: true}, 'getAddresses')` + - `connect()` by default caches the user's address in local storage + + + + - Switch from `UserSession.isSignedIn()` to `isConnected()` + - Switch from `UserSession.signUserOut()` to `disconnect()` + + + + - Remove code referencing deprecated methods (`AppConfig`, `UserSession`, etc.) + - Remove the `@stacks/connect-react` package + - You may need to manually reload a component to see local storage updates + - No custom hooks are needed to use Stacks Connect anymore + - We are working on a new `@stacks/react` package that will make usage even easier in the future (e.g., tracking transaction status, reloading components when a connection is established, updating the page when the network changes, and more) + + + +## Address Access + +Previously, the `UserSession` class was used to access the user's addresses and data, which abstracted away the underlying implementation details. +Now, the `request` method is used to directly interact with the wallet, giving developers more explicit control and clarity over what's happening under the hood. +This manual approach makes the wallet interaction more transparent and customizable. +Developers can manually manage the currently connected user's address in e.g. local storage, jotai, etc. or use the `connect()`/`request()` method to cache the address in local storage. + +:::callout +### Security Note +For security reasons, the `8.x.x` release only returns the current network's address (where previously both mainnet and testnet addresses were returned). +::: diff --git a/content/docs/reference/stacks.js/(connect)/wallet-support.mdx b/content/docs/reference/stacks.js/(connect)/wallet-support.mdx new file mode 100644 index 000000000..02f704680 --- /dev/null +++ b/content/docs/reference/stacks.js/(connect)/wallet-support.mdx @@ -0,0 +1,59 @@ +--- +title: Wallet Support +description: Compatibility information for different wallet providers +--- + +This page provides detailed information about which methods and events are supported by different wallet providers in the Stacks ecosystem. + +## Method Compatibility + +| Method | Leather | Xverse-like | +|-----------------------------|----------------------------------------------|---------------------------------------------------------------| +| `getAddresses` | 🟡 No support for experimental purposes | 🟡 Use `wallet_connect` instead | +| `sendTransfer` | 🟡 Expects `amount` as string | 🟡 Expects `amount` as number | +| `signPsbt` | 🟡 Uses signing index array only | 🟡 Uses `signInputs` record instead of array | +| `stx_getAddresses` | 🟢 | 🔴 | +| `stx_getAccounts` | 🔴 | 🟢 | +| `stx_getNetworks` | 🔴 | 🔴 | +| `stx_transferStx` | 🟢 | 🟢 | +| `stx_transferSip10Ft` | 🟢 | 🔴 | +| `stx_transferSip9Nft` | 🟢 | 🔴 | +| `stx_callContract` | 🟡 Hex-encoded Clarity values only | 🟡 Hex-encoded Clarity values only, no support for `postConditions` | +| `stx_deployContract` | 🟡 Hex-encoded Clarity values only | 🟡 Hex-encoded Clarity values only, no support for `postConditions` | +| `stx_signTransaction` | 🟡 Hex-encoded Clarity values only | 🟡 Hex-encoded Clarity values only | +| `stx_signMessage` | 🟡 Hex-encoded Clarity values only | 🟡 Hex-encoded Clarity values only | +| `stx_signStructuredMessage` | 🟡 Hex-encoded Clarity values only | 🟡 Hex-encoded Clarity values only | +| `stx_updateProfile` | 🔴 | 🔴 | + +## Event Compatibility + +| Event | Leather | Xverse | +|---------------------|---------|--------| +| `stx_accountChange` | 🔴 | 🔴 | +| `stx_networkChange` | 🔴 | 🔴 | + +**Legend** + +- 🔴 No support (yet) +- 🟡 Partial support +- 🟢 Supported + +## Compatibility Layer + +The `request` method in `@stacks/connect` adds a layer of auto-compatibility for different wallet providers. This helps unify the interface where wallet providers may implement methods and results differently. + +| Method | Status | Notes | +| --------------------------- | ------ | ---------------------------------------------------------------------------------------------------- | +| `getAddresses` | 🔵 | Maps to `wallet_connect` for Xverse-like wallets | +| `sendTransfer` | 🔵 | Converts `amount` to number for Xverse, string for Leather | +| `signPsbt` | 🟡 | Transforms PSBT format for Leather (base64 to hex) with lossy restructure of `signInputs` | +| `stx_getAddresses` | 🔵 | Maps to `wallet_connect` for Xverse-like wallets | +| `stx_callContract` | 🔵 | Transforms Clarity values to hex-encoded format for compatibility | +| `stx_deployContract` | 🔵 | Transforms Clarity values to hex-encoded format for compatibility | +| `stx_signTransaction` | 🔵 | Transforms Clarity values to hex-encoded format for compatibility | +| `stx_signMessage` | 🔵 | Transforms Clarity values to hex-encoded format for compatibility | +| `stx_signStructuredMessage` | 🔵 | Transforms Clarity values to hex-encoded format for compatibility | + +- 🟢 No overrides needed for any wallet +- 🔵 Has compatibility overrides that maintain functionality +- 🟡 Has breaking overrides that may lose some information diff --git a/content/docs/reference/stacks.js/(integrations)/meta.json b/content/docs/reference/stacks.js/(integrations)/meta.json new file mode 100644 index 000000000..439071b54 --- /dev/null +++ b/content/docs/reference/stacks.js/(integrations)/meta.json @@ -0,0 +1,7 @@ +{ + "title": "Integrations", + "pages": [ + "pyth-oracle-integration", + "react-native-integration" + ] +} \ No newline at end of file diff --git a/content/docs/reference/stacks.js/(integrations)/pyth-oracle-integration.mdx b/content/docs/reference/stacks.js/(integrations)/pyth-oracle-integration.mdx new file mode 100644 index 000000000..d252fca50 --- /dev/null +++ b/content/docs/reference/stacks.js/(integrations)/pyth-oracle-integration.mdx @@ -0,0 +1,196 @@ +--- +title: Pyth oracle integration +sidebarTitle: Pyth oracle integration +description: In this guide, you'll learn how to integrate Pyth Network price feeds into your frontend application using Stacks.js. +isNew: true +--- + +import { File, Folder, Files } from 'fumadocs-ui/components/files'; +import { Steps, Step } from '@/components/steps'; +import { ArrowRight, Check } from 'lucide-react'; + +:::objectives +- Install and configure the Pyth SDK +- Fetch VAA messages from Hermes API +- Build transactions with oracle data +- Handle post-conditions for oracle fees +::: + +:::prerequisites +- A React or Node.js application with Stacks.js installed +- Understanding of [Pyth oracle contracts](/resources/clarity/integrations/external-data) +::: + +## Quickstart + + + + ### Install dependencies + + Install the Pyth SDK alongside your existing Stacks.js packages: + + ```package-install + @pythnetwork/price-service-client buffer + ``` + + The buffer package is needed for data format conversion in browser environments. + + + + ### Set up the Pyth client + + Create a service to handle Pyth price feed interactions: + + ```typescript services/pyth.ts + import { PriceServiceConnection } from '@pythnetwork/price-service-client'; + import { Buffer } from 'buffer'; + + // Price feed IDs + export const PRICE_FEEDS = { + BTC_USD: '0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43', + STX_USD: '0xec7a775f46379b5e943c3526b1c8d54cd49749176b0b98e02dde68d1bd335c17', + ETH_USD: '0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace', + USDC_USD: '0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a' + }; + + // Initialize Pyth client + const pythClient = new PriceServiceConnection( + 'https://hermes.pyth.network', + { + priceFeedRequestConfig: { + binary: true // Request binary format for on-chain use + } + } + ); + + export async function fetchPriceUpdateVAA(priceFeedId: string): Promise { + try { + // Fetch the latest VAA for the price feed + const vaas = await pythClient.getLatestVaas([priceFeedId]); + + if (!vaas || vaas.length === 0) { + throw new Error('No VAA data received'); + } + + // Convert base64 to hex for Clarity + const messageBuffer = Buffer.from(vaas[0], 'base64'); + const hexString = messageBuffer.toString('hex'); + + return `0x${hexString}`; + } catch (error) { + console.error('Failed to fetch price VAA:', error); + throw error; + } + } + ``` + + + + ### Build oracle-enabled transactions + + Create a transaction that includes fresh price data: + + ```typescript components/PythTransaction.tsx + import { request } from '@stacks/connect'; + import { + Cl, + PostConditionMode + } from '@stacks/transactions'; + import { fetchPriceUpdateVAA, PRICE_FEEDS } from '../services/pyth'; + import { useState } from 'react'; + + export function MintWithOraclePrice() { + const [loading, setLoading] = useState(false); + + const handleMint = async () => { + setLoading(true); + try { + // Fetch fresh price data + const priceVAA = await fetchPriceUpdateVAA(PRICE_FEEDS.BTC_USD); + + // Convert hex string to buffer Clarity value + const vaaBuffer = Cl.bufferFromHex(priceVAA.slice(2)); + + // Call contract with price data using request + const response = await request('stx_callContract', { + contract: 'SP1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRCBGD7R.benjamin-club', + functionName: 'mint-for-hundred-dollars', + functionArgs: [vaaBuffer], + postConditionMode: 'deny', + network: 'mainnet' + }); + + console.log('Transaction submitted:', response.txid); + alert(`NFT minted! Transaction ID: ${response.txid}`); + } catch (error) { + console.error('Minting failed:', error); + alert('Failed to mint NFT'); + } finally { + setLoading(false); + } + }; + + return ( + + ); + } + ``` + + + + ### Add post-conditions for oracle fees + + Pyth oracle updates require a small fee. Include post-conditions when calling contracts: + + ```typescript components/MintWithPostConditions.tsx + import { request } from '@stacks/connect'; + import { Cl, Pc } from '@stacks/transactions'; + import { fetchPriceUpdateVAA, PRICE_FEEDS } from '../services/pyth'; + + export function MintWithPostConditions() { + const handleMint = async () => { + const userAddress = 'SP1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRCBGD7R'; + + // Create post-conditions + const postConditions = [ + // Oracle fee (1 uSTX) + Pc.principal(userAddress).willSendLte(1).ustx(), + // sBTC transfer for $100 worth (example: 100,000 sats) + Pc.principal(userAddress) + .willSendEq(100000) + .ft('SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sbtc-token', 'sbtc') + ]; + + try { + const priceVAA = await fetchPriceUpdateVAA(PRICE_FEEDS.BTC_USD); + + const response = await request('stx_callContract', { + contract: `${userAddress}.benjamin-club`, + functionName: 'mint-for-hundred-dollars', + functionArgs: [Cl.bufferFromHex(priceVAA.slice(2))], + postConditions, + postConditionMode: 'deny', + network: 'mainnet' + }); + + console.log('Transaction successful:', response.txid); + } catch (error) { + console.error('Transaction failed:', error); + } + }; + + return ; + } + ``` + + + +:::next-steps +- [Clarity contracts](/resources/clarity/integrations/external-data): Learn how to integrate Pyth oracle with Clarity contracts. +- [Testing with Clarinet](/tools/clarinet/pyth-oracle-integration): Learn how to test Pyth oracle integration with Clarinet. +::: \ No newline at end of file diff --git a/content/docs/reference/stacks.js/(integrations)/react-native-integration.mdx b/content/docs/reference/stacks.js/(integrations)/react-native-integration.mdx new file mode 100644 index 000000000..e1b8fa866 --- /dev/null +++ b/content/docs/reference/stacks.js/(integrations)/react-native-integration.mdx @@ -0,0 +1,283 @@ +--- +title: Using Stacks.js with React Native +sidebarTitle: React Native integration +description: Learn how to integrate Stacks blockchain functionality into React Native mobile applications +--- + +Stacks.js can be integrated into React Native applications to bring blockchain functionality to mobile devices. This tutorial walks you through setting up a React Native project with Expo and configuring it to work with Stacks.js libraries. + +:::objectives +- Set up an Expo project configured for Stacks.js +- Install and configure necessary polyfills for React Native +- Generate wallets and sign transactions in a mobile app +- Handle React Native's JavaScript environment limitations +- Build a working Stacks mobile application +::: + +:::prerequisites +- Node.js and npm installed on your development machine +- Basic knowledge of React Native and Expo +- Familiarity with Stacks.js concepts +- iOS or Android device/simulator for testing +::: + +## Set up the Expo project + +Start by creating a new Expo project. The latest version of Expo provides the best compatibility with Stacks.js polyfills. + +```terminal +$ npx create-expo-app@latest my-stacks-app +$ cd my-stacks-app +``` + +The boilerplate project includes everything needed to start building. Test the initial setup by running the development server. + +```terminal +$ npm start +``` + +Connect your mobile device using the Expo Go app and scan the QR code to verify the base project works correctly. + +## Install necessary dependencies + +React Native's JavaScript environment lacks certain Node.js and browser APIs that Stacks.js requires. Install the core Stacks libraries along with necessary polyfills. + +```terminal +$ npm install @stacks/transactions @stacks/wallet-sdk +``` + +Install the polyfill dependencies as dev dependencies to handle missing APIs. + +```terminal +$ npm install --save-dev buffer process react-native-get-random-values \ + text-encoding readable-stream crypto-browserify @peculiar/webcrypto +``` + +These polyfills provide: +- `buffer` and `process` - Node.js globals +- `react-native-get-random-values` - Crypto random values +- `text-encoding` - TextEncoder/TextDecoder APIs +- `crypto-browserify` and `@peculiar/webcrypto` - Cryptographic functions + +## Configure Metro bundler + +Metro bundler needs configuration to properly resolve Node.js modules. Create a custom Metro configuration file. + +```terminal +$ npx expo customize metro.config.js +``` + +Update the configuration to map Node.js modules to their React Native-compatible versions. + +```js metro.config.js +const { getDefaultConfig } = require("expo/metro-config"); + +const config = getDefaultConfig(__dirname); + +config.resolver.extraNodeModules = { + stream: require.resolve("readable-stream"), + crypto: require.resolve("crypto-browserify"), +}; + +module.exports = config; +``` + +This configuration ensures that when Stacks.js requests Node.js modules, Metro provides the appropriate polyfills. + +## Set up global polyfills + +Create a polyfill system to make browser and Node.js APIs available in React Native. This requires modifying the app's entry point. + +### Create the polyfill file + +Create a new file to initialize all required global objects. + +```js polyfill.js +import { Buffer } from "buffer/"; +import process from "process"; +import "react-native-get-random-values"; +import { TextDecoder, TextEncoder } from "text-encoding"; + +global.process = process; +global.Buffer = Buffer; +global.TextEncoder = TextEncoder; +global.TextDecoder = TextDecoder; +``` + +### Create custom entry point + +Create a new entry point that loads polyfills before the app starts. + +```js index.js +import "./polyfill"; +import { Crypto } from "@peculiar/webcrypto"; + +Object.assign(global.crypto, new Crypto()); + +import "expo-router/entry"; +``` + +### Update package.json + +Point the app to use the new entry point. + +```json package.json +{ + "main": "index.js", + // ... other configuration +} +``` + +:::callout +type: warn +Polyfills must be loaded in separate files as shown. Loading them in the same file can cause runtime initialization errors. +::: + +## Implement Stacks functionality + +With the environment configured, you can now use Stacks.js in your React Native components. Update the main screen to demonstrate wallet generation and transaction signing. + +### Import Stacks.js modules + +Edit the main screen component to import necessary Stacks.js functions. + +```tsx app/(tabs)/index.tsx +import { + TransactionVersion, + getAddressFromPrivateKey, + makeSTXTokenTransfer, +} from "@stacks/transactions"; +import { Wallet, generateSecretKey, generateWallet } from "@stacks/wallet-sdk"; +import { useState } from "react"; +import { Button } from "react-native"; +``` + +### Set up component state + +Create state variables to manage wallet data and user feedback. + +```tsx app/(tabs)/index.tsx +export default function HomeScreen() { + const [mnemonic, setMnemonic] = useState("Press button to generate"); + const [wallet, setWallet] = useState(null); + const [log, setLog] = useState(""); + + // Component implementation continues... +} +``` + +### Generate wallet and sign transaction + +Implement the core functionality to create a wallet and sign a transaction. + +```tsx app/(tabs)/index.tsx +const generate = async () => { + try { + // Generate a new seed phrase + const mnemonic = generateSecretKey(); + setMnemonic(mnemonic); + + // Create wallet from seed phrase + const wallet = await generateWallet({ + secretKey: mnemonic, + password: "", + }); + setWallet(wallet); + + // Create and sign a transaction + const txOptions = { + amount: 1000, + anchorMode: "any" as const, + recipient: "SP3W993D3BRDYB284CY3SBFDEGTC5XEDJPDEA21CN", + senderKey: wallet.accounts[0].stxPrivateKey, + fee: 300, + network: "testnet" as const, + nonce: 0, + }; + + const transaction = await makeSTXTokenTransfer(txOptions); + setLog("Transaction signed successfully ✓"); + } catch (error) { + setLog(`Error: ${error.message}`); + } +}; +``` + +### Build the user interface + +Create a simple UI to display wallet information and trigger wallet generation. + +```tsx app/(tabs)/index.tsx +return ( + + Stacks Wallet Demo + + + Seed Phrase + {mnemonic} + + ); + } + ``` + + For complete frontend integration details, see our [Stacks.js integration guide](/reference/stacks.js/pyth-oracle-integration). + + + + ### Test your implementation + + Write comprehensive tests using Clarinet: + + ```typescript tests/benjamin-club.test.ts + import { describe, expect, it } from "vitest"; + import { Cl } from '@stacks/transactions'; + + describe("Benjamin Club Tests", () => { + it("should calculate correct sBTC amount", () => { + // Set mock BTC price to $100,000 + simnet.callPublicFn( + "mock-pyth-oracle", + "set-mock-price", + [ + Cl.bufferFromHex(BTC_FEED_ID), + Cl.int(10000000000000), // $100,000 with 8 decimals + Cl.int(-8) + ], + deployer + ); + + // Test price calculation + const response = simnet.callReadOnlyFn( + "benjamin-club", + "get-required-sbtc-amount", + [], + wallet1 + ); + + // $100 at $100k/BTC = 0.001 BTC = 100,000 sats + expect(response.result).toBeOk(Cl.uint(100000)); + }); + }); + ``` + + For advanced testing strategies including mainnet simulation, see our [Clarinet testing guide](/tools/clarinet/pyth-oracle-integration). + + + +## Best practices + +### Price freshness + +Always verify price data is recent enough for your use case: + +```clarity +(define-constant MAX-PRICE-AGE u300) ;; 5 minutes + +(define-private (verify-price-freshness (price-data (tuple))) + (let ((age (- block-height (get publish-time price-data)))) + (asserts! (<= age MAX-PRICE-AGE) ERR-STALE-PRICE) + (ok true))) +``` + +### Error handling + +Implement comprehensive error handling for oracle failures: + +```typescript +try { + const vaa = await fetchBTCPriceVAA(); + // Process VAA... +} catch (error) { + if (error.message.includes('Network')) { + // Retry with exponential backoff + await retryWithBackoff(() => fetchBTCPriceVAA()); + } else { + // Handle other errors + throw error; + } +} +``` + +### Gas optimization + +Batch multiple price updates when possible: + +```clarity +(define-public (update-multiple-prices + (btc-vaa (buff 8192)) + (eth-vaa (buff 8192)) + (stx-vaa (buff 8192))) + (let ((all-vaas (concat btc-vaa (concat eth-vaa stx-vaa)))) + (contract-call? PYTH-ORACLE verify-and-update-price-feeds all-vaas params))) +``` + +## Troubleshooting + +### Common issues + + + + VAA verification fails + + Ensure you're fetching VAA data with `binary: true` option and converting from base64 to hex correctly. The VAA must be recent (typically within 5 minutes). + + + + + Price calculations are incorrect + + Check that you're handling the exponent correctly. Pyth uses fixed-point representation where the actual price = raw_price * 10^exponent. For negative exponents, divide by 10^(-exponent). + + + + + Transaction runs out of gas + + Oracle updates can be gas-intensive. Ensure your gas limits account for both the oracle update and your contract logic. Consider caching prices when multiple operations need the same price. + + + + +## Security considerations + +1. **Price manipulation**: Always use confidence intervals and implement sanity checks +2. **Front-running**: Consider using commit-reveal schemes for price-sensitive operations +3. **Oracle fees**: Set appropriate post-conditions to limit fee exposure +4. **Staleness**: Reject prices older than your security threshold + +## Quick reference + +### Contract addresses + +| Network | Contract | Address | +|---------|----------|---------| +| Mainnet | pyth-oracle-v3 | `SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-oracle-v3` | +| Mainnet | pyth-storage-v3 | `SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-storage-v3` | +| Testnet | pyth-oracle-v3 | `ST3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-oracle-v3` | + +### Price feed IDs + +| Asset | Feed ID | +|-------|---------| +| BTC/USD | `0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43` | +| STX/USD | `0xec7a775f46379b5e943c3526b1c8d54cd49749176b0b98e02dde68d1bd335c17` | +| ETH/USD | `0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace` | +| USDC/USD | `0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a` | + +## Additional resources + +- [Pyth Network documentation](https://docs.pyth.network) +- [Trust Machines Pyth integration](https://github.com/Trust-Machines/stacks-pyth-bridge) +- [Example repository](https://github.com/your-org/benjamin-club-example) +- [Wormhole VAA specification](https://wormhole.com/docs/protocol/infrastructure/vaas/) + +## Next steps + +Now that you understand Pyth oracle integration: + + + + + \ No newline at end of file diff --git a/content/docs/resources/snippets/build-a-stx-pc.mdx b/content/docs/resources/snippets/build-a-stx-pc.mdx new file mode 100644 index 000000000..901d62c43 --- /dev/null +++ b/content/docs/resources/snippets/build-a-stx-pc.mdx @@ -0,0 +1,48 @@ +--- +title: Build a STX post-condition +description: A helper function that creates a post-condition for STX token transfers using the Pc builder class, ensuring exact amounts are transferred as expected. +full: true +--- + +```typescript +import { + AnchorMode, + broadcastTransaction, + makeSTXTokenTransfer, + Pc, + PostConditionMode, +} from "@stacks/transactions"; + +// Create a post-condition that ensures exactly 10 STX is sent +const pc = Pc.principal("ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM") + .willSendEq(10000000) // 10 STX in micro-STX + .ustx(); + +const txOptions = { + recipient: "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5", + amount: 10000000, + senderKey: "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601", + network: "testnet", + postConditions: [pc], + postConditionMode: PostConditionMode.Deny, + anchorMode: AnchorMode.Any, +}; + +const transaction = await makeSTXTokenTransfer(txOptions); +const broadcastResponse = await broadcastTransaction(transaction); +console.log("Transaction ID:", broadcastResponse.txid); +``` + +## Use cases + +- Securing STX token transfers with transfer amount validation +- Protecting users from unexpected token transfers +- Ensuring contract interactions behave as expected + +## Key concepts + +The `Pc` builder provides a fluent interface for creating post-conditions: + +- `Pc.principal()` - Specify the principal that will send tokens +- `.willSendEq()` - Ensure exactly this amount is sent (also supports `willSendGte`, `willSendLte`, `willSendGt`, `willSendLt`) +- `.ustx()` - Specify the token type (micro-STX) \ No newline at end of file diff --git a/content/docs/resources/snippets/build-an-ft-pc.mdx b/content/docs/resources/snippets/build-an-ft-pc.mdx new file mode 100644 index 000000000..d864ec769 --- /dev/null +++ b/content/docs/resources/snippets/build-an-ft-pc.mdx @@ -0,0 +1,34 @@ +--- +title: Build an FT post-condition +description: Create post-conditions for fungible token transfers to ensure exact amounts are transferred as expected +--- + +```typescript +import { Pc } from '@stacks/transactions'; + +// Create a post-condition for fungible token transfers +const postCondition = Pc.principal("ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM") + .willSendGte(500) // Amount in token's smallest unit + .ft("ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE.token-ft", "my-token"); + +// Use in transaction options +const txOptions = { + // ... other transaction options + postConditions: [postCondition], + postConditionMode: PostConditionMode.Deny, +}; +``` + +## Use cases + +- Securing fungible token transfers with amount validation +- Protecting users from unexpected token transfers in DeFi protocols +- Ensuring token swaps happen with expected amounts + +## Key concepts + +The `Pc` builder for fungible tokens accepts: + +- `.ft()` - Takes two parameters: + - Contract address with asset name (e.g., `"contract.asset-name"`) + - Token name as defined in the contract \ No newline at end of file diff --git a/content/docs/resources/snippets/build-an-nft-pc.mdx b/content/docs/resources/snippets/build-an-nft-pc.mdx new file mode 100644 index 000000000..cb8a42fe0 --- /dev/null +++ b/content/docs/resources/snippets/build-an-nft-pc.mdx @@ -0,0 +1,31 @@ +--- +title: Build an NFT post-condition +description: Create post-conditions for NFT transfers to ensure specific tokens are or aren't transferred +--- + +```typescript +import { Pc, Cl } from '@stacks/transactions'; + +// Ensure a specific NFT will be sent +const sendPC = Pc.principal("ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM") + .willSendAsset() + .nft('ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE.cool-nfts::nft-token', Cl.uint(42)); + +// Ensure a specific NFT will NOT be sent +const keepPC = Pc.principal("ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM") + .willNotSendAsset() + .nft('ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE.cool-nfts::nft-token', Cl.uint(1)); +``` + +## Use cases + +- Protecting valuable NFTs from accidental transfers +- Ensuring specific NFTs are transferred in marketplace transactions +- Safeguarding NFT collections during contract interactions + +## Key concepts + +NFT post-conditions use the `.nft()` method which requires: + +- **Asset identifier**: Contract address + asset name with `::` separator +- **Token ID**: The specific NFT ID as a Clarity value (using `Cl.uint()`) \ No newline at end of file diff --git a/content/docs/resources/snippets/build-an-unsigned-tx.mdx b/content/docs/resources/snippets/build-an-unsigned-tx.mdx new file mode 100644 index 000000000..726d1571c --- /dev/null +++ b/content/docs/resources/snippets/build-an-unsigned-tx.mdx @@ -0,0 +1,51 @@ +--- +title: Build an unsigned transaction +description: Create unsigned transactions for hardware wallets or multi-signature scenarios +--- + +```typescript +import { getPublicKeyFromPrivate } from "@stacks/encryption"; +import { + makeUnsignedSTXTokenTransfer, + makeUnsignedContractCall, + Cl, + AnchorMode, + PostConditionMode +} from "@stacks/transactions"; +import { STACKS_TESTNET } from "@stacks/network"; + +// Get public key from private key +const privateKey = "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601"; +const publicKey = getPublicKeyFromPrivate(privateKey); + +// Build unsigned STX transfer +const unsignedTx = await makeUnsignedSTXTokenTransfer({ + recipient: "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5", + amount: 1000000n, // 1 STX in micro-STX + fee: 200n, + nonce: 0n, + network: STACKS_TESTNET, + memo: "Test transfer", + publicKey, + anchorMode: AnchorMode.Any, + postConditionMode: PostConditionMode.Deny, +}); + +// Transaction is ready for external signing +console.log("Unsigned transaction created:", unsignedTx.txid()); +``` + +## Use cases + +- Hardware wallet integration (Ledger, Trezor) +- Multi-signature wallet transactions +- Offline transaction signing +- Secure key management systems + +## Key concepts + +Unsigned transactions separate transaction creation from signing: + +- **Public key only**: No private key needed for creation +- **External signing**: Sign with hardware wallet or secure enclave +- **Serialization**: Can be transported and signed elsewhere \ No newline at end of file diff --git a/content/docs/resources/snippets/check-for-duplicates.mdx b/content/docs/resources/snippets/check-for-duplicates.mdx new file mode 100644 index 000000000..9f6676760 --- /dev/null +++ b/content/docs/resources/snippets/check-for-duplicates.mdx @@ -0,0 +1,40 @@ +--- +title: Check for duplicates +description: Detect duplicate characters in strings and duplicate items in lists using Clarity +--- + +```clarity +;; Check for duplicate characters in a string +(define-read-only (has-duplicate-chars? (input (string-ascii 200))) + (is-none (fold dup input (slice? (concat input "|END") u1 (+ (len input) u4)))) +) + +(define-private (dup (ch (string-ascii 1)) (out (optional (string-ascii 204)))) + (match out out_some + (match (index-of? (unwrap-panic (slice? out_some u0 (- (len out_some) u4))) ch) + found none + (slice? out_some u1 (len out_some)) + ) + out + ) +) + +;; Example usage +(has-duplicate-chars? "hello") ;; Returns true (duplicate 'l') +(has-duplicate-chars? "world") ;; Returns false (no duplicates) +``` + +## Use cases + +- Validating usernames for uniqueness of characters +- Checking NFT trait uniqueness in collections +- Preventing duplicate entries in voting systems +- Ensuring unique identifiers in lists + +## Key concepts + +The duplicate detection uses different strategies: + +- **Strings**: Uses `fold` with `index-of?` to find repeated characters +- **Lists**: Checks if elements appear again in the remaining list +- **Optimization**: Early exit on first duplicate found \ No newline at end of file diff --git a/content/docs/resources/snippets/convert-btc-to-stx-address.mdx b/content/docs/resources/snippets/convert-btc-to-stx-address.mdx new file mode 100644 index 000000000..0c9082014 --- /dev/null +++ b/content/docs/resources/snippets/convert-btc-to-stx-address.mdx @@ -0,0 +1,47 @@ +--- +title: Convert BTC to STX address +description: Convert Bitcoin addresses to their corresponding Stacks addresses using base58 decoding in Clarity +--- + +```clarity +(define-read-only (btc-to-stx (input (string-ascii 60))) + (let ( + ;; Decode base58 string to numbers + (b58-numbers (map unwrap-uint (filter is-some-uint (map b58-to-uint input)))) + ;; Validate all characters are valid base58 + (t1 (asserts! (>= (len b58-numbers) (len input)) ERR_INVALID_CHAR)) + ;; Count leading '1's (zeros in base58) + (leading-ones-count (default-to (len input) (index-of? (map is-zero b58-numbers) false))) + ;; Convert to bytes + (decoded (concat (fold decode-outer to-decode LST) leading-zeros)) + (decoded-hex (fold to-hex-rev decoded 0x)) + ;; Verify checksum + (actual-checksum (unwrap-panic (slice? (sha256 (sha256 (unwrap-panic (slice? decoded-hex u0 (- decoded-hex-len u4))))) u0 u4))) + (expected-checksum (unwrap-panic (slice? decoded-hex (- decoded-hex-len u4) decoded-hex-len))) + (t3 (asserts! (is-eq actual-checksum expected-checksum) ERR_BAD_CHECKSUM)) + ;; Extract version and construct principal + (version (unwrap-panic (element-at? STX_VER (unwrap! (index-of? BTC_VER (unwrap-panic (element-at? decoded-hex u0))) ERR_INVALID_VERSION)))) + ) + (principal-construct? version (unwrap-panic (as-max-len? (unwrap-panic (slice? decoded-hex u1 (- decoded-hex-len u4))) u20))) + ) +) + +;; Example usage +(btc-to-stx "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa") ;; Returns Stacks address +``` + +## Use cases + +- Cross-chain address mapping for Bitcoin-Stacks bridges +- Verifying ownership across both chains +- Converting legacy Bitcoin addresses to Stacks format +- Building cross-chain authentication systems + +## Key concepts + +The conversion process involves: + +1. **Base58 decoding**: Bitcoin addresses use base58 encoding +2. **Checksum verification**: Last 4 bytes are a double SHA-256 checksum +3. **Version mapping**: Bitcoin version bytes map to Stacks version bytes +4. **Principal construction**: Build Stacks principal from decoded data \ No newline at end of file diff --git a/content/docs/resources/snippets/convert-string-to-principal.mdx b/content/docs/resources/snippets/convert-string-to-principal.mdx new file mode 100644 index 000000000..f10fa90a5 --- /dev/null +++ b/content/docs/resources/snippets/convert-string-to-principal.mdx @@ -0,0 +1,53 @@ +--- +title: Convert string to principal +description: Parse string addresses into principal types using c32 decoding in Clarity +--- + +```clarity +(define-read-only (string-to-principal? (input (string-ascii 82))) + (let ( + ;; Find the dot separator for contract addresses + (dot (default-to (len input) (index-of? input "."))) + ;; Extract address part (skip first char which is version) + (addr (unwrap! (slice? input u1 dot) ERR_INVALID_LENGTH)) + ;; Decode c32 characters to numbers + (addressc32 (map unwrap-panic-uint (filter is-some-uint (map c32-index addr)))) + ;; Validate all characters are valid c32 + (isValidChars (asserts! (is-eq (len addr) (len addressc32)) ERR_INVALID_CHAR)) + ;; Extract version and decode address data + (version (unwrap-panic (element-at? addressc32 u0))) + (decoded (decode-address addressc32)) + ;; Verify checksum + (checksum (verify-checksum decoded version)) + ) + ;; Construct principal with or without contract name + (match (slice? input (+ u1 dot) (len input)) contract + (principal-construct? (to-byte version) (get-address-bytes decoded) contract) + (principal-construct? (to-byte version) (get-address-bytes decoded)) + ) + ) +) + +;; Example usage +(string-to-principal? "SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7") +;; Returns (some SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7) + +(string-to-principal? "SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7.my-contract") +;; Returns (some SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7.my-contract) +``` + +## Use cases + +- Parsing user input addresses in contracts +- Converting stored string addresses to principals +- Validating address formats before use +- Building dynamic contract calls with string inputs + +## Key concepts + +Stacks addresses use c32 encoding: + +- **c32 alphabet**: `0123456789ABCDEFGHJKMNPQRSTVWXYZ` (no I, L, O, U) +- **Checksum**: Last 4 bytes verify address integrity +- **Version byte**: First character indicates address type +- **Contract addresses**: Include `.contract-name` suffix \ No newline at end of file diff --git a/content/docs/resources/snippets/create-a-random-burn-address.mdx b/content/docs/resources/snippets/create-a-random-burn-address.mdx new file mode 100644 index 000000000..41a330a82 --- /dev/null +++ b/content/docs/resources/snippets/create-a-random-burn-address.mdx @@ -0,0 +1,38 @@ +--- +title: Create a random burn address +description: Generate burn addresses for permanently removing tokens from circulation +--- + +```clarity +(define-read-only (generate-burn-address (entropy (string-ascii 40))) + (let ( + ;; Hash the entropy to create address bytes + (hash-bytes (hash160 (unwrap-panic (to-consensus-buff? entropy)))) + ;; Use version byte for current network + (version-byte (if is-in-mainnet 0x16 0x1a)) + ) + ;; Construct a valid principal that no one controls + (principal-construct? version-byte hash-bytes) + ) +) + +;; Example: Generate unique burn address +(generate-burn-address "BURN-2024-01-15-PROJECT-XYZ") +;; Returns: (ok SP1FJPSG7V4QMA7D4XVPZ3B2HQ8GY3EK8GC0NGNT3) +``` + +## Use cases + +- Token burning mechanisms +- Proof-of-burn implementations +- Creating unspendable addresses for protocol fees +- Deflationary token economics + +## Key concepts + +Burn addresses are valid principals that: + +- **No private key**: Generated from arbitrary data, not a key pair +- **Verifiable**: Anyone can verify tokens sent to these addresses +- **Unique**: Different entropy creates different addresses +- **Permanent**: Funds sent are irretrievably lost \ No newline at end of file diff --git a/content/docs/resources/snippets/create-a-sponsored-tx.mdx b/content/docs/resources/snippets/create-a-sponsored-tx.mdx new file mode 100644 index 000000000..707c097c1 --- /dev/null +++ b/content/docs/resources/snippets/create-a-sponsored-tx.mdx @@ -0,0 +1,69 @@ +--- +title: Create a sponsored transaction +description: Build transactions where a sponsor pays the fees on behalf of users +--- + +```typescript +import { STACKS_TESTNET } from "@stacks/network"; +import { bytesToHex } from "@stacks/common"; +import { + broadcastTransaction, + deserializeTransaction, + makeContractCall, + sponsorTransaction, + BufferReader, + AnchorMode, + Cl, +} from "@stacks/transactions"; + +// Step 1: User creates the transaction with sponsored flag +const userTxOptions = { + contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", + contractName: "my-contract", + functionName: "my-function", + functionArgs: [Cl.uint(123)], + fee: 0, // User doesn't pay fees + senderKey: "b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01", + network: STACKS_TESTNET, + sponsored: true, // Mark as sponsored + anchorMode: AnchorMode.Any, +}; + +const transaction = await makeContractCall(userTxOptions); +const serializedTx = bytesToHex(transaction.serialize()); + +// Step 2: Send serialized transaction to sponsor +// (In practice, this would be sent to a sponsorship service) + +// Step 3: Sponsor signs and pays fees +const sponsorKey = "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601"; +const deserializedTx = deserializeTransaction(serializedTx); +const sponsoredTx = await sponsorTransaction({ + transaction: deserializedTx, + sponsorPrivateKey: sponsorKey, + fee: 1000, // Sponsor pays the fee + sponsorNonce: 0, +}); + +// Step 4: Broadcast the sponsored transaction +const broadcastResponse = await broadcastTransaction({ + transaction: sponsoredTx, + network: STACKS_TESTNET, +}); + +console.log("Sponsored transaction ID:", broadcastResponse.txid); +``` + +## Use cases + +- Onboarding new users without STX for fees +- Subsidizing transaction costs for dApp users +- Enterprise applications paying for user transactions +- Gaming applications with seamless user experience + +## Key concepts + +Sponsored transactions have two parties: + +- **User**: Creates and signs the transaction with `sponsored: true` +- **Sponsor**: Pays the fees and broadcasts the transaction \ No newline at end of file diff --git a/content/docs/resources/snippets/create-sha256-hash-clarity.mdx b/content/docs/resources/snippets/create-sha256-hash-clarity.mdx new file mode 100644 index 000000000..486b85c53 --- /dev/null +++ b/content/docs/resources/snippets/create-sha256-hash-clarity.mdx @@ -0,0 +1,34 @@ +--- +title: Create SHA256 hash in Clarity +description: Generate SHA-256 hashes from buffer data in Clarity smart contracts +--- + +```clarity +(define-read-only (create-sha256-hash (data (buff 4096))) + (sha256 (unwrap-panic (to-consensus-buff? data))) +) + +;; Example usage +(define-read-only (hash-message (message (string-utf8 200))) + (create-sha256-hash (unwrap-panic (to-consensus-buff? message))) +) + +;; Hash a simple string +(print (hash-message u"Hello World")) +``` + +## Use cases + +- Creating unique identifiers from data +- Verifying data integrity in contracts +- Implementing commit-reveal schemes +- Building merkle trees for proofs + +## Key concepts + +The SHA-256 implementation in Clarity: + +- Takes a buffer as input (max 1MB) +- Returns a 32-byte buffer hash +- Uses `to-consensus-buff?` to ensure consistent encoding +- Produces the same hash as off-chain implementations \ No newline at end of file diff --git a/content/docs/resources/snippets/create-sha256-hash-stacks-js.mdx b/content/docs/resources/snippets/create-sha256-hash-stacks-js.mdx new file mode 100644 index 000000000..8a8fccd0a --- /dev/null +++ b/content/docs/resources/snippets/create-sha256-hash-stacks-js.mdx @@ -0,0 +1,46 @@ +--- +title: Create SHA256 hash in Stacks.js +description: Generate SHA-256 hashes that match Clarity's hashing output +--- + +```typescript +import { sha256 } from "@noble/hashes/sha256"; +import { bytesToHex, hexToBytes, utf8ToBytes } from "@stacks/common"; +import { bufferCV, stringUtf8CV, serializeCV } from "@stacks/transactions"; + +// Hash a string (matching Clarity's sha256 output) +function hashString(text: string) { + const clarityValue = stringUtf8CV(text); + const serialized = serializeCV(clarityValue); + return bytesToHex(sha256(serialized)); +} + +// Hash hex data (matching Clarity's sha256 output) +function hashHexData(hexData: string) { + const clarityValue = bufferCV(hexToBytes(hexData)); + const serialized = serializeCV(clarityValue); + return bytesToHex(sha256(serialized)); +} + +// Example usage +const hash1 = hashString("Hello World"); +console.log("String hash:", hash1); + +const hash2 = hashHexData("0x1234567890abcdef"); +console.log("Hex hash:", hash2); +``` + +## Use cases + +- Creating deterministic identifiers +- Verifying data integrity between on-chain and off-chain +- Implementing commit-reveal schemes off-chain +- Building merkle trees compatible with Clarity + +## Key concepts + +To match Clarity's SHA-256 output: + +1. **Convert to Clarity value**: Use appropriate CV type (`stringUtf8CV`, `bufferCV`, etc.) +2. **Serialize**: Use `serializeCV` to match Clarity's encoding +3. **Hash**: Apply SHA-256 to the serialized bytes \ No newline at end of file diff --git a/content/docs/resources/snippets/deploy-a-contract.mdx b/content/docs/resources/snippets/deploy-a-contract.mdx new file mode 100644 index 000000000..46d29137a --- /dev/null +++ b/content/docs/resources/snippets/deploy-a-contract.mdx @@ -0,0 +1,55 @@ +--- +title: Deploy a contract +description: Deploy a Clarity smart contract to the Stacks blockchain using Stacks.js +--- + +```typescript +import { STACKS_TESTNET } from "@stacks/network"; +import { + makeContractDeploy, + broadcastTransaction, + AnchorMode, + PostConditionMode +} from "@stacks/transactions"; + +const contractCode = ` +(define-data-var counter uint u0) + +(define-public (increment) + (ok (var-set counter (+ (var-get counter) u1)))) + +(define-read-only (get-counter) + (ok (var-get counter))) +`; + +const txOptions = { + contractName: "my-counter", + codeBody: contractCode, + senderKey: "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601", + network: STACKS_TESTNET, + anchorMode: AnchorMode.Any, + postConditionMode: PostConditionMode.Allow, + fee: 100000n, // Set an appropriate fee +}; + +const transaction = await makeContractDeploy(txOptions); +const broadcastResponse = await broadcastTransaction({ transaction }); +console.log("Contract deployed!"); +console.log("Transaction ID:", broadcastResponse.txid); +``` + +## Use cases + +- Deploying new smart contracts to mainnet or testnet +- Automating contract deployments in CI/CD pipelines +- Programmatic contract deployment for dApp initialization +- Deploying contract upgrades or new versions + +## Key concepts + +Contract deployment requires: + +- **Contract name**: Unique identifier for your contract (letters, numbers, hyphens) +- **Code body**: The Clarity contract code as a string +- **Sender key**: Private key of the account deploying the contract +- **Network**: Target network (mainnet, testnet, or devnet) \ No newline at end of file diff --git a/content/docs/resources/snippets/derive-principal-addresses-between-networks.mdx b/content/docs/resources/snippets/derive-principal-addresses-between-networks.mdx new file mode 100644 index 000000000..40f082e91 --- /dev/null +++ b/content/docs/resources/snippets/derive-principal-addresses-between-networks.mdx @@ -0,0 +1,65 @@ +--- +title: Derive principal addresses between networks +description: Convert addresses between mainnet and testnet by extracting and reconstructing with different version bytes +--- + +```clarity +;; Extract hash bytes from an address +(define-read-only (get-address-hash-bytes (address principal)) + (get hash-bytes (unwrap-panic (principal-destruct? address))) +) + +;; Convert testnet address to mainnet +(define-read-only (testnet-to-mainnet (testnet-address principal)) + (let ( + ;; Extract the hash bytes from testnet address + (hash-bytes (get-address-hash-bytes testnet-address)) + ;; Mainnet version byte + (mainnet-version 0x16) + ) + ;; Reconstruct with mainnet version + (principal-construct? mainnet-version hash-bytes) + ) +) + +;; Convert mainnet address to testnet +(define-read-only (mainnet-to-testnet (mainnet-address principal)) + (let ( + ;; Extract the hash bytes from mainnet address + (hash-bytes (get-address-hash-bytes mainnet-address)) + ;; Testnet version byte + (testnet-version 0x1a) + ) + ;; Reconstruct with testnet version + (principal-construct? testnet-version hash-bytes) + ) +) + +;; Example usage +(testnet-to-mainnet 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM) +;; Returns: (ok SP1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRCBGD7R) +``` + +## Use cases + +- Cross-network address verification +- Building multi-network dApps +- Address validation tools +- Network migration utilities + +## Key concepts + +Stacks addresses consist of: + +- **Version byte**: Indicates network and address type +- **Hash bytes**: 20-byte hash of the public key +- **Checksum**: Built into the c32 encoding + +### Version bytes reference + +| Version | Network | Type | Prefix | +|---------|---------|------|--------| +| 0x16 | Mainnet | Standard | SP | +| 0x17 | Mainnet | Contract | SM | +| 0x1a | Testnet | Standard | ST | +| 0x1b | Testnet | Contract | SN | \ No newline at end of file diff --git a/content/docs/resources/snippets/derive-stacks-address-from-keys.mdx b/content/docs/resources/snippets/derive-stacks-address-from-keys.mdx new file mode 100644 index 000000000..1e0d76b91 --- /dev/null +++ b/content/docs/resources/snippets/derive-stacks-address-from-keys.mdx @@ -0,0 +1,40 @@ +--- +title: Derive Stacks address from keys +description: Generate Stacks addresses from private or public keys using multiple methods +--- + +```typescript +import { getPublicKeyFromPrivate } from "@stacks/encryption"; +import { + getAddressFromPrivateKey, + getAddressFromPublicKey +} from "@stacks/transactions"; + +// Derive address from private key +const privateKey = process.env.PRIVATE_KEY; // Keep this secret! +const addressFromPrivate = getAddressFromPrivateKey(privateKey, "testnet"); + +// Derive public key and address +const publicKey = getPublicKeyFromPrivate(privateKey); +const addressFromPublic = getAddressFromPublicKey(publicKey, "testnet"); + +console.log("Address:", addressFromPrivate); +console.log("Public key:", publicKey); +console.log("Same address:", addressFromPrivate === addressFromPublic); // true +``` + +## Use cases + +- Wallet address generation +- Key pair validation +- Address recovery from backup keys +- Multi-signature wallet setup + +## Key concepts + +Stacks addresses are derived through: + +- **Private key**: 32-byte random number (keep secret!) +- **Public key**: Derived from private key using ECDSA +- **Address**: Base58check-encoded hash of public key +- **Network**: Different prefixes for mainnet (SP/SM) vs testnet (ST/SN) \ No newline at end of file diff --git a/content/docs/resources/snippets/fetch-testnet-bitcoin-on-regtest.mdx b/content/docs/resources/snippets/fetch-testnet-bitcoin-on-regtest.mdx new file mode 100644 index 000000000..d1f587924 --- /dev/null +++ b/content/docs/resources/snippets/fetch-testnet-bitcoin-on-regtest.mdx @@ -0,0 +1,46 @@ +--- +title: Fetch testnet Bitcoin on regtest +description: Request testnet BTC from the Hiro faucet for local development and testing +--- + +```typescript +const TESTNET_ADDRESS = 'bcrt1q728h29ejjttmkupwdkyu2x4zcmkuc3q29gvwaa'; + +try { + const response = await fetch( + `https://api.testnet.hiro.so/extended/v1/faucets/btc?address=${TESTNET_ADDRESS}`, + { + method: 'POST', + headers: { + "Content-Type": "application/json", + }, + } + ); + + const result = await response.json(); + console.log("Faucet response:", result); + + if (result.success) { + console.log(`Transaction ID: ${result.txid}`); + console.log(`Amount sent: ${result.amount} sats`); + } +} catch (error) { + console.error("Faucet request failed:", error); +} +``` + +## Use cases + +- Local development with Bitcoin transactions +- Testing sBTC operations +- Integration testing for cross-chain applications +- Developing Bitcoin-aware smart contracts + +## Key concepts + +The Hiro testnet faucet: + +- **Rate limited**: One request per address per hour +- **Amount**: Sends 0.5 testnet BTC per request +- **Network**: Works with Bitcoin testnet/regtest addresses +- **Format**: Supports legacy, segwit, and taproot addresses \ No newline at end of file diff --git a/content/docs/resources/snippets/filter-items-from-a-list.mdx b/content/docs/resources/snippets/filter-items-from-a-list.mdx new file mode 100644 index 000000000..9821760a7 --- /dev/null +++ b/content/docs/resources/snippets/filter-items-from-a-list.mdx @@ -0,0 +1,37 @@ +--- +title: Filter items from a list +description: Remove specific items from lists using fold in Clarity +--- + +```clarity +(define-read-only (filter-item (l (list 100 uint)) (remove uint)) + (get newList (fold remove-value l { compareTo: remove, newList: (list) })) +) + +(define-private (remove-value (listValue uint) (trackerTuple { compareTo: uint, newList: (list 100 uint) })) + (merge trackerTuple {newList: + (if (is-eq listValue (get compareTo trackerTuple)) + (get newList trackerTuple) + (unwrap-panic (as-max-len? (append (get newList trackerTuple) listValue) u100)) + ) + }) +) + +;; Example usage +(filter-item (list u1 u2 u3 u2 u4) u2) ;; Returns (u1 u3 u4) +``` + +## Use cases + +- Removing blacklisted addresses from access lists +- Filtering out completed tasks from todo lists +- Excluding specific tokens from portfolios +- Data cleanup in smart contracts + +## Key concepts + +This pattern uses `fold` to iterate through a list and build a new list: + +- **Accumulator**: Tracks the value to remove and builds the new list +- **Conditional append**: Only adds items that don't match the filter +- **Type safety**: Maintains list type and maximum length \ No newline at end of file diff --git a/content/docs/resources/snippets/generate-a-secret-key.mdx b/content/docs/resources/snippets/generate-a-secret-key.mdx new file mode 100644 index 000000000..46c5697ad --- /dev/null +++ b/content/docs/resources/snippets/generate-a-secret-key.mdx @@ -0,0 +1,32 @@ +--- +title: Generate a secret key +description: Create mnemonic seed phrases for wallet generation +--- + +```typescript +import { generateSecretKey } from '@stacks/wallet-sdk'; + +// Generate a 24-word mnemonic (256 bits of entropy) +const mnemonic24 = generateSecretKey(); +// Example: "aunt birth lounge misery utility blind holiday walnut fuel make gift parent gap picnic exact various express sphere family nerve oil drill engage youth" + +// Generate a 12-word mnemonic (128 bits of entropy) +const mnemonic12 = generateSecretKey(128); +// Example: "winter crash infant long upset beauty cram tank short remain obtain sauce" +``` + +## Use cases + +- Creating new wallet seed phrases +- Generating secure entropy for applications +- Building wallet creation flows +- Testing wallet functionality + +## Key concepts + +Mnemonic seed phrases follow the BIP39 standard: + +- **Entropy**: Random data used to generate the phrase +- **Word count**: 12 words (128 bits) or 24 words (256 bits) +- **Word list**: Standardized list of 2048 words +- **Checksum**: Built-in error detection \ No newline at end of file diff --git a/content/docs/resources/snippets/generate-a-wallet.mdx b/content/docs/resources/snippets/generate-a-wallet.mdx new file mode 100644 index 000000000..f203caeca --- /dev/null +++ b/content/docs/resources/snippets/generate-a-wallet.mdx @@ -0,0 +1,35 @@ +--- +title: Generate a wallet +description: Create a new wallet with mnemonic phrase or restore from existing seed +--- + +```typescript +import { generateWallet, generateSecretKey } from '@stacks/wallet-sdk'; + +// Generate a new wallet with a new 24-word seed phrase +const secretKey = generateSecretKey(256); // 256 bits = 24 words +const wallet = await generateWallet({ + secretKey, + password: 'your-secure-password', +}); + +// Access the first account +const account = wallet.accounts[0]; +console.log('Address:', account.stxAddress); +console.log('Mnemonic:', secretKey); +``` + +## Use cases + +- Creating new wallets for users +- Restoring wallets from seed phrases +- Generating deterministic wallet addresses +- Building wallet applications + +## Key concepts + +The wallet SDK generates hierarchical deterministic (HD) wallets following BIP32/BIP39 standards: + +- **Secret key**: Can be a mnemonic phrase or private key +- **Password**: Encrypts the wallet (different from mnemonic passphrase) +- **Accounts**: Multiple accounts can be derived from one seed \ No newline at end of file diff --git a/content/docs/resources/snippets/generate-random-number.mdx b/content/docs/resources/snippets/generate-random-number.mdx new file mode 100644 index 000000000..46333a203 --- /dev/null +++ b/content/docs/resources/snippets/generate-random-number.mdx @@ -0,0 +1,47 @@ +--- +title: Generate random number +description: Create pseudo-random numbers using block hashes for randomness in smart contracts +--- + +```clarity +(define-read-only (generate-random (block-height uint)) + (let ( + ;; Get block header hash + (block-hash (unwrap! (get-stacks-block-info? id-header-hash block-height) (err u1001))) + ;; Take a slice of the hash for randomness + (hash-slice (unwrap-panic (slice? block-hash u16 u32))) + ;; Convert to uint + (random-value (buff-to-uint-be (unwrap-panic (as-max-len? hash-slice u16)))) + ) + (ok random-value) + ) +) + +;; Generate random number in range +(define-read-only (random-in-range (block-height uint) (min uint) (max uint)) + (let ( + (random (try! (generate-random block-height))) + (range (- max min)) + ) + (ok (+ min (mod random (+ u1 range)))) + ) +) + +;; Example: Random between 1-100 +(random-in-range block-height u1 u100) +``` + +## Use cases + +- Lottery and gaming contracts +- Random NFT trait generation +- Fair distribution mechanisms +- Random selection from lists + +## Key concepts + +Blockchain randomness is deterministic but unpredictable: + +- **Block hashes**: Use historical block data as entropy source +- **Future blocks**: Cannot predict future block hashes +- **Commitment schemes**: Combine with commit-reveal for fairness \ No newline at end of file diff --git a/content/docs/resources/snippets/get-account-details-from-wallet.mdx b/content/docs/resources/snippets/get-account-details-from-wallet.mdx new file mode 100644 index 000000000..cea0214e7 --- /dev/null +++ b/content/docs/resources/snippets/get-account-details-from-wallet.mdx @@ -0,0 +1,53 @@ +--- +title: Get account details from wallet +description: Extract addresses, keys, and other account information from a wallet instance +--- + +```typescript +import { STACKS_TESTNET, STACKS_MAINNET } from "@stacks/network"; +import { generateWallet, getStxAddress } from "@stacks/wallet-sdk"; + +// Generate or restore wallet +const wallet = await generateWallet({ + secretKey: "your twenty four word mnemonic phrase goes here...", + password: "wallet-password", +}); + +// Get first account +const account = wallet.accounts[0]; + +// Get addresses for different networks +const testnetAddress = getStxAddress({ + account, + transactionVersion: 0 // testnet +}); + +const mainnetAddress = getStxAddress({ + account, + transactionVersion: 1 // mainnet +}); + +// Get keys +const privateKey = account.stxPrivateKey; +const publicKey = account.stxPublicKey; + +console.log("Testnet address:", testnetAddress); +console.log("Mainnet address:", mainnetAddress); +console.log("Public key:", publicKey); +``` + +## Use cases + +- Displaying user addresses in wallet UIs +- Getting private keys for transaction signing +- Deriving addresses for different networks +- Building wallet management tools + +## Key concepts + +Wallet accounts contain: + +- **Private key**: Used for signing transactions +- **Public key**: Derived from private key +- **Addresses**: Network-specific (mainnet vs testnet) +- **Derivation path**: BIP44 path used to generate the account \ No newline at end of file diff --git a/content/docs/resources/snippets/helper-function-to-restrict-contract-calls.mdx b/content/docs/resources/snippets/helper-function-to-restrict-contract-calls.mdx new file mode 100644 index 000000000..c70bd1422 --- /dev/null +++ b/content/docs/resources/snippets/helper-function-to-restrict-contract-calls.mdx @@ -0,0 +1,36 @@ +--- +title: Helper function to restrict contract calls +description: Implement access control to ensure functions can only be called by users, not other contracts +--- + +```clarity +;; Check if caller is a standard principal (user wallet) +(define-private (is-standard-principal-call) + (is-none (get name (unwrap! (principal-destruct? contract-caller) false))) +) + +;; Public function restricted to direct user calls +(define-public (user-only-function (amount uint)) + (begin + (asserts! (is-standard-principal-call) (err u401)) + ;; Function logic here + (ok true) + ) +) +``` + +## Use cases + +- Preventing contract-to-contract reentrancy attacks +- Ensuring human-initiated transactions for governance +- Restricting token minting to direct user actions +- Protecting admin functions from automated calls + +## Key concepts + +Principal types in Clarity: + +- **Standard principals**: User wallets (SP/ST addresses) +- **Contract principals**: Deployed contracts (address.contract-name) +- **contract-caller**: The immediate caller of the current function +- **tx-sender**: The original transaction initiator \ No newline at end of file diff --git a/content/docs/resources/snippets/index.mdx b/content/docs/resources/snippets/index.mdx new file mode 100644 index 000000000..a0e8900bf --- /dev/null +++ b/content/docs/resources/snippets/index.mdx @@ -0,0 +1,76 @@ +--- +title: Snippets +sidebarTitle: Overview +description: Ready-to-use code examples for building on Stacks and Bitcoin +llm: false +--- + +## Overview + +To explore Snippets with AI, copy and paste [llms.txt](/resources/snippets/llms.txt) into your LLM of choice. + +## Transactions + +### Token Transfers + +- [Transfer STX](/resources/snippets/transfer-stx) - Send STX tokens between addresses +- [Transfer a SIP-10 token](/resources/snippets/transfer-a-sip10-token) - Transfer fungible tokens + +### Transaction Building + +- [Build an unsigned transaction](/resources/snippets/build-an-unsigned-tx) - Create transactions for hardware wallets +- [Create a sponsored transaction](/resources/snippets/create-a-sponsored-tx) - Pay fees on behalf of users + +### Post-Conditions + +- [Build a STX post-condition](/resources/snippets/build-a-stx-pc) - Secure STX transfers +- [Build an FT post-condition](/resources/snippets/build-an-ft-pc) - Secure fungible token transfers +- [Build an NFT post-condition](/resources/snippets/build-an-nft-pc) - Secure NFT transfers + +## Smart Contracts + +### Contract Deployment + +- [Deploy a contract](/resources/snippets/deploy-a-contract) - Deploy contracts to the blockchain + +### Clarity Functions + +- [Create SHA256 hash](/resources/snippets/create-sha256-hash-clarity) - Generate hashes in Clarity +- [Filter items from a list](/resources/snippets/filter-items-from-a-list) - List manipulation in Clarity +- [Generate random number](/resources/snippets/generate-random-number) - Pseudo-random numbers in contracts +- [Check for duplicates](/resources/snippets/check-for-duplicates) - Find duplicate items in lists +- [Return an entry from a map](/resources/snippets/return-an-entry-from-a-map) - Access map data structures +- [Helper function to restrict contract calls](/resources/snippets/helper-function-to-restrict-contract-calls) - Access control patterns + +## Accounts & Addresses + +### Wallet Management + +- [Generate a wallet](/resources/snippets/generate-a-wallet) - Create new wallet with mnemonic +- [Generate a secret key](/resources/snippets/generate-a-secret-key) - Create private keys +- [Get account details from wallet](/resources/snippets/get-account-details-from-wallet) - Extract account information + +### Address Utilities + +- [Convert BTC to STX address](/resources/snippets/convert-btc-to-stx-address) - Cross-chain address conversion +- [Convert string to principal](/resources/snippets/convert-string-to-principal) - Parse principal addresses +- [Derive Stacks address from keys](/resources/snippets/derive-stacks-address-from-keys) - Generate addresses from key pairs +- [Derive principal addresses between networks](/resources/snippets/derive-principal-addresses-between-networks) - Network address mapping +- [Create a random burn address](/resources/snippets/create-a-random-burn-address) - Generate burn addresses + +## Cryptography & Security + +### Hashing + +- [Create SHA256 hash (Stacks.js)](/resources/snippets/create-sha256-hash-stacks-js) - Generate hashes in JavaScript +- [Create SHA256 hash (Clarity)](/resources/snippets/create-sha256-hash-clarity) - Generate hashes in smart contracts + +### API Integration + +- [Integrate API keys using Stacks.js](/resources/snippets/integrate-api-keys-using-stacksjs) - Secure API key usage + +## Development Tools + +### Testing + +- [Fetch testnet Bitcoin on regtest](/resources/snippets/fetch-testnet-bitcoin-on-regtest) - Get test BTC for development \ No newline at end of file diff --git a/content/docs/resources/snippets/integrate-api-keys-using-stacksjs.mdx b/content/docs/resources/snippets/integrate-api-keys-using-stacksjs.mdx new file mode 100644 index 000000000..2307698cd --- /dev/null +++ b/content/docs/resources/snippets/integrate-api-keys-using-stacksjs.mdx @@ -0,0 +1,38 @@ +--- +title: Integrate API keys using Stacks.js +description: Configure Stacks.js to use API keys for enhanced rate limits and monitoring +--- + +```typescript +import { createApiKeyMiddleware, createFetchFn } from "@stacks/common"; +import { StacksMainnet, StacksTestnet } from "@stacks/network"; + +// Create middleware with your API key +const apiMiddleware = createApiKeyMiddleware({ + apiKey: process.env.HIRO_API_KEY +}); + +// Create custom fetch function +const customFetch = createFetchFn(apiMiddleware); + +// Configure network with API key +const network = new StacksMainnet({ + fetchFn: customFetch +}); +``` + +## Use cases + +- Increased API rate limits for production applications +- API usage monitoring and analytics +- Priority access during high traffic periods +- Custom enterprise support features + +## Key concepts + +API key benefits: + +- **Higher rate limits**: 500 requests/minute vs 50 for anonymous +- **Usage tracking**: Monitor your API consumption +- **Priority queue**: Better performance during peak times +- **Support**: Access to dedicated support channels \ No newline at end of file diff --git a/content/docs/resources/snippets/meta.json b/content/docs/resources/snippets/meta.json new file mode 100644 index 000000000..d1753a8d1 --- /dev/null +++ b/content/docs/resources/snippets/meta.json @@ -0,0 +1,38 @@ +{ + "title": "Snippets", + "root": true, + "pages": [ + "---Snippets---", + "index", + "---Transactions---", + "transfer-stx", + "transfer-a-sip10-token", + "build-an-unsigned-tx", + "create-a-sponsored-tx", + "build-a-stx-pc", + "build-an-ft-pc", + "build-an-nft-pc", + "---Smart Contracts---", + "deploy-a-contract", + "create-sha256-hash-clarity", + "filter-items-from-a-list", + "generate-random-number", + "check-for-duplicates", + "return-an-entry-from-a-map", + "helper-function-to-restrict-contract-calls", + "---Accounts & Addresses---", + "generate-a-wallet", + "generate-a-secret-key", + "get-account-details-from-wallet", + "convert-btc-to-stx-address", + "convert-string-to-principal", + "derive-stacks-address-from-keys", + "derive-principal-addresses-between-networks", + "create-a-random-burn-address", + "---Cryptography & Security---", + "create-sha256-hash-stacks-js", + "integrate-api-keys-using-stacksjs", + "---Development Tools---", + "fetch-testnet-bitcoin-on-regtest" + ] +} \ No newline at end of file diff --git a/content/docs/resources/snippets/return-an-entry-from-a-map.mdx b/content/docs/resources/snippets/return-an-entry-from-a-map.mdx new file mode 100644 index 000000000..b0acc93ea --- /dev/null +++ b/content/docs/resources/snippets/return-an-entry-from-a-map.mdx @@ -0,0 +1,47 @@ +--- +title: Return an entry from a map +description: Query contract map data using the Stacks API map_entry endpoint +--- + +```typescript +import { Cl, cvToHex } from "@stacks/transactions"; + +// Query a map entry from a contract +const contractAddress = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM"; +const contractName = "my-contract"; +const mapName = "user-balances"; + +// Create the map key (e.g., a principal) +const mapKey = Cl.standardPrincipal("ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5"); + +const response = await fetch( + `https://api.hiro.so/v2/map_entry/${contractAddress}/${contractName}/${mapName}`, + { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(cvToHex(mapKey)), + } +); + +const result = await response.json(); +const data = result.data ? Cl.deserialize(result.data) : null; + +console.log("Map value:", data); +``` + +## Use cases + +- Reading user balances from token contracts +- Checking NFT ownership records +- Retrieving configuration values from contracts +- Monitoring contract state without transactions + +## Key concepts + +The map_entry API: + +- **POST request**: Send the serialized map key +- **Hex encoding**: Keys must be hex-encoded Clarity values +- **Response format**: Returns hex-encoded Clarity value or null \ No newline at end of file diff --git a/content/docs/resources/snippets/transfer-a-sip10-token.mdx b/content/docs/resources/snippets/transfer-a-sip10-token.mdx new file mode 100644 index 000000000..4ea8d885b --- /dev/null +++ b/content/docs/resources/snippets/transfer-a-sip10-token.mdx @@ -0,0 +1,69 @@ +--- +title: Transfer a SIP-10 token +description: Transfer fungible tokens using the SIP-10 standard with post-conditions +--- + +```typescript +import { STACKS_MAINNET } from "@stacks/network"; +import { + AnchorMode, + broadcastTransaction, + Cl, + makeContractCall, + Pc, + PostConditionMode, +} from "@stacks/transactions"; + +// Token contract details +const tokenAddress = "SP3K8BC0PPEVCV7NZ6QSRWPQ2JE9E5B6N3PA0KBR9"; +const tokenName = "wrapped-bitcoin"; +const contractIdentifier = `${tokenAddress}.${tokenName}`; + +// Create post-condition to ensure exact amount is transferred +const postConditions = [ + Pc.principal("SP2C20XGZBAYFZ1NYNHT1J6MGBGVX9X7X3P7LAX7K") + .willSendEq(100000000) // 1 wBTC (8 decimals) + .ft(contractIdentifier, tokenName) +]; + +const txOptions = { + contractAddress: tokenAddress, + contractName: tokenName, + functionName: "transfer", + functionArgs: [ + Cl.uint(100000000), // amount (with decimals) + Cl.principal("SP2C20XGZBAYFZ1NYNHT1J6MGBGVX9X7X3P7LAX7K"), // sender + Cl.principal("SP31DA84DWTF6510EW6DCTC3GB3XH1EEBGP7MYT2"), // recipient + Cl.none(), // optional memo + ], + senderKey: "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601", + validateWithAbi: true, + network: STACKS_MAINNET, + postConditions, + postConditionMode: PostConditionMode.Deny, + anchorMode: AnchorMode.Any, +}; + +const transaction = await makeContractCall(txOptions); +const broadcastResponse = await broadcastTransaction({ + transaction, + network: STACKS_MAINNET, +}); + +console.log("Transaction ID:", broadcastResponse.txid); +``` + +## Use cases + +- Transferring fungible tokens between wallets +- Integrating token transfers in dApps +- Building DEX or swap functionality +- Implementing payment systems with custom tokens + +## Key concepts + +SIP-10 is the fungible token standard on Stacks, similar to ERC-20: + +- **Standard interface**: All SIP-10 tokens implement `transfer`, `get-balance`, etc. +- **Post-conditions**: Protect users by ensuring exact amounts are transferred +- **Memos**: Optional field for including transfer notes \ No newline at end of file diff --git a/content/docs/resources/snippets/transfer-stx.mdx b/content/docs/resources/snippets/transfer-stx.mdx new file mode 100644 index 000000000..d44e9718a --- /dev/null +++ b/content/docs/resources/snippets/transfer-stx.mdx @@ -0,0 +1,50 @@ +--- +title: Transfer STX +description: Send STX tokens between addresses with post-conditions for secure transfers +--- + +```typescript +import { STACKS_TESTNET } from "@stacks/network"; +import { + AnchorMode, + broadcastTransaction, + makeSTXTokenTransfer, + Pc, + PostConditionMode, +} from "@stacks/transactions"; + +// Define sender and recipient +const senderAddress = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM"; +const recipientAddress = "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5"; + +// Create post-condition to ensure exact amount is sent +const postConditions = Pc.principal(senderAddress) + .willSendEq(1000000) // 1 STX in micro-STX + .ustx(); + +// Configure transaction options +const txOptions = { + recipient: recipientAddress, + amount: 1000000, // 1 STX in micro-STX + senderKey: "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601", + network: STACKS_TESTNET, + memo: "Transfer memo", // Optional memo field + postConditions: [postConditions], + postConditionMode: PostConditionMode.Deny, + anchorMode: AnchorMode.Any, +}; + +// Create and broadcast the transaction +const transaction = await makeSTXTokenTransfer(txOptions); +const broadcastResponse = await broadcastTransaction({ transaction }); +console.log("Transaction ID:", broadcastResponse.txid); +``` + +## Use cases + +- Transferring STX tokens securely between addresses +- Validating transaction amounts for secure transfers + +## Key concepts + +- **Post-conditions**: Ensure the exact amount of STX is transferred \ No newline at end of file diff --git a/content/docs/resources/templates/index.mdx b/content/docs/resources/templates/index.mdx new file mode 100644 index 000000000..c40a0d010 --- /dev/null +++ b/content/docs/resources/templates/index.mdx @@ -0,0 +1,8 @@ +--- +title: Project templates +description: Project templates for building on Stacks. +llm: false +--- + +## Project templates + diff --git a/content/docs/resources/templates/meta.json b/content/docs/resources/templates/meta.json new file mode 100644 index 000000000..c6aeac0c4 --- /dev/null +++ b/content/docs/resources/templates/meta.json @@ -0,0 +1,8 @@ +{ + "title": "Project templates", + "root": true, + "pages": [ + "index", + "..." + ] +} diff --git a/content/docs/stacks/api-keys.mdx b/content/docs/stacks/api-keys.mdx deleted file mode 100644 index 6799efe2c..000000000 --- a/content/docs/stacks/api-keys.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: API keys -description: For developers who need API requests beyond the standard rate limits. ---- - -import ApiKeysContent from '@/snippets/api-keys.mdx'; - - diff --git a/content/docs/stacks/api/accounts/assets.mdx b/content/docs/stacks/api/accounts/assets.mdx deleted file mode 100644 index 6abfbee24..000000000 --- a/content/docs/stacks/api/accounts/assets.mdx +++ /dev/null @@ -1,287 +0,0 @@ ---- -title: Get account assets -description: Retrieves a list of all asset events associated with an account or a contract identifier. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get account assets - -Retrieves a list of all assets events associated with an account or a Contract Identifier. This includes Transfers, Mints. - -### Query Parameters - - - -Results per page - -Default: `20` - -Minimum: `0` - -Maximum: `100` - - - - - -Result offset - -Default: `0` - -Minimum: `0` - - - - - -Include data from unanchored (i.e. unconfirmed) microblocks - -Default: `false` - - - - - -Block hash or block height. Return data representing the state up until that point in time, rather than the current block. Note - Use either of the query parameters but not both at a time. - - - -### Path Parameters - - - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Default Response | -| `4XX` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/extended/v1/address/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/assets?limit=20&offset=0&unanchored=false&until_block=string" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/address/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/assets?limit=20&offset=0&unanchored=false&until_block=string", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "event_index": 0, - "event_type": "smart_contract_log", - "tx_id": "string", - "contract_log": { - "contract_id": "string", - "topic": "string", - "value": { - "hex": "string", - "repr": "string" - } - } - } - ] -} -``` - - - - - -```ts -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent = AbstractTransactionEvent & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent = AbstractTransactionEvent1 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent = AbstractTransactionEvent2 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent = AbstractTransactionEvent3 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent = AbstractTransactionEvent4 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; - -export interface AddressAssetsListResponse { - limit: number; - offset: number; - total: number; - results: ( - | SmartContractLogTransactionEvent - | StxLockTransactionEvent - | StxAssetTransactionEvent - | FungibleTokenAssetTransactionEvent - | NonFungibleTokenAssetTransactionEvent - )[]; -} -export interface AbstractTransactionEvent { - event_index: number; -} -export interface AbstractTransactionEvent1 { - event_index: number; -} -export interface AbstractTransactionEvent2 { - event_index: number; -} -export interface AbstractTransactionEvent3 { - event_index: number; -} -export interface AbstractTransactionEvent4 { - event_index: number; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "string", - "message": "string" -} -``` - - - - - -```ts -export interface ErrorResponse { - error: string; - message?: string; - [k: string]: unknown; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/accounts/balances.mdx b/content/docs/stacks/api/accounts/balances.mdx deleted file mode 100644 index 978ed7eec..000000000 --- a/content/docs/stacks/api/accounts/balances.mdx +++ /dev/null @@ -1,292 +0,0 @@ ---- -title: Get user balances -description: Retrieves account balance information, including STX, fungible, and non-fungible tokens. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get account balances - -**NOTE:** This endpoint is deprecated in favor of [Get address FT balances](/stacks/api/accounts/principal-ft-balances). - - Retrieves total account balance information for a given Address or Contract Identifier. This includes the balances of STX Tokens, Fungible Tokens and Non-Fungible Tokens for the account. - -### Query Parameters - - - -Include data from unanchored (i.e. unconfirmed) microblocks - -Default: `false` - - - - - -Block hash or block height. Return data representing the state up until that point in time, rather than the current block. Note - Use either of the query parameters but not both at a time. - - - -### Path Parameters - - - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | GET request that returns address balances | -| `4XX` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/extended/v1/address/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/balances?unanchored=false&until_block=string" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/address/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/balances?unanchored=false&until_block=string", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns address balances - - - - - -```json -{ - "stx": { - "balance": "string", - "estimated_balance": "string", - "pending_balance_inbound": "string", - "pending_balance_outbound": "string", - "total_sent": "string", - "total_received": "string", - "total_fees_sent": "string", - "total_miner_rewards_received": "string", - "lock_tx_id": "string", - "locked": "string", - "lock_height": 0, - "burnchain_lock_height": 0, - "burnchain_unlock_height": 0 - }, - "fungible_tokens": { - "property1": { - "balance": "string", - "total_sent": "string", - "total_received": "string" - }, - "property2": { - "balance": "string", - "total_sent": "string", - "total_received": "string" - } - }, - "non_fungible_tokens": { - "property1": { - "count": "string", - "total_sent": "string", - "total_received": "string" - }, - "property2": { - "count": "string", - "total_sent": "string", - "total_received": "string" - } - }, - "token_offering_locked": { - "total_locked": "string", - "total_unlocked": "string", - "unlock_schedule": [ - { - "amount": "string", - "block_height": 0 - } - ] - } -} -``` - - - - - -```ts -/** - * GET request that returns address balances - */ -export interface AddressBalanceResponse { - stx: StxBalance; - fungible_tokens: { - [k: string]: FtBalance; - }; - non_fungible_tokens: { - [k: string]: NftBalance; - }; - token_offering_locked?: AddressTokenOfferingLocked; -} -export interface StxBalance { - balance: string; - /** - * Total STX balance considering pending mempool transactions - */ - estimated_balance?: string; - /** - * Inbound STX balance from pending mempool transactions - */ - pending_balance_inbound?: string; - /** - * Outbound STX balance from pending mempool transactions - */ - pending_balance_outbound?: string; - total_sent?: string; - total_received?: string; - total_fees_sent?: string; - total_miner_rewards_received: string; - /** - * The transaction where the lock event occurred. Empty if no tokens are locked. - */ - lock_tx_id: string; - /** - * The amount of locked STX, as string quoted micro-STX. Zero if no tokens are locked. - */ - locked: string; - /** - * The STX chain block height of when the lock event occurred. Zero if no tokens are locked. - */ - lock_height: number; - /** - * The burnchain block height of when the lock event occurred. Zero if no tokens are locked. - */ - burnchain_lock_height: number; - /** - * The burnchain block height of when the tokens unlock. Zero if no tokens are locked. - */ - burnchain_unlock_height: number; -} -export interface FtBalance { - balance: string; - total_sent: string; - total_received: string; -} -export interface NftBalance { - count: string; - total_sent: string; - total_received: string; -} -/** - * Token Offering Locked - */ -export interface AddressTokenOfferingLocked { - /** - * Micro-STX amount still locked at current block height. - */ - total_locked: string; - /** - * Micro-STX amount unlocked at current block height. - */ - total_unlocked: string; - unlock_schedule: AddressUnlockSchedule[]; -} -/** - * Unlock schedule amount and block height - */ -export interface AddressUnlockSchedule { - /** - * Micro-STX amount locked at this block height. - */ - amount: string; - block_height: number; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "string", - "message": "string" -} -``` - - - - - -```ts -export interface ErrorResponse { - error: string; - message?: string; - [k: string]: unknown; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/accounts/inbound-stx-transfers.mdx b/content/docs/stacks/api/accounts/inbound-stx-transfers.mdx deleted file mode 100644 index bdf74d141..000000000 --- a/content/docs/stacks/api/accounts/inbound-stx-transfers.mdx +++ /dev/null @@ -1,232 +0,0 @@ ---- -title: Get inbound STX transfers -description: Retrieves a list of STX transfers with memos to the given principal. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get inbound STX transfers - -Retrieves a list of STX transfers with memos to the given principal. This includes regular transfers from a stx-transfer transaction type, - and transfers from contract-call transactions a the `send-many-memo` bulk sending contract. - -### Query Parameters - - - -Results per page - -Default: `20` - -Minimum: `0` - -Maximum: `50` - - - - - -Result offset - -Default: `0` - -Minimum: `0` - - - - - -Filter for transactions only at this given block height - - - - - -Include data from unanchored (i.e. unconfirmed) microblocks - -Default: `false` - - - - - -Block hash or block height. Return data representing the state up until that point in time, rather than the current block. Note - Use either of the query parameters but not both at a time. - - - -### Path Parameters - - - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Default Response | -| `4XX` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/extended/v1/address/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/stx_inbound?limit=20&offset=0&height=0&unanchored=false&until_block=string" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/address/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/stx_inbound?limit=20&offset=0&height=0&unanchored=false&until_block=string", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "sender": "string", - "amount": "string", - "memo": "string", - "block_height": 0, - "tx_id": "string", - "transfer_type": "bulk-send", - "tx_index": 0 - } - ] -} -``` - - - - - -```ts -export interface AddressStxInboundListResponse { - limit: number; - offset: number; - total: number; - results: InboundStxTransfer[]; -} -export interface InboundStxTransfer { - /** - * Principal that sent this transfer - */ - sender: string; - /** - * Transfer amount in micro-STX as integer string - */ - amount: string; - /** - * Hex encoded memo bytes associated with the transfer - */ - memo: string; - /** - * Block height at which this transfer occurred - */ - block_height: number; - /** - * The transaction ID in which this transfer occurred - */ - tx_id: string; - /** - * Indicates if the transfer is from a stx-transfer transaction or a contract-call transaction - */ - transfer_type: "bulk-send" | "stx-transfer" | "stx-transfer-memo"; - /** - * Index of the transaction within a block - */ - tx_index: number; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "string", - "message": "string" -} -``` - - - - - -```ts -export interface ErrorResponse { - error: string; - message?: string; - [k: string]: unknown; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/accounts/index.mdx b/content/docs/stacks/api/accounts/index.mdx deleted file mode 100644 index 3473a5c39..000000000 --- a/content/docs/stacks/api/accounts/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Accounts -index: true -toc: false -description: Manage account balances, transactions, nonces, assets, and related information. ---- \ No newline at end of file diff --git a/content/docs/stacks/api/accounts/latest-nonce.mdx b/content/docs/stacks/api/accounts/latest-nonce.mdx deleted file mode 100644 index fcae1fb94..000000000 --- a/content/docs/stacks/api/accounts/latest-nonce.mdx +++ /dev/null @@ -1,183 +0,0 @@ ---- -title: Get the latest nonce -description: Retrieves the latest nonce values used by an account by inspecting the mempool and anchored transactions. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get the latest nonce used by an account - -Retrieves the latest nonce values used by an account by inspecting the mempool, microblock transactions, and anchored transactions. - -### Query Parameters - - - -Optionally get the nonce at a given block height. - -Minimum: `1` - - - - - -Optionally get the nonce at a given block hash. Note - Use either of the query parameters but not both at a time. - - - -### Path Parameters - - - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | The latest nonce values used by an account by inspecting the mempool, microblock transactions, and anchored transactions | -| `4XX` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/extended/v1/address/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/nonces?block_height=1&block_hash=string" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/address/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/nonces?block_height=1&block_hash=string", { - method: "GET" -}); -``` - - - - - - - - - -The latest nonce values used by an account by inspecting the mempool, microblock transactions, and anchored transactions - - - - - -```json -{ - "last_mempool_tx_nonce": 0, - "last_executed_tx_nonce": 0, - "possible_next_nonce": 0, - "detected_missing_nonces": [ - 0 - ], - "detected_mempool_nonces": [ - 0 - ] -} -``` - - - - - -```ts -/** - * The latest nonce values used by an account by inspecting the mempool, microblock transactions, and anchored transactions - */ -export interface AddressNonces { - last_mempool_tx_nonce: number | null; - last_executed_tx_nonce: number | null; - /** - * The likely nonce required for creating the next transaction, based on the last nonces seen by the API. This can be incorrect if the API's mempool or transactions aren't fully synchronized, even by a small amount, or if a previous transaction is still propagating through the Stacks blockchain network when this endpoint is called. - */ - possible_next_nonce: number; - /** - * Nonces that appear to be missing and likely causing a mempool transaction to be stuck. - */ - detected_missing_nonces: number[]; - /** - * Nonces currently in mempool for this address. - */ - detected_mempool_nonces: number[]; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "string", - "message": "string" -} -``` - - - - - -```ts -export interface ErrorResponse { - error: string; - message?: string; - [k: string]: unknown; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/accounts/meta.json b/content/docs/stacks/api/accounts/meta.json deleted file mode 100644 index cdedb61f1..000000000 --- a/content/docs/stacks/api/accounts/meta.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "title": "Accounts", - "pages": [ - "info", - "assets", - "balances", - "stx-balances", - "principal-stx-balance", - "principal-ft-balances", - "principal-ft-balance", - "inbound-stx-transfers", - "transactions", - "transactions-with-transfers", - "transaction-with-transfers", - "nft-events", - "latest-nonce" - ], - "defaultOpen": false -} \ No newline at end of file diff --git a/content/docs/stacks/api/accounts/principal-ft-balance.mdx b/content/docs/stacks/api/accounts/principal-ft-balance.mdx deleted file mode 100644 index c1c6a2e87..000000000 --- a/content/docs/stacks/api/accounts/principal-ft-balance.mdx +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: Get principal FT balance -description: Retrieves a specific fungible-token balance for a given principal. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get principal FT balance - -Retrieves a specific fungible-token balance for a given principal. - -### Path Parameters - - - - - - - -fungible token identifier - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Default Response | -| `4XX` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/extended/v2/addresses/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/balances/ft/string" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/addresses/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/balances/ft/string", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "balance": "string" -} -``` - - - - - -```ts -export interface Response { - balance: string; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "string", - "message": "string" -} -``` - - - - - -```ts -export interface ErrorResponse { - error: string; - message?: string; - [k: string]: unknown; -} -``` - - - - - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/api/accounts/principal-ft-balances.mdx b/content/docs/stacks/api/accounts/principal-ft-balances.mdx deleted file mode 100644 index 474fd1e8f..000000000 --- a/content/docs/stacks/api/accounts/principal-ft-balances.mdx +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: Get principal FT balances -description: Retrieves Fungible-token account balance information for a given Address or Contract Identifier. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get principal FT balances - -Retrieves Fungible-token account balance information for a given Address or Contract Identifier. - -### Query Parameters - - - -Results per page - -Default: `100` - -Minimum: `0` - -Maximum: `200` - - - - - -Result offset - -Default: `0` - -Minimum: `0` - - - -### Path Parameters - - - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Default Response | -| `4XX` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/extended/v2/addresses/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/balances/ft?limit=100&offset=0" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/addresses/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/balances/ft?limit=100&offset=0", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "token": "string", - "balance": "string" - } - ] -} -``` - - - - - -```ts -export interface Response { - limit: number; - offset: number; - total: number; - results: { - token: string; - balance: string; - }[]; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "string", - "message": "string" -} -``` - - - - - -```ts -export interface ErrorResponse { - error: string; - message?: string; - [k: string]: unknown; -} -``` - - - - - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/api/accounts/principal-stx-balance.mdx b/content/docs/stacks/api/accounts/principal-stx-balance.mdx deleted file mode 100644 index 53d1ad63c..000000000 --- a/content/docs/stacks/api/accounts/principal-stx-balance.mdx +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: Get principal STX balance -description: Retrieves STX account balance information for a given Address or Contract Identifier. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get principal STX balance - -Retrieves STX account balance information for a given Address or Contract Identifier. - -### Query Parameters - - - -Include pending mempool transactions in the balance calculation - -Default: `false` - - - -### Path Parameters - - - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Default Response | -| `4XX` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/extended/v2/addresses/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/balances/stx?include_mempool=false" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/addresses/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/balances/stx?include_mempool=false", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "balance": "string", - "estimated_balance": "string", - "pending_balance_inbound": "string", - "pending_balance_outbound": "string", - "total_sent": "string", - "total_received": "string", - "total_fees_sent": "string", - "total_miner_rewards_received": "string", - "lock_tx_id": "string", - "locked": "string", - "lock_height": 0, - "burnchain_lock_height": 0, - "burnchain_unlock_height": 0 -} -``` - - - - - -```ts -export interface StxBalance { - balance: string; - /** - * Total STX balance considering pending mempool transactions - */ - estimated_balance?: string; - /** - * Inbound STX balance from pending mempool transactions - */ - pending_balance_inbound?: string; - /** - * Outbound STX balance from pending mempool transactions - */ - pending_balance_outbound?: string; - total_sent?: string; - total_received?: string; - total_fees_sent?: string; - total_miner_rewards_received: string; - /** - * The transaction where the lock event occurred. Empty if no tokens are locked. - */ - lock_tx_id: string; - /** - * The amount of locked STX, as string quoted micro-STX. Zero if no tokens are locked. - */ - locked: string; - /** - * The STX chain block height of when the lock event occurred. Zero if no tokens are locked. - */ - lock_height: number; - /** - * The burnchain block height of when the lock event occurred. Zero if no tokens are locked. - */ - burnchain_lock_height: number; - /** - * The burnchain block height of when the tokens unlock. Zero if no tokens are locked. - */ - burnchain_unlock_height: number; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "string", - "message": "string" -} -``` - - - - - -```ts -export interface ErrorResponse { - error: string; - message?: string; - [k: string]: unknown; -} -``` - - - - - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/api/accounts/stx-balances.mdx b/content/docs/stacks/api/accounts/stx-balances.mdx deleted file mode 100644 index 72e4c160f..000000000 --- a/content/docs/stacks/api/accounts/stx-balances.mdx +++ /dev/null @@ -1,250 +0,0 @@ ---- -title: Get account STX balance -description: Retrieves the STX token balance for a specified address or contract identifier. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get account STX balance - -**NOTE:** This endpoint is deprecated in favor of [Get address STX balance](/stacks/api/accounts/principal-stx-balance). - -Retrieves STX token balance for a given Address or Contract Identifier. - -### Query Parameters - - - -Include data from unanchored (i.e. unconfirmed) microblocks - -Default: `false` - - - - - -Block hash or block height. Return data representing the state up until that point in time, rather than the current block. Note - Use either of the query parameters but not both at a time. - - - -### Path Parameters - - - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | GET request that returns address balances | -| `4XX` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/extended/v1/address/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/stx?unanchored=false&until_block=string" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/address/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/stx?unanchored=false&until_block=string", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns address balances - - - - - -```json -{ - "balance": "string", - "estimated_balance": "string", - "pending_balance_inbound": "string", - "pending_balance_outbound": "string", - "total_sent": "string", - "total_received": "string", - "total_fees_sent": "string", - "total_miner_rewards_received": "string", - "lock_tx_id": "string", - "locked": "string", - "lock_height": 0, - "burnchain_lock_height": 0, - "burnchain_unlock_height": 0, - "token_offering_locked": { - "total_locked": "string", - "total_unlocked": "string", - "unlock_schedule": [ - { - "amount": "string", - "block_height": 0 - } - ] - } -} -``` - - - - - -```ts -/** - * GET request that returns address balances - */ -export type AddressStxBalance = StxBalance & { - token_offering_locked?: AddressTokenOfferingLocked; -}; - -export interface StxBalance { - balance: string; - /** - * Total STX balance considering pending mempool transactions - */ - estimated_balance?: string; - /** - * Inbound STX balance from pending mempool transactions - */ - pending_balance_inbound?: string; - /** - * Outbound STX balance from pending mempool transactions - */ - pending_balance_outbound?: string; - total_sent?: string; - total_received?: string; - total_fees_sent?: string; - total_miner_rewards_received: string; - /** - * The transaction where the lock event occurred. Empty if no tokens are locked. - */ - lock_tx_id: string; - /** - * The amount of locked STX, as string quoted micro-STX. Zero if no tokens are locked. - */ - locked: string; - /** - * The STX chain block height of when the lock event occurred. Zero if no tokens are locked. - */ - lock_height: number; - /** - * The burnchain block height of when the lock event occurred. Zero if no tokens are locked. - */ - burnchain_lock_height: number; - /** - * The burnchain block height of when the tokens unlock. Zero if no tokens are locked. - */ - burnchain_unlock_height: number; -} -/** - * Token Offering Locked - */ -export interface AddressTokenOfferingLocked { - /** - * Micro-STX amount still locked at current block height. - */ - total_locked: string; - /** - * Micro-STX amount unlocked at current block height. - */ - total_unlocked: string; - unlock_schedule: AddressUnlockSchedule[]; -} -/** - * Unlock schedule amount and block height - */ -export interface AddressUnlockSchedule { - /** - * Micro-STX amount locked at this block height. - */ - amount: string; - block_height: number; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "string", - "message": "string" -} -``` - - - - - -```ts -export interface ErrorResponse { - error: string; - message?: string; - [k: string]: unknown; -} -``` - - - - - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/api/accounts/transaction-with-transfers.mdx b/content/docs/stacks/api/accounts/transaction-with-transfers.mdx deleted file mode 100644 index f252bd9d5..000000000 --- a/content/docs/stacks/api/accounts/transaction-with-transfers.mdx +++ /dev/null @@ -1,2220 +0,0 @@ ---- -title: Get account transaction with transfers -description: Retrieves transaction details for a specific transaction including STX transfers for each transaction. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get account transaction information for specific transaction - -**NOTE:** This endpoint is deprecated in favor of [Get events for an address transaction](/api/get-address-transaction-events). - - Retrieves transaction details for a given Transaction Id `tx_id`, for a given account or contract Identifier. - -### Path Parameters - - - - - - - -Transaction ID - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Transaction with STX transfers for a given address | -| `4XX` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/extended/v1/address/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/string/with_transfers" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/address/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/string/with_transfers", { - method: "GET" -}); -``` - - - - - - - - - -Transaction with STX transfers for a given address - - - - - -```json -{ - "tx": { - "tx_id": "string", - "nonce": 0, - "fee_rate": "string", - "sender_address": "string", - "sponsor_nonce": 0, - "sponsored": true, - "sponsor_address": "string", - "post_condition_mode": "allow", - "post_conditions": [ - { - "principal": { - "type_id": "principal_origin" - }, - "condition_code": "sent_equal_to", - "amount": "string", - "type": "stx" - } - ], - "anchor_mode": "on_chain_only", - "block_hash": "string", - "block_height": 0, - "block_time": 0, - "block_time_iso": "string", - "burn_block_time": 0, - "burn_block_height": 0, - "burn_block_time_iso": "string", - "parent_burn_block_time": 0, - "parent_burn_block_time_iso": "string", - "canonical": true, - "tx_index": 0, - "tx_status": "success", - "tx_result": { - "hex": "string", - "repr": "string" - }, - "event_count": 0, - "parent_block_hash": "string", - "is_unanchored": true, - "microblock_hash": "string", - "microblock_sequence": 0, - "microblock_canonical": true, - "execution_cost_read_count": 0, - "execution_cost_read_length": 0, - "execution_cost_runtime": 0, - "execution_cost_write_count": 0, - "execution_cost_write_length": 0, - "events": [ - { - "event_index": 0, - "event_type": "smart_contract_log", - "tx_id": "string", - "contract_log": { - "contract_id": "string", - "topic": "string", - "value": { - "hex": "string", - "repr": "string" - } - } - } - ], - "tx_type": "token_transfer", - "token_transfer": { - "recipient_address": "string", - "amount": "string", - "memo": "string" - } - }, - "stx_sent": "string", - "stx_received": "string", - "stx_transfers": [ - { - "amount": "string", - "sender": "string", - "recipient": "string" - } - ], - "ft_transfers": [ - { - "amount": "string", - "asset_identifier": "string", - "sender": "string", - "recipient": "string" - } - ], - "nft_transfers": [ - { - "value": { - "hex": "string", - "repr": "string" - }, - "asset_identifier": "string", - "sender": "string", - "recipient": "string" - } - ] -} -``` - - - - - -```ts -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent = AbstractTransactionEvent & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent = AbstractTransactionEvent1 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent = AbstractTransactionEvent2 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent = AbstractTransactionEvent3 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent = AbstractTransactionEvent4 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent1 = AbstractTransactionEvent5 & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent1 = AbstractTransactionEvent6 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent1 = AbstractTransactionEvent7 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent1 = AbstractTransactionEvent8 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent1 = AbstractTransactionEvent9 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent2 = AbstractTransactionEvent10 & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent2 = AbstractTransactionEvent11 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent2 = AbstractTransactionEvent12 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent2 = AbstractTransactionEvent13 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent2 = AbstractTransactionEvent14 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent3 = AbstractTransactionEvent15 & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent3 = AbstractTransactionEvent16 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent3 = AbstractTransactionEvent17 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent3 = AbstractTransactionEvent18 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent3 = AbstractTransactionEvent19 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent4 = AbstractTransactionEvent20 & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent4 = AbstractTransactionEvent21 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent4 = AbstractTransactionEvent22 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent4 = AbstractTransactionEvent23 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent4 = AbstractTransactionEvent24 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent5 = AbstractTransactionEvent25 & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent5 = AbstractTransactionEvent26 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent5 = AbstractTransactionEvent27 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent5 = AbstractTransactionEvent28 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent5 = AbstractTransactionEvent29 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; - -/** - * Transaction with STX transfers for a given address - */ -export interface AddressTransactionWithTransfers { - tx: - | TokenTransferTransaction - | SmartContractTransaction - | ContractCallTransaction - | PoisonMicroblockTransaction - | CoinbaseTransaction - | TenureChangeTransaction; - /** - * Total sent from the given address, including the tx fee, in micro-STX as an integer string. - */ - stx_sent: string; - /** - * Total received by the given address in micro-STX as an integer string. - */ - stx_received: string; - stx_transfers: { - /** - * Amount transferred in micro-STX as an integer string. - */ - amount: string; - /** - * Principal that sent STX. This is unspecified if the STX were minted. - */ - sender?: string; - /** - * Principal that received STX. This is unspecified if the STX were burned. - */ - recipient?: string; - }[]; - ft_transfers?: { - /** - * Amount transferred as an integer string. This balance does not factor in possible SIP-010 decimals. - */ - amount: string; - /** - * Fungible Token asset identifier. - */ - asset_identifier: string; - /** - * Principal that sent the asset. - */ - sender?: string; - /** - * Principal that received the asset. - */ - recipient?: string; - }[]; - nft_transfers?: { - /** - * Non Fungible Token asset value. - */ - value: { - hex: string; - repr: string; - }; - /** - * Non Fungible Token asset identifier. - */ - asset_identifier: string; - /** - * Principal that sent the asset. - */ - sender?: string; - /** - * Principal that received the asset. - */ - recipient?: string; - }[]; -} -export interface TokenTransferTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent - | StxLockTransactionEvent - | StxAssetTransactionEvent - | FungibleTokenAssetTransactionEvent - | NonFungibleTokenAssetTransactionEvent - )[]; - tx_type: "token_transfer"; - token_transfer: { - recipient_address: string; - /** - * Transfer amount as Integer string (64-bit unsigned integer) - */ - amount: string; - /** - * Hex encoded arbitrary message, up to 34 bytes length (should try decoding to an ASCII string) - */ - memo: string; - }; -} -export interface AbstractTransactionEvent { - event_index: number; -} -export interface AbstractTransactionEvent1 { - event_index: number; -} -export interface AbstractTransactionEvent2 { - event_index: number; -} -export interface AbstractTransactionEvent3 { - event_index: number; -} -export interface AbstractTransactionEvent4 { - event_index: number; -} -export interface SmartContractTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent1 - | StxLockTransactionEvent1 - | StxAssetTransactionEvent1 - | FungibleTokenAssetTransactionEvent1 - | NonFungibleTokenAssetTransactionEvent1 - )[]; - tx_type: "smart_contract"; - smart_contract: { - clarity_version: number | null; - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Clarity code of the smart contract being deployed - */ - source_code: string; - }; -} -export interface AbstractTransactionEvent5 { - event_index: number; -} -export interface AbstractTransactionEvent6 { - event_index: number; -} -export interface AbstractTransactionEvent7 { - event_index: number; -} -export interface AbstractTransactionEvent8 { - event_index: number; -} -export interface AbstractTransactionEvent9 { - event_index: number; -} -export interface ContractCallTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent2 - | StxLockTransactionEvent2 - | StxAssetTransactionEvent2 - | FungibleTokenAssetTransactionEvent2 - | NonFungibleTokenAssetTransactionEvent2 - )[]; - tx_type: "contract_call"; - contract_call: { - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Name of the Clarity function to be invoked - */ - function_name: string; - /** - * Function definition, including function name and type as well as parameter names and types - */ - function_signature: string; - function_args?: { - hex: string; - repr: string; - name: string; - type: string; - }[]; - }; -} -export interface AbstractTransactionEvent10 { - event_index: number; -} -export interface AbstractTransactionEvent11 { - event_index: number; -} -export interface AbstractTransactionEvent12 { - event_index: number; -} -export interface AbstractTransactionEvent13 { - event_index: number; -} -export interface AbstractTransactionEvent14 { - event_index: number; -} -export interface PoisonMicroblockTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent3 - | StxLockTransactionEvent3 - | StxAssetTransactionEvent3 - | FungibleTokenAssetTransactionEvent3 - | NonFungibleTokenAssetTransactionEvent3 - )[]; - tx_type: "poison_microblock"; - poison_microblock: { - /** - * Hex encoded microblock header - */ - microblock_header_1: string; - /** - * Hex encoded microblock header - */ - microblock_header_2: string; - }; -} -export interface AbstractTransactionEvent15 { - event_index: number; -} -export interface AbstractTransactionEvent16 { - event_index: number; -} -export interface AbstractTransactionEvent17 { - event_index: number; -} -export interface AbstractTransactionEvent18 { - event_index: number; -} -export interface AbstractTransactionEvent19 { - event_index: number; -} -export interface CoinbaseTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent4 - | StxLockTransactionEvent4 - | StxAssetTransactionEvent4 - | FungibleTokenAssetTransactionEvent4 - | NonFungibleTokenAssetTransactionEvent4 - )[]; - tx_type: "coinbase"; - coinbase_payload: { - /** - * Hex encoded 32-byte scratch space for block leader's use - */ - data: string; - alt_recipient?: string | null; - vrf_proof?: string | null; - }; -} -export interface AbstractTransactionEvent20 { - event_index: number; -} -export interface AbstractTransactionEvent21 { - event_index: number; -} -export interface AbstractTransactionEvent22 { - event_index: number; -} -export interface AbstractTransactionEvent23 { - event_index: number; -} -export interface AbstractTransactionEvent24 { - event_index: number; -} -export interface TenureChangeTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent5 - | StxLockTransactionEvent5 - | StxAssetTransactionEvent5 - | FungibleTokenAssetTransactionEvent5 - | NonFungibleTokenAssetTransactionEvent5 - )[]; - tx_type: "tenure_change"; - tenure_change_payload: { - /** - * Consensus hash of this tenure. Corresponds to the sortition in which the miner of this block was chosen. - */ - tenure_consensus_hash: string; - /** - * Consensus hash of the previous tenure. Corresponds to the sortition of the previous winning block-commit. - */ - prev_tenure_consensus_hash: string; - /** - * Current consensus hash on the underlying burnchain. Corresponds to the last-seen sortition. - */ - burn_view_consensus_hash: string; - /** - * (Hex string) Stacks Block hash - */ - previous_tenure_end: string; - /** - * The number of blocks produced in the previous tenure. - */ - previous_tenure_blocks: number; - /** - * Cause of change in mining tenure. Depending on cause, tenure can be ended or extended. - */ - cause: "block_found" | "extended"; - /** - * (Hex string) The ECDSA public key hash of the current tenure. - */ - pubkey_hash: string; - }; -} -export interface AbstractTransactionEvent25 { - event_index: number; -} -export interface AbstractTransactionEvent26 { - event_index: number; -} -export interface AbstractTransactionEvent27 { - event_index: number; -} -export interface AbstractTransactionEvent28 { - event_index: number; -} -export interface AbstractTransactionEvent29 { - event_index: number; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "string", - "message": "string" -} -``` - - - - - -```ts -export interface ErrorResponse { - error: string; - message?: string; - [k: string]: unknown; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/accounts/transactions-with-transfers.mdx b/content/docs/stacks/api/accounts/transactions-with-transfers.mdx deleted file mode 100644 index 00c7c70c3..000000000 --- a/content/docs/stacks/api/accounts/transactions-with-transfers.mdx +++ /dev/null @@ -1,2267 +0,0 @@ ---- -title: Get account transactions with transfers -description: Retrieves transactions for a specific account including STX transfers for each transaction. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get account transactions including STX transfers for each transaction. - -Retrieve all transactions for an account or contract identifier including STX transfers for each transaction. - -### Query Parameters - - - -Results per page - -Default: `20` - -Minimum: `0` - -Maximum: `50` - - - - - -Result offset - -Default: `0` - -Minimum: `0` - - - - - -Filter for transactions only at this given block height - - - - - -Include data from unanchored (i.e. unconfirmed) microblocks - -Default: `false` - - - - - -Block hash or block height. Return data representing the state up until that point in time, rather than the current block. Note - Use either of the query parameters but not both at a time. - - - -### Path Parameters - - - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Default Response | -| `4XX` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/extended/v1/address/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/transactions_with_transfers?limit=20&offset=0&height=0&unanchored=false&until_block=string" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/address/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/transactions_with_transfers?limit=20&offset=0&height=0&unanchored=false&until_block=string", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "tx": { - "tx_id": "string", - "nonce": 0, - "fee_rate": "string", - "sender_address": "string", - "sponsor_nonce": 0, - "sponsored": true, - "sponsor_address": "string", - "post_condition_mode": "allow", - "post_conditions": [ - { - "principal": { - "type_id": "principal_origin" - }, - "condition_code": "sent_equal_to", - "amount": "string", - "type": "stx" - } - ], - "anchor_mode": "on_chain_only", - "block_hash": "string", - "block_height": 0, - "block_time": 0, - "block_time_iso": "string", - "burn_block_time": 0, - "burn_block_height": 0, - "burn_block_time_iso": "string", - "parent_burn_block_time": 0, - "parent_burn_block_time_iso": "string", - "canonical": true, - "tx_index": 0, - "tx_status": "success", - "tx_result": { - "hex": "string", - "repr": "string" - }, - "event_count": 0, - "parent_block_hash": "string", - "is_unanchored": true, - "microblock_hash": "string", - "microblock_sequence": 0, - "microblock_canonical": true, - "execution_cost_read_count": 0, - "execution_cost_read_length": 0, - "execution_cost_runtime": 0, - "execution_cost_write_count": 0, - "execution_cost_write_length": 0, - "events": [ - { - "event_index": 0, - "event_type": "smart_contract_log", - "tx_id": "string", - "contract_log": { - "contract_id": "string", - "topic": "string", - "value": { - "hex": "string", - "repr": "string" - } - } - } - ], - "tx_type": "token_transfer", - "token_transfer": { - "recipient_address": "string", - "amount": "string", - "memo": "string" - } - }, - "stx_sent": "string", - "stx_received": "string", - "stx_transfers": [ - { - "amount": "string", - "sender": "string", - "recipient": "string" - } - ], - "ft_transfers": [ - { - "amount": "string", - "asset_identifier": "string", - "sender": "string", - "recipient": "string" - } - ], - "nft_transfers": [ - { - "value": { - "hex": "string", - "repr": "string" - }, - "asset_identifier": "string", - "sender": "string", - "recipient": "string" - } - ] - } - ] -} -``` - - - - - -```ts -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent = AbstractTransactionEvent & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent = AbstractTransactionEvent1 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent = AbstractTransactionEvent2 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent = AbstractTransactionEvent3 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent = AbstractTransactionEvent4 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent1 = AbstractTransactionEvent5 & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent1 = AbstractTransactionEvent6 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent1 = AbstractTransactionEvent7 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent1 = AbstractTransactionEvent8 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent1 = AbstractTransactionEvent9 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent2 = AbstractTransactionEvent10 & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent2 = AbstractTransactionEvent11 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent2 = AbstractTransactionEvent12 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent2 = AbstractTransactionEvent13 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent2 = AbstractTransactionEvent14 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent3 = AbstractTransactionEvent15 & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent3 = AbstractTransactionEvent16 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent3 = AbstractTransactionEvent17 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent3 = AbstractTransactionEvent18 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent3 = AbstractTransactionEvent19 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent4 = AbstractTransactionEvent20 & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent4 = AbstractTransactionEvent21 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent4 = AbstractTransactionEvent22 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent4 = AbstractTransactionEvent23 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent4 = AbstractTransactionEvent24 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent5 = AbstractTransactionEvent25 & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent5 = AbstractTransactionEvent26 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent5 = AbstractTransactionEvent27 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent5 = AbstractTransactionEvent28 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent5 = AbstractTransactionEvent29 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; - -export interface AddressTransactionsWithTransfersListResponse { - limit: number; - offset: number; - total: number; - results: AddressTransactionWithTransfers[]; -} -/** - * Transaction with STX transfers for a given address - */ -export interface AddressTransactionWithTransfers { - tx: - | TokenTransferTransaction - | SmartContractTransaction - | ContractCallTransaction - | PoisonMicroblockTransaction - | CoinbaseTransaction - | TenureChangeTransaction; - /** - * Total sent from the given address, including the tx fee, in micro-STX as an integer string. - */ - stx_sent: string; - /** - * Total received by the given address in micro-STX as an integer string. - */ - stx_received: string; - stx_transfers: { - /** - * Amount transferred in micro-STX as an integer string. - */ - amount: string; - /** - * Principal that sent STX. This is unspecified if the STX were minted. - */ - sender?: string; - /** - * Principal that received STX. This is unspecified if the STX were burned. - */ - recipient?: string; - }[]; - ft_transfers?: { - /** - * Amount transferred as an integer string. This balance does not factor in possible SIP-010 decimals. - */ - amount: string; - /** - * Fungible Token asset identifier. - */ - asset_identifier: string; - /** - * Principal that sent the asset. - */ - sender?: string; - /** - * Principal that received the asset. - */ - recipient?: string; - }[]; - nft_transfers?: { - /** - * Non Fungible Token asset value. - */ - value: { - hex: string; - repr: string; - }; - /** - * Non Fungible Token asset identifier. - */ - asset_identifier: string; - /** - * Principal that sent the asset. - */ - sender?: string; - /** - * Principal that received the asset. - */ - recipient?: string; - }[]; -} -export interface TokenTransferTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent - | StxLockTransactionEvent - | StxAssetTransactionEvent - | FungibleTokenAssetTransactionEvent - | NonFungibleTokenAssetTransactionEvent - )[]; - tx_type: "token_transfer"; - token_transfer: { - recipient_address: string; - /** - * Transfer amount as Integer string (64-bit unsigned integer) - */ - amount: string; - /** - * Hex encoded arbitrary message, up to 34 bytes length (should try decoding to an ASCII string) - */ - memo: string; - }; -} -export interface AbstractTransactionEvent { - event_index: number; -} -export interface AbstractTransactionEvent1 { - event_index: number; -} -export interface AbstractTransactionEvent2 { - event_index: number; -} -export interface AbstractTransactionEvent3 { - event_index: number; -} -export interface AbstractTransactionEvent4 { - event_index: number; -} -export interface SmartContractTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent1 - | StxLockTransactionEvent1 - | StxAssetTransactionEvent1 - | FungibleTokenAssetTransactionEvent1 - | NonFungibleTokenAssetTransactionEvent1 - )[]; - tx_type: "smart_contract"; - smart_contract: { - clarity_version: number | null; - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Clarity code of the smart contract being deployed - */ - source_code: string; - }; -} -export interface AbstractTransactionEvent5 { - event_index: number; -} -export interface AbstractTransactionEvent6 { - event_index: number; -} -export interface AbstractTransactionEvent7 { - event_index: number; -} -export interface AbstractTransactionEvent8 { - event_index: number; -} -export interface AbstractTransactionEvent9 { - event_index: number; -} -export interface ContractCallTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent2 - | StxLockTransactionEvent2 - | StxAssetTransactionEvent2 - | FungibleTokenAssetTransactionEvent2 - | NonFungibleTokenAssetTransactionEvent2 - )[]; - tx_type: "contract_call"; - contract_call: { - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Name of the Clarity function to be invoked - */ - function_name: string; - /** - * Function definition, including function name and type as well as parameter names and types - */ - function_signature: string; - function_args?: { - hex: string; - repr: string; - name: string; - type: string; - }[]; - }; -} -export interface AbstractTransactionEvent10 { - event_index: number; -} -export interface AbstractTransactionEvent11 { - event_index: number; -} -export interface AbstractTransactionEvent12 { - event_index: number; -} -export interface AbstractTransactionEvent13 { - event_index: number; -} -export interface AbstractTransactionEvent14 { - event_index: number; -} -export interface PoisonMicroblockTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent3 - | StxLockTransactionEvent3 - | StxAssetTransactionEvent3 - | FungibleTokenAssetTransactionEvent3 - | NonFungibleTokenAssetTransactionEvent3 - )[]; - tx_type: "poison_microblock"; - poison_microblock: { - /** - * Hex encoded microblock header - */ - microblock_header_1: string; - /** - * Hex encoded microblock header - */ - microblock_header_2: string; - }; -} -export interface AbstractTransactionEvent15 { - event_index: number; -} -export interface AbstractTransactionEvent16 { - event_index: number; -} -export interface AbstractTransactionEvent17 { - event_index: number; -} -export interface AbstractTransactionEvent18 { - event_index: number; -} -export interface AbstractTransactionEvent19 { - event_index: number; -} -export interface CoinbaseTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent4 - | StxLockTransactionEvent4 - | StxAssetTransactionEvent4 - | FungibleTokenAssetTransactionEvent4 - | NonFungibleTokenAssetTransactionEvent4 - )[]; - tx_type: "coinbase"; - coinbase_payload: { - /** - * Hex encoded 32-byte scratch space for block leader's use - */ - data: string; - alt_recipient?: string | null; - vrf_proof?: string | null; - }; -} -export interface AbstractTransactionEvent20 { - event_index: number; -} -export interface AbstractTransactionEvent21 { - event_index: number; -} -export interface AbstractTransactionEvent22 { - event_index: number; -} -export interface AbstractTransactionEvent23 { - event_index: number; -} -export interface AbstractTransactionEvent24 { - event_index: number; -} -export interface TenureChangeTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent5 - | StxLockTransactionEvent5 - | StxAssetTransactionEvent5 - | FungibleTokenAssetTransactionEvent5 - | NonFungibleTokenAssetTransactionEvent5 - )[]; - tx_type: "tenure_change"; - tenure_change_payload: { - /** - * Consensus hash of this tenure. Corresponds to the sortition in which the miner of this block was chosen. - */ - tenure_consensus_hash: string; - /** - * Consensus hash of the previous tenure. Corresponds to the sortition of the previous winning block-commit. - */ - prev_tenure_consensus_hash: string; - /** - * Current consensus hash on the underlying burnchain. Corresponds to the last-seen sortition. - */ - burn_view_consensus_hash: string; - /** - * (Hex string) Stacks Block hash - */ - previous_tenure_end: string; - /** - * The number of blocks produced in the previous tenure. - */ - previous_tenure_blocks: number; - /** - * Cause of change in mining tenure. Depending on cause, tenure can be ended or extended. - */ - cause: "block_found" | "extended"; - /** - * (Hex string) The ECDSA public key hash of the current tenure. - */ - pubkey_hash: string; - }; -} -export interface AbstractTransactionEvent25 { - event_index: number; -} -export interface AbstractTransactionEvent26 { - event_index: number; -} -export interface AbstractTransactionEvent27 { - event_index: number; -} -export interface AbstractTransactionEvent28 { - event_index: number; -} -export interface AbstractTransactionEvent29 { - event_index: number; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "string", - "message": "string" -} -``` - - - - - -```ts -export interface ErrorResponse { - error: string; - message?: string; - [k: string]: unknown; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/accounts/transactions.mdx b/content/docs/stacks/api/accounts/transactions.mdx deleted file mode 100644 index 5766bb46d..000000000 --- a/content/docs/stacks/api/accounts/transactions.mdx +++ /dev/null @@ -1,2180 +0,0 @@ ---- -title: Get account transactions -description: Retrieves transactions for a specific account. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get account transactions - -**NOTE:** This endpoint is deprecated in favor of [Get address transactions](/api/get-address-transactions). - - Retrieves a list of all Transactions for a given Address or Contract Identifier. More information on Transaction types can be found [here](https://docs.stacks.co/understand-stacks/transactions#types). - - If you need to actively monitor new transactions for an address or contract id, we highly recommend subscribing to [WebSockets or Socket.io](https://github.com/hirosystems/stacks-blockchain-api/tree/master/client) for real-time updates. - -### Query Parameters - - - -Results per page - -Default: `20` - -Minimum: `0` - -Maximum: `50` - - - - - -Result offset - -Default: `0` - -Minimum: `0` - - - - - -Filter for transactions only at this given block height - - - - - -Include data from unanchored (i.e. unconfirmed) microblocks - -Default: `false` - - - - - -Block hash or block height. Return data representing the state up until that point in time, rather than the current block. Note - Use either of the query parameters but not both at a time. - - - -### Path Parameters - - - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | GET request that returns account transactions | -| `4XX` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/extended/v1/address/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/transactions?limit=20&offset=0&height=0&unanchored=false&until_block=string" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/address/SP318Q55DEKHRXJK696033DQN5C54D9K2EE6DHRWP/transactions?limit=20&offset=0&height=0&unanchored=false&until_block=string", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns account transactions - - - - - -```json -{ - "limit": 20, - "offset": 0, - "total": 1, - "results": [ - { - "tx_id": "string", - "nonce": 0, - "fee_rate": "string", - "sender_address": "string", - "sponsor_nonce": 0, - "sponsored": true, - "sponsor_address": "string", - "post_condition_mode": "allow", - "post_conditions": [ - { - "principal": { - "type_id": "principal_origin" - }, - "condition_code": "sent_equal_to", - "amount": "string", - "type": "stx" - } - ], - "anchor_mode": "on_chain_only", - "block_hash": "string", - "block_height": 0, - "block_time": 0, - "block_time_iso": "string", - "burn_block_time": 0, - "burn_block_height": 0, - "burn_block_time_iso": "string", - "parent_burn_block_time": 0, - "parent_burn_block_time_iso": "string", - "canonical": true, - "tx_index": 0, - "tx_status": "success", - "tx_result": { - "hex": "string", - "repr": "string" - }, - "event_count": 0, - "parent_block_hash": "string", - "is_unanchored": true, - "microblock_hash": "string", - "microblock_sequence": 0, - "microblock_canonical": true, - "execution_cost_read_count": 0, - "execution_cost_read_length": 0, - "execution_cost_runtime": 0, - "execution_cost_write_count": 0, - "execution_cost_write_length": 0, - "events": [ - { - "event_index": 0, - "event_type": "smart_contract_log", - "tx_id": "string", - "contract_log": { - "contract_id": "string", - "topic": "string", - "value": { - "hex": "string", - "repr": "string" - } - } - } - ], - "tx_type": "token_transfer", - "token_transfer": { - "recipient_address": "string", - "amount": "string", - "memo": "string" - } - } - ] -} -``` - - - - - -```ts -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent = AbstractTransactionEvent & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent = AbstractTransactionEvent1 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent = AbstractTransactionEvent2 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent = AbstractTransactionEvent3 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent = AbstractTransactionEvent4 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent1 = AbstractTransactionEvent5 & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent1 = AbstractTransactionEvent6 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent1 = AbstractTransactionEvent7 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent1 = AbstractTransactionEvent8 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent1 = AbstractTransactionEvent9 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent2 = AbstractTransactionEvent10 & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent2 = AbstractTransactionEvent11 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent2 = AbstractTransactionEvent12 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent2 = AbstractTransactionEvent13 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent2 = AbstractTransactionEvent14 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent3 = AbstractTransactionEvent15 & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent3 = AbstractTransactionEvent16 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent3 = AbstractTransactionEvent17 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent3 = AbstractTransactionEvent18 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent3 = AbstractTransactionEvent19 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent4 = AbstractTransactionEvent20 & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent4 = AbstractTransactionEvent21 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent4 = AbstractTransactionEvent22 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent4 = AbstractTransactionEvent23 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent4 = AbstractTransactionEvent24 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type SmartContractLogTransactionEvent5 = AbstractTransactionEvent25 & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxLockTransactionEvent5 = AbstractTransactionEvent26 & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type StxAssetTransactionEvent5 = AbstractTransactionEvent27 & { - event_type: "stx_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - sender: string; - recipient: string; - amount: string; - memo?: string; - }; -}; -export type FungibleTokenAssetTransactionEvent5 = AbstractTransactionEvent28 & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type NonFungibleTokenAssetTransactionEvent5 = AbstractTransactionEvent29 & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: "transfer" | "mint" | "burn"; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; - -/** - * GET request that returns account transactions - */ -export interface AddressTransactionsListResponse { - limit: number; - offset: number; - total: number; - results: ( - | TokenTransferTransaction - | SmartContractTransaction - | ContractCallTransaction - | PoisonMicroblockTransaction - | CoinbaseTransaction - | TenureChangeTransaction - )[]; -} -export interface TokenTransferTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent - | StxLockTransactionEvent - | StxAssetTransactionEvent - | FungibleTokenAssetTransactionEvent - | NonFungibleTokenAssetTransactionEvent - )[]; - tx_type: "token_transfer"; - token_transfer: { - recipient_address: string; - /** - * Transfer amount as Integer string (64-bit unsigned integer) - */ - amount: string; - /** - * Hex encoded arbitrary message, up to 34 bytes length (should try decoding to an ASCII string) - */ - memo: string; - }; -} -export interface AbstractTransactionEvent { - event_index: number; -} -export interface AbstractTransactionEvent1 { - event_index: number; -} -export interface AbstractTransactionEvent2 { - event_index: number; -} -export interface AbstractTransactionEvent3 { - event_index: number; -} -export interface AbstractTransactionEvent4 { - event_index: number; -} -export interface SmartContractTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent1 - | StxLockTransactionEvent1 - | StxAssetTransactionEvent1 - | FungibleTokenAssetTransactionEvent1 - | NonFungibleTokenAssetTransactionEvent1 - )[]; - tx_type: "smart_contract"; - smart_contract: { - clarity_version: number | null; - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Clarity code of the smart contract being deployed - */ - source_code: string; - }; -} -export interface AbstractTransactionEvent5 { - event_index: number; -} -export interface AbstractTransactionEvent6 { - event_index: number; -} -export interface AbstractTransactionEvent7 { - event_index: number; -} -export interface AbstractTransactionEvent8 { - event_index: number; -} -export interface AbstractTransactionEvent9 { - event_index: number; -} -export interface ContractCallTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent2 - | StxLockTransactionEvent2 - | StxAssetTransactionEvent2 - | FungibleTokenAssetTransactionEvent2 - | NonFungibleTokenAssetTransactionEvent2 - )[]; - tx_type: "contract_call"; - contract_call: { - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Name of the Clarity function to be invoked - */ - function_name: string; - /** - * Function definition, including function name and type as well as parameter names and types - */ - function_signature: string; - function_args?: { - hex: string; - repr: string; - name: string; - type: string; - }[]; - }; -} -export interface AbstractTransactionEvent10 { - event_index: number; -} -export interface AbstractTransactionEvent11 { - event_index: number; -} -export interface AbstractTransactionEvent12 { - event_index: number; -} -export interface AbstractTransactionEvent13 { - event_index: number; -} -export interface AbstractTransactionEvent14 { - event_index: number; -} -export interface PoisonMicroblockTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent3 - | StxLockTransactionEvent3 - | StxAssetTransactionEvent3 - | FungibleTokenAssetTransactionEvent3 - | NonFungibleTokenAssetTransactionEvent3 - )[]; - tx_type: "poison_microblock"; - poison_microblock: { - /** - * Hex encoded microblock header - */ - microblock_header_1: string; - /** - * Hex encoded microblock header - */ - microblock_header_2: string; - }; -} -export interface AbstractTransactionEvent15 { - event_index: number; -} -export interface AbstractTransactionEvent16 { - event_index: number; -} -export interface AbstractTransactionEvent17 { - event_index: number; -} -export interface AbstractTransactionEvent18 { - event_index: number; -} -export interface AbstractTransactionEvent19 { - event_index: number; -} -export interface CoinbaseTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent4 - | StxLockTransactionEvent4 - | StxAssetTransactionEvent4 - | FungibleTokenAssetTransactionEvent4 - | NonFungibleTokenAssetTransactionEvent4 - )[]; - tx_type: "coinbase"; - coinbase_payload: { - /** - * Hex encoded 32-byte scratch space for block leader's use - */ - data: string; - alt_recipient?: string | null; - vrf_proof?: string | null; - }; -} -export interface AbstractTransactionEvent20 { - event_index: number; -} -export interface AbstractTransactionEvent21 { - event_index: number; -} -export interface AbstractTransactionEvent22 { - event_index: number; -} -export interface AbstractTransactionEvent23 { - event_index: number; -} -export interface AbstractTransactionEvent24 { - event_index: number; -} -export interface TenureChangeTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: "allow" | "deny"; - post_conditions: ( - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "stx"; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; - amount: string; - type: "fungible"; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - | { - principal: - | { - type_id: "principal_origin"; - } - | { - type_id: "principal_standard"; - address: string; - } - | { - type_id: "principal_contract"; - address: string; - contract_name: string; - }; - condition_code: "sent" | "not_sent"; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; - } - )[]; - /** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ - anchor_mode: "on_chain_only" | "off_chain_only" | "any"; - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - /** - * Status of the transaction - */ - tx_status: "success" | "abort_by_response" | "abort_by_post_condition"; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - events: ( - | SmartContractLogTransactionEvent5 - | StxLockTransactionEvent5 - | StxAssetTransactionEvent5 - | FungibleTokenAssetTransactionEvent5 - | NonFungibleTokenAssetTransactionEvent5 - )[]; - tx_type: "tenure_change"; - tenure_change_payload: { - /** - * Consensus hash of this tenure. Corresponds to the sortition in which the miner of this block was chosen. - */ - tenure_consensus_hash: string; - /** - * Consensus hash of the previous tenure. Corresponds to the sortition of the previous winning block-commit. - */ - prev_tenure_consensus_hash: string; - /** - * Current consensus hash on the underlying burnchain. Corresponds to the last-seen sortition. - */ - burn_view_consensus_hash: string; - /** - * (Hex string) Stacks Block hash - */ - previous_tenure_end: string; - /** - * The number of blocks produced in the previous tenure. - */ - previous_tenure_blocks: number; - /** - * Cause of change in mining tenure. Depending on cause, tenure can be ended or extended. - */ - cause: "block_found" | "extended"; - /** - * (Hex string) The ECDSA public key hash of the current tenure. - */ - pubkey_hash: string; - }; -} -export interface AbstractTransactionEvent25 { - event_index: number; -} -export interface AbstractTransactionEvent26 { - event_index: number; -} -export interface AbstractTransactionEvent27 { - event_index: number; -} -export interface AbstractTransactionEvent28 { - event_index: number; -} -export interface AbstractTransactionEvent29 { - event_index: number; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "string", - "message": "string" -} -``` - - - - - -```ts -export interface ErrorResponse { - error: string; - message?: string; - [k: string]: unknown; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/architecture.mdx b/content/docs/stacks/api/architecture.mdx deleted file mode 100644 index 133eb46af..000000000 --- a/content/docs/stacks/api/architecture.mdx +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Architecture -description: Understand the architecture of the Stacks Blockchain API. ---- - -import { ImageZoom } from 'fumadocs-ui/components/image-zoom'; - - - -## RPC Endpoints - -The `stacks-node` has its own minimal set of http endpoints referred to as `RPC endpoints`. - -- The `stacks-blockchain-api` allows clients to access RPC endpoints by proxying requests to a load-balanced pool of `stacks-nodes`. -- For more details on RPC endpoints, see: [RPC Endpoints Documentation](https://github.com/blockstack/stacks-blockchain/blob/master/docs/rpc-endpoints.md) -- Common RPC endpoints include: - - `POST /v2/transactions` - Broadcast a transaction - - `GET /v2/pox` - Retrieve current Proof of Transfer (PoX) relevant information - - `POST /v2/contracts/call-read//` - Evaluate and return the result of calling a Clarity function - - `POST /v2/fees/transaction` - Evaluate a given transaction and provide transaction fee estimation data - - `GET /v2/accounts/
` - Fetch the current nonce required for creating transactions - -## Additional Endpoints - -The Stacks Blockchain API implements additional endpoints that provide data unavailable directly from Stacks nodes due to various constraints. - -- The `stacks-node` may not persist certain data or may not serve it efficiently to many clients. For instance, while it can return the current STX balance of an account, it cannot provide a history of account transactions. -- The API implements the Rosetta specification by Coinbase, an open standard designed to simplify blockchain deployment and interaction. More information can be found at [Rosetta API](https://www.rosetta-api.org/). -- The API includes support for the Blockchain Naming System (BNS) endpoints. Details are available at [BNS Documentation](https://docs.stacks.co/clarity/example-contracts/bns). -- For Express.js routes, see the directory `/src/api/routes`. - -The API creates an "event observer" http server which listens for events from a stacks-node "event emitter". - -Events are HTTP POST requests containing: - - Blocks - - Transactions - -Byproducts of executed transactions such as: - - Asset transfers - - Smart-contract log data - - Execution cost data - -The API processes and stores these events as relational data in PostgreSQL. For the "event observer" code, see `/src/event-stream`. - -## OpenAPI and JSON Schema - -All http endpoints and responses are defined in OpenAPI and JSON Schema. - -- See `/docs/openapi.yaml` -- These are used to auto-generate the docs at https://hirosystems.github.io/stacks-blockchain-api/ -- JSON Schemas are converted into TypeScript interfaces, which are used internally by the db controller module to transform SQL query results into the correct object shapes. -- OpenAPI and JSON Schemas are also used to generate a standalone `@stacks/blockchain-api-client`. - -## Development Setup - -The easiest/quickest way to develop in this repo is using the VS Code debugger. It uses docker-compose to set up a stacks-node and Postgres instance. - -Alternatively, you can run `npm run dev:integrated` which does the same thing but without a debugger. diff --git a/content/docs/stacks/api/blocks/average-times.mdx b/content/docs/stacks/api/blocks/average-times.mdx deleted file mode 100644 index b0a665b78..000000000 --- a/content/docs/stacks/api/blocks/average-times.mdx +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: Get average block times -description: Retrieves average block times. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get average block times - -Retrieves average block times (in seconds) - -| Status code | Description | -| :------ | :------ | -| `200` | Average block times (in seconds) | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v2/blocks/average-times" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/blocks/average-times", { - method: "GET" -}); -``` - - - - - - - - - -Request to fetch average block times (in seconds) - - - - - -```json -{ - "last_1h": 0, - "last_24h": 0, - "last_7d": 0, - "last_30d": 0 -} -``` - - - - - -```ts -/** - * Request to fetch average block times (in seconds) - */ -export interface AverageBlockTimesResponse { - /** - * Average block times over the last hour (in seconds) - */ - last_1h: number; - /** - * Average block times over the last 24 hours (in seconds) - */ - last_24h: number; - /** - * Average block times over the last 7 days (in seconds) - */ - last_7d: number; - /** - * Average block times over the last 30 days (in seconds) - */ - last_30d: number; -} -``` - - - - - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/api/blocks/block-by-burn-block-hash.mdx b/content/docs/stacks/api/blocks/block-by-burn-block-hash.mdx deleted file mode 100644 index f131a8d3a..000000000 --- a/content/docs/stacks/api/blocks/block-by-burn-block-hash.mdx +++ /dev/null @@ -1,237 +0,0 @@ ---- -title: Get block by burnchain block hash -description: Retrieves block details of a specific block for a given burnchain block hash. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get block by burnchain block hash - - -This endpoint is deprecated in favor of [Get blocks](/stacks/api/blocks/get-blocks). - - -Retrieves block details of a specific block for a given burnchain block hash - -| Status code | Description | -| :------ | :------ | -| `200` | Block | -| `404` | Cannot find block with given height | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/block/by_burn_block_hash/%7Bburn_block_hash%7D" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/block/by_burn_block_hash/%7Bburn_block_hash%7D", { - method: "GET" -}); -``` - - - - - - - - - -A block - - - - - -```json -{ - "canonical": true, - "height": 0, - "hash": "string", - "block_time": 0, - "block_time_iso": "string", - "index_block_hash": "string", - "parent_block_hash": "string", - "burn_block_time": 0, - "burn_block_time_iso": "string", - "burn_block_hash": "string", - "burn_block_height": 0, - "miner_txid": "string", - "parent_microblock_hash": "string", - "parent_microblock_sequence": 0, - "txs": [ - "string" - ], - "microblocks_accepted": [ - "string" - ], - "microblocks_streamed": [ - "string" - ], - "execution_cost_read_count": 0, - "execution_cost_read_length": 0, - "execution_cost_runtime": 0, - "execution_cost_write_count": 0, - "execution_cost_write_length": 0, - "microblock_tx_count": { - "property1": 0, - "property2": 0 - } -} -``` - - - - - -```ts -/** - * A block - */ -export interface Block { - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Height of the block - */ - height: number; - /** - * Hash representing the block - */ - hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * The only hash that can uniquely identify an anchored block or an unconfirmed state trie - */ - index_block_hash: string; - /** - * Hash of the parent block - */ - parent_block_hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Hash of the anchor chain block - */ - burn_block_hash: string; - /** - * Height of the anchor chain block - */ - burn_block_height: number; - /** - * Anchor chain transaction ID - */ - miner_txid: string; - /** - * The hash of the last streamed block that precedes this block to which this block is to be appended. Not every anchored block will have a parent microblock stream. An anchored block that does not have a parent microblock stream has the parent microblock hash set to an empty string, and the parent microblock sequence number set to -1. - */ - parent_microblock_hash: string; - /** - * The hash of the last streamed block that precedes this block to which this block is to be appended. Not every anchored block will have a parent microblock stream. An anchored block that does not have a parent microblock stream has the parent microblock hash set to an empty string, and the parent microblock sequence number set to -1. - */ - parent_microblock_sequence: number; - /** - * List of transactions included in the block - */ - txs: string[]; - /** - * List of microblocks that were accepted in this anchor block. Not every anchored block will have a accepted all (or any) of the previously streamed microblocks. Microblocks that were orphaned are not included in this list. - */ - microblocks_accepted: string[]; - /** - * List of microblocks that were streamed/produced by this anchor block's miner. This list only includes microblocks that were accepted in the following anchor block. Microblocks that were orphaned are not included in this list. - */ - microblocks_streamed: string[]; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - /** - * List of txs counts in each accepted microblock - */ - microblock_tx_count: { - [k: string]: number; - }; -} -``` - - - - - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/api/blocks/block-by-burn-block-height.mdx b/content/docs/stacks/api/blocks/block-by-burn-block-height.mdx deleted file mode 100644 index f99b40d54..000000000 --- a/content/docs/stacks/api/blocks/block-by-burn-block-height.mdx +++ /dev/null @@ -1,237 +0,0 @@ ---- -title: Get block by burnchain block height -description: Retrieves block details of a specific block for a given burnchain block height. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get block by burnchain height - - -This endpoint is deprecated in favor of [Get blocks](/stacks/api/blocks/get-blocks). - - -Retrieves block details of a specific block for a given burn chain height - -| Status code | Description | -| :------ | :------ | -| `200` | Block | -| `404` | Cannot find block with given height | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/block/by_burn_block_height/%7Bburn_block_height%7D" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/block/by_burn_block_height/%7Bburn_block_height%7D", { - method: "GET" -}); -``` - - - - - - - - - -A block - - - - - -```json -{ - "canonical": true, - "height": 0, - "hash": "string", - "block_time": 0, - "block_time_iso": "string", - "index_block_hash": "string", - "parent_block_hash": "string", - "burn_block_time": 0, - "burn_block_time_iso": "string", - "burn_block_hash": "string", - "burn_block_height": 0, - "miner_txid": "string", - "parent_microblock_hash": "string", - "parent_microblock_sequence": 0, - "txs": [ - "string" - ], - "microblocks_accepted": [ - "string" - ], - "microblocks_streamed": [ - "string" - ], - "execution_cost_read_count": 0, - "execution_cost_read_length": 0, - "execution_cost_runtime": 0, - "execution_cost_write_count": 0, - "execution_cost_write_length": 0, - "microblock_tx_count": { - "property1": 0, - "property2": 0 - } -} -``` - - - - - -```ts -/** - * A block - */ -export interface Block { - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Height of the block - */ - height: number; - /** - * Hash representing the block - */ - hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * The only hash that can uniquely identify an anchored block or an unconfirmed state trie - */ - index_block_hash: string; - /** - * Hash of the parent block - */ - parent_block_hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Hash of the anchor chain block - */ - burn_block_hash: string; - /** - * Height of the anchor chain block - */ - burn_block_height: number; - /** - * Anchor chain transaction ID - */ - miner_txid: string; - /** - * The hash of the last streamed block that precedes this block to which this block is to be appended. Not every anchored block will have a parent microblock stream. An anchored block that does not have a parent microblock stream has the parent microblock hash set to an empty string, and the parent microblock sequence number set to -1. - */ - parent_microblock_hash: string; - /** - * The hash of the last streamed block that precedes this block to which this block is to be appended. Not every anchored block will have a parent microblock stream. An anchored block that does not have a parent microblock stream has the parent microblock hash set to an empty string, and the parent microblock sequence number set to -1. - */ - parent_microblock_sequence: number; - /** - * List of transactions included in the block - */ - txs: string[]; - /** - * List of microblocks that were accepted in this anchor block. Not every anchored block will have a accepted all (or any) of the previously streamed microblocks. Microblocks that were orphaned are not included in this list. - */ - microblocks_accepted: string[]; - /** - * List of microblocks that were streamed/produced by this anchor block's miner. This list only includes microblocks that were accepted in the following anchor block. Microblocks that were orphaned are not included in this list. - */ - microblocks_streamed: string[]; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - /** - * List of txs counts in each accepted microblock - */ - microblock_tx_count: { - [k: string]: number; - }; -} -``` - - - - - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/api/blocks/block-by-hash.mdx b/content/docs/stacks/api/blocks/block-by-hash.mdx deleted file mode 100644 index 8f34541f5..000000000 --- a/content/docs/stacks/api/blocks/block-by-hash.mdx +++ /dev/null @@ -1,237 +0,0 @@ ---- -title: Get block by hash -description: Retrieves block details of a specific block for a given chain height. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get block by hash - - -This endpoint is deprecated in favor of [Get blocks](/stacks/api/blocks/get-blocks). - - -Retrieves block details of a specific block for a given chain height. You can use the hash from your latest block ('get_block_list' API) to get your block details. - -| Status code | Description | -| :------ | :------ | -| `200` | Block | -| `404` | Cannot find block with given ID | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/block/%7Bhash%7D" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/block/%7Bhash%7D", { - method: "GET" -}); -``` - - - - - - - - - -A block - - - - - -```json -{ - "canonical": true, - "height": 0, - "hash": "string", - "block_time": 0, - "block_time_iso": "string", - "index_block_hash": "string", - "parent_block_hash": "string", - "burn_block_time": 0, - "burn_block_time_iso": "string", - "burn_block_hash": "string", - "burn_block_height": 0, - "miner_txid": "string", - "parent_microblock_hash": "string", - "parent_microblock_sequence": 0, - "txs": [ - "string" - ], - "microblocks_accepted": [ - "string" - ], - "microblocks_streamed": [ - "string" - ], - "execution_cost_read_count": 0, - "execution_cost_read_length": 0, - "execution_cost_runtime": 0, - "execution_cost_write_count": 0, - "execution_cost_write_length": 0, - "microblock_tx_count": { - "property1": 0, - "property2": 0 - } -} -``` - - - - - -```ts -/** - * A block - */ -export interface Block { - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Height of the block - */ - height: number; - /** - * Hash representing the block - */ - hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * The only hash that can uniquely identify an anchored block or an unconfirmed state trie - */ - index_block_hash: string; - /** - * Hash of the parent block - */ - parent_block_hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Hash of the anchor chain block - */ - burn_block_hash: string; - /** - * Height of the anchor chain block - */ - burn_block_height: number; - /** - * Anchor chain transaction ID - */ - miner_txid: string; - /** - * The hash of the last streamed block that precedes this block to which this block is to be appended. Not every anchored block will have a parent microblock stream. An anchored block that does not have a parent microblock stream has the parent microblock hash set to an empty string, and the parent microblock sequence number set to -1. - */ - parent_microblock_hash: string; - /** - * The hash of the last streamed block that precedes this block to which this block is to be appended. Not every anchored block will have a parent microblock stream. An anchored block that does not have a parent microblock stream has the parent microblock hash set to an empty string, and the parent microblock sequence number set to -1. - */ - parent_microblock_sequence: number; - /** - * List of transactions included in the block - */ - txs: string[]; - /** - * List of microblocks that were accepted in this anchor block. Not every anchored block will have a accepted all (or any) of the previously streamed microblocks. Microblocks that were orphaned are not included in this list. - */ - microblocks_accepted: string[]; - /** - * List of microblocks that were streamed/produced by this anchor block's miner. This list only includes microblocks that were accepted in the following anchor block. Microblocks that were orphaned are not included in this list. - */ - microblocks_streamed: string[]; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - /** - * List of txs counts in each accepted microblock - */ - microblock_tx_count: { - [k: string]: number; - }; -} -``` - - - - - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/api/blocks/block-by-height.mdx b/content/docs/stacks/api/blocks/block-by-height.mdx deleted file mode 100644 index ac3678840..000000000 --- a/content/docs/stacks/api/blocks/block-by-height.mdx +++ /dev/null @@ -1,238 +0,0 @@ ---- -title: Get block by height -description: Retrieves block details of a specific block for a given chain height. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get block by height - - -This endpoint is deprecated in favor of [Get blocks](/stacks/api/blocks/get-block). - - -Retrieves block details of a specific block at a given block height - - -| Status code | Description | -| :------ | :------ | -| `200` | Block | -| `404` | Cannot find block with given height | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/block/by_height/%7Bheight%7D" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/block/by_height/%7Bheight%7D", { - method: "GET" -}); -``` - - - - - - - - - -A block - - - - - -```json -{ - "canonical": true, - "height": 0, - "hash": "string", - "block_time": 0, - "block_time_iso": "string", - "index_block_hash": "string", - "parent_block_hash": "string", - "burn_block_time": 0, - "burn_block_time_iso": "string", - "burn_block_hash": "string", - "burn_block_height": 0, - "miner_txid": "string", - "parent_microblock_hash": "string", - "parent_microblock_sequence": 0, - "txs": [ - "string" - ], - "microblocks_accepted": [ - "string" - ], - "microblocks_streamed": [ - "string" - ], - "execution_cost_read_count": 0, - "execution_cost_read_length": 0, - "execution_cost_runtime": 0, - "execution_cost_write_count": 0, - "execution_cost_write_length": 0, - "microblock_tx_count": { - "property1": 0, - "property2": 0 - } -} -``` - - - - - -```ts -/** - * A block - */ -export interface Block { - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Height of the block - */ - height: number; - /** - * Hash representing the block - */ - hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * The only hash that can uniquely identify an anchored block or an unconfirmed state trie - */ - index_block_hash: string; - /** - * Hash of the parent block - */ - parent_block_hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Hash of the anchor chain block - */ - burn_block_hash: string; - /** - * Height of the anchor chain block - */ - burn_block_height: number; - /** - * Anchor chain transaction ID - */ - miner_txid: string; - /** - * The hash of the last streamed block that precedes this block to which this block is to be appended. Not every anchored block will have a parent microblock stream. An anchored block that does not have a parent microblock stream has the parent microblock hash set to an empty string, and the parent microblock sequence number set to -1. - */ - parent_microblock_hash: string; - /** - * The hash of the last streamed block that precedes this block to which this block is to be appended. Not every anchored block will have a parent microblock stream. An anchored block that does not have a parent microblock stream has the parent microblock hash set to an empty string, and the parent microblock sequence number set to -1. - */ - parent_microblock_sequence: number; - /** - * List of transactions included in the block - */ - txs: string[]; - /** - * List of microblocks that were accepted in this anchor block. Not every anchored block will have a accepted all (or any) of the previously streamed microblocks. Microblocks that were orphaned are not included in this list. - */ - microblocks_accepted: string[]; - /** - * List of microblocks that were streamed/produced by this anchor block's miner. This list only includes microblocks that were accepted in the following anchor block. Microblocks that were orphaned are not included in this list. - */ - microblocks_streamed: string[]; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - /** - * List of txs counts in each accepted microblock - */ - microblock_tx_count: { - [k: string]: number; - }; -} -``` - - - - - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/api/blocks/get-block.mdx b/content/docs/stacks/api/blocks/get-block.mdx deleted file mode 100644 index 6035dcb24..000000000 --- a/content/docs/stacks/api/blocks/get-block.mdx +++ /dev/null @@ -1,209 +0,0 @@ ---- -title: Get block -description: Retrieves a single block. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get block - -Retrieves a single block - -### Path Parameters - - - -filter by block height, hash, index block hash or the constant `latest` to filter for the most recent block - - - -| Status code | Description | -| :------ | :------ | -| `200` | Block | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v2/blocks/42000" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/blocks/42000", { - method: "GET" -}); -``` - - - - - - - - - -A block - - - - - -```json -{ - "canonical": true, - "height": 0, - "hash": "string", - "block_time": 0, - "block_time_iso": "string", - "index_block_hash": "string", - "parent_block_hash": "string", - "parent_index_block_hash": "string", - "burn_block_time": 0, - "burn_block_time_iso": "string", - "burn_block_hash": "string", - "burn_block_height": 0, - "miner_txid": "string", - "tx_count": 0, - "execution_cost_read_count": 0, - "execution_cost_read_length": 0, - "execution_cost_runtime": 0, - "execution_cost_write_count": 0, - "execution_cost_write_length": 0 -} -``` - - - - - -```ts -/** - * A block - */ -export interface NakamotoBlock { - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Height of the block - */ - height: number; - /** - * Hash representing the block - */ - hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * The only hash that can uniquely identify an anchored block or an unconfirmed state trie - */ - index_block_hash: string; - /** - * Hash of the parent block - */ - parent_block_hash: string; - /** - * Index block hash of the parent block - */ - parent_index_block_hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Hash of the anchor chain block - */ - burn_block_hash: string; - /** - * Height of the anchor chain block - */ - burn_block_height: number; - /** - * Anchor chain transaction ID - */ - miner_txid: string; - /** - * Number of transactions included in the block - */ - tx_count: number; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/blocks/get-blocks-by-burn-block.mdx b/content/docs/stacks/api/blocks/get-blocks-by-burn-block.mdx deleted file mode 100644 index 43dad5dc9..000000000 --- a/content/docs/stacks/api/blocks/get-blocks-by-burn-block.mdx +++ /dev/null @@ -1,252 +0,0 @@ ---- -title: Get blocks by burn block -description: Retrieves a list of blocks confirmed by a specific burn block. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get blocks by burn block - -Retrieves a list of blocks confirmed by a specific burn block - -### Path Parameters - - - -filter by burn block height, hash, or the constant `latest` to filter for the most recent burn block - - - -### Query Parameters - - - -max number of blocks to fetch - -Example: `20` - - - - - -index of first burn block to fetch - -Example: `0` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of blocks | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v2/burn-blocks/42000/blocks?limit=20&offset=0" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/burn-blocks/42000/blocks?limit=20&offset=0", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns blocks - - - - - -```json -{ - "limit": 30, - "offset": 0, - "total": 0, - "results": [ - { - "canonical": true, - "height": 0, - "hash": "string", - "block_time": 0, - "block_time_iso": "string", - "index_block_hash": "string", - "parent_block_hash": "string", - "parent_index_block_hash": "string", - "burn_block_time": 0, - "burn_block_time_iso": "string", - "burn_block_hash": "string", - "burn_block_height": 0, - "miner_txid": "string", - "tx_count": 0, - "execution_cost_read_count": 0, - "execution_cost_read_length": 0, - "execution_cost_runtime": 0, - "execution_cost_write_count": 0, - "execution_cost_write_length": 0 - } - ] -} -``` - - - - - -```ts -/** - * GET request that returns blocks - */ -export interface NakamotoBlockListResponse { - /** - * The number of blocks to return - */ - limit: number; - /** - * The number to blocks to skip (starting at `0`) - */ - offset: number; - /** - * The number of blocks available - */ - total: number; - results: NakamotoBlock[]; -} -/** - * A block - */ -export interface NakamotoBlock { - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Height of the block - */ - height: number; - /** - * Hash representing the block - */ - hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * The only hash that can uniquely identify an anchored block or an unconfirmed state trie - */ - index_block_hash: string; - /** - * Hash of the parent block - */ - parent_block_hash: string; - /** - * Index block hash of the parent block - */ - parent_index_block_hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Hash of the anchor chain block - */ - burn_block_hash: string; - /** - * Height of the anchor chain block - */ - burn_block_height: number; - /** - * Anchor chain transaction ID - */ - miner_txid: string; - /** - * Number of transactions included in the block - */ - tx_count: number; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/blocks/get-blocks.mdx b/content/docs/stacks/api/blocks/get-blocks.mdx deleted file mode 100644 index c49bd756b..000000000 --- a/content/docs/stacks/api/blocks/get-blocks.mdx +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: Get blocks -description: Retrieves a list of recently mined blocks. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get blocks - -Retrieves a list of recently mined blocks - - -### Query Parameters - - - -max number of blocks to fetch - -Example: `20` - - - - - -index of first burn block to fetch - -Example: `0` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of blocks | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v2/blocks?limit=20&offset=0" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/blocks?limit=20&offset=0", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns blocks - - - - - -```json -{ - "limit": 30, - "offset": 0, - "total": 0, - "results": [ - { - "canonical": true, - "height": 0, - "hash": "string", - "block_time": 0, - "block_time_iso": "string", - "index_block_hash": "string", - "parent_block_hash": "string", - "parent_index_block_hash": "string", - "burn_block_time": 0, - "burn_block_time_iso": "string", - "burn_block_hash": "string", - "burn_block_height": 0, - "miner_txid": "string", - "tx_count": 0, - "execution_cost_read_count": 0, - "execution_cost_read_length": 0, - "execution_cost_runtime": 0, - "execution_cost_write_count": 0, - "execution_cost_write_length": 0 - } - ] -} -``` - - - - - -```ts -/** - * GET request that returns blocks - */ -export interface NakamotoBlockListResponse { - /** - * The number of blocks to return - */ - limit: number; - /** - * The number to blocks to skip (starting at `0`) - */ - offset: number; - /** - * The number of blocks available - */ - total: number; - results: NakamotoBlock[]; -} -/** - * A block - */ -export interface NakamotoBlock { - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Height of the block - */ - height: number; - /** - * Hash representing the block - */ - hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * The only hash that can uniquely identify an anchored block or an unconfirmed state trie - */ - index_block_hash: string; - /** - * Hash of the parent block - */ - parent_block_hash: string; - /** - * Index block hash of the parent block - */ - parent_index_block_hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Hash of the anchor chain block - */ - burn_block_hash: string; - /** - * Height of the anchor chain block - */ - burn_block_height: number; - /** - * Anchor chain transaction ID - */ - miner_txid: string; - /** - * Number of transactions included in the block - */ - tx_count: number; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/blocks/index.mdx b/content/docs/stacks/api/blocks/index.mdx deleted file mode 100644 index 535232ea4..000000000 --- a/content/docs/stacks/api/blocks/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Blocks -index: true -toc: false -description: Handle the retrieval and management of block data using various identifiers. ---- \ No newline at end of file diff --git a/content/docs/stacks/api/blocks/meta.json b/content/docs/stacks/api/blocks/meta.json deleted file mode 100644 index c55c85c73..000000000 --- a/content/docs/stacks/api/blocks/meta.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "title": "Blocks", - "pages": [ - "get-block", - "get-blocks", - "get-blocks-by-burn-block", - "average-times", - "recent-blocks", - "block-by-hash", - "block-by-height", - "block-by-burn-block-hash", - "block-by-burn-block-height" - ], - "defaultOpen": false -} \ No newline at end of file diff --git a/content/docs/stacks/api/blocks/recent-blocks.mdx b/content/docs/stacks/api/blocks/recent-blocks.mdx deleted file mode 100644 index 0941b0f23..000000000 --- a/content/docs/stacks/api/blocks/recent-blocks.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: Get recent blocks -description: Retrieves a list of recently mined blocks. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get recent blocks - - -This endpoint is deprecated in favor of [Get blocks](/stacks/api/blocks/get-blocks). - - -Retrieves a list of recently mined blocks - -If you need to actively monitor new blocks, we highly recommend subscribing to [WebSockets or Socket.io](https://github.com/hirosystems/stacks-blockchain-api/tree/master/client) for real-time updates. - -### Query Parameters - - - -max number of blocks to fetch - -Default: `20` - -Maximum: `30` - - - - - -index of first block to fetch - -Example: `42000` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of blocks | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/block?limit=20&offset=42000" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/block?limit=20&offset=42000", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns blocks - - - - - -```json -{ - "limit": 30, - "offset": 0, - "total": 0, - "results": [ - { - "canonical": true, - "height": 0, - "hash": "string", - "block_time": 0, - "block_time_iso": "string", - "index_block_hash": "string", - "parent_block_hash": "string", - "burn_block_time": 0, - "burn_block_time_iso": "string", - "burn_block_hash": "string", - "burn_block_height": 0, - "miner_txid": "string", - "parent_microblock_hash": "string", - "parent_microblock_sequence": 0, - "txs": [ - "string" - ], - "microblocks_accepted": [ - "string" - ], - "microblocks_streamed": [ - "string" - ], - "execution_cost_read_count": 0, - "execution_cost_read_length": 0, - "execution_cost_runtime": 0, - "execution_cost_write_count": 0, - "execution_cost_write_length": 0, - "microblock_tx_count": { - "property1": 0, - "property2": 0 - } - } - ] -} -``` - - - - - -```ts -/** - * GET request that returns blocks - */ -export interface BlockListResponse { - /** - * The number of blocks to return - */ - limit: number; - /** - * The number to blocks to skip (starting at `0`) - */ - offset: number; - /** - * The number of blocks available - */ - total: number; - results: Block[]; -} -/** - * A block - */ -export interface Block { - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Height of the block - */ - height: number; - /** - * Hash representing the block - */ - hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * The only hash that can uniquely identify an anchored block or an unconfirmed state trie - */ - index_block_hash: string; - /** - * Hash of the parent block - */ - parent_block_hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Hash of the anchor chain block - */ - burn_block_hash: string; - /** - * Height of the anchor chain block - */ - burn_block_height: number; - /** - * Anchor chain transaction ID - */ - miner_txid: string; - /** - * The hash of the last streamed block that precedes this block to which this block is to be appended. Not every anchored block will have a parent microblock stream. An anchored block that does not have a parent microblock stream has the parent microblock hash set to an empty string, and the parent microblock sequence number set to -1. - */ - parent_microblock_hash: string; - /** - * The hash of the last streamed block that precedes this block to which this block is to be appended. Not every anchored block will have a parent microblock stream. An anchored block that does not have a parent microblock stream has the parent microblock hash set to an empty string, and the parent microblock sequence number set to -1. - */ - parent_microblock_sequence: number; - /** - * List of transactions included in the block - */ - txs: string[]; - /** - * List of microblocks that were accepted in this anchor block. Not every anchored block will have a accepted all (or any) of the previously streamed microblocks. Microblocks that were orphaned are not included in this list. - */ - microblocks_accepted: string[]; - /** - * List of microblocks that were streamed/produced by this anchor block's miner. This list only includes microblocks that were accepted in the following anchor block. Microblocks that were orphaned are not included in this list. - */ - microblocks_streamed: string[]; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - /** - * List of txs counts in each accepted microblock - */ - microblock_tx_count: { - [k: string]: number; - }; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/burn-blocks/get-burn-block.mdx b/content/docs/stacks/api/burn-blocks/get-burn-block.mdx deleted file mode 100644 index 015a02f03..000000000 --- a/content/docs/stacks/api/burn-blocks/get-burn-block.mdx +++ /dev/null @@ -1,150 +0,0 @@ ---- -title: Get burn block -description: Retrieves a single burn block. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get burn block - -Retrieves a single burn block -### Path Parameters - - - -filter by burn block height, hash, or the constant `latest` to filter for the most recent burn block - - - -| Status code | Description | -| :------ | :------ | -| `200` | Burn block | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v2/burn-blocks/42000" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/burn-blocks/42000", { - method: "GET" -}); -``` - - - - - - - - - -A burn block - - - - - -```json -{ - "burn_block_time": 0, - "burn_block_time_iso": "string", - "burn_block_hash": "string", - "burn_block_height": 0, - "stacks_blocks": [ - "string" - ], - "avg_block_time": 0, - "total_tx_count": 0 -} -``` - - - - - -```ts -/** - * A burn block - */ -export interface BurnBlock { - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Hash of the anchor chain block - */ - burn_block_hash: string; - /** - * Height of the anchor chain block - */ - burn_block_height: number; - /** - * Hashes of the Stacks blocks included in the burn block - */ - stacks_blocks: string[]; - /** - * Average time between blocks in seconds. Returns 0 if there is only one block in the burn block. - */ - avg_block_time: number; - /** - * Total number of transactions in the Stacks blocks associated with this burn block - */ - total_tx_count: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/burn-blocks/get-burn-blocks.mdx b/content/docs/stacks/api/burn-blocks/get-burn-blocks.mdx deleted file mode 100644 index 3865e7534..000000000 --- a/content/docs/stacks/api/burn-blocks/get-burn-blocks.mdx +++ /dev/null @@ -1,189 +0,0 @@ ---- -title: Get burn blocks -description: Retrieves a list of recent burn blocks. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get burn blocks - -Retrieves a list of recent burn blocks - - -### Query Parameters - - - -max number of burn blocks to fetch - -Default: `20` - -Maximum: `30` - - - - - -index of first burn block to fetch - -Example: `42000` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of burn blocks | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v2/burn-blocks?limit=20&offset=42000" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/burn-blocks?limit=20&offset=42000", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns burn blocks - - - - - -```json -{ - "limit": 30, - "offset": 0, - "total": 0, - "results": [ - { - "burn_block_time": 0, - "burn_block_time_iso": "string", - "burn_block_hash": "string", - "burn_block_height": 0, - "stacks_blocks": [ - "string" - ], - "avg_block_time": 0, - "total_tx_count": 0 - } - ] -} -``` - - - - - -```ts -/** - * GET request that returns burn blocks - */ -export interface BurnBlockListResponse { - /** - * The number of burn blocks to return - */ - limit: number; - /** - * The number to burn blocks to skip (starting at `0`) - */ - offset: number; - /** - * The number of burn blocks available (regardless of filter parameters) - */ - total: number; - results: BurnBlock[]; -} -/** - * A burn block - */ -export interface BurnBlock { - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Hash of the anchor chain block - */ - burn_block_hash: string; - /** - * Height of the anchor chain block - */ - burn_block_height: number; - /** - * Hashes of the Stacks blocks included in the burn block - */ - stacks_blocks: string[]; - /** - * Average time between blocks in seconds. Returns 0 if there is only one block in the burn block. - */ - avg_block_time: number; - /** - * Total number of transactions in the Stacks blocks associated with this burn block - */ - total_tx_count: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/burn-blocks/index.mdx b/content/docs/stacks/api/burn-blocks/index.mdx deleted file mode 100644 index 2e92e607b..000000000 --- a/content/docs/stacks/api/burn-blocks/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Burn blocks -index: true -toc: false -description: Retrieve information about specific burned blocks. ---- diff --git a/content/docs/stacks/api/client/accounts/get-assets.mdx b/content/docs/stacks/api/client/accounts/get-assets.mdx deleted file mode 100644 index 53453e14e..000000000 --- a/content/docs/stacks/api/client/accounts/get-assets.mdx +++ /dev/null @@ -1,234 +0,0 @@ ---- -title: Assets -description: Retrieves a list of all assets events associated with an account or a contract identifier. -toc: false ---- - -import { Root, API, APIExample } from '@/components/layout'; -import { Property } from 'fumadocs-openapi/ui' -import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; - -import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; -import { Badge } from '@/components/ui/badge'; - - - - - -
- -

`getAccountAssets`

- -This API endpoint retrieves a comprehensive list of asset events associated with a specific account or contract identifier, including asset transfers and mints. It is essential for tracking asset movements and changes in ownership within the Stacks blockchain. - -### Parameters - - -The account address or contract identifier whose asset events are to be retrieved. - - - -Optional overrides for the request initialization settings. - - -
- - - - - - - Retrieve Account Assets - - - - ```ts - import { Configuration, AccountsApi } from '@stacks/blockchain-api-client'; - - const apiConfig = new Configuration({ - basePath: 'https://api.testnet.hiro.so', - }); - - const accountsApi = new AccountsApi(apiConfig); - const principal = 'ST000000000000000000002AMW42H'; - // Retrieve all asset events for the specified account or contract identifier - const assets = await accountsApi.getAccountAssets({ - principal: principal, - }); - ``` - - - - - ```ts - import { - UserSession, - makeAuthRequest, - AppConfig - } from '@stacks/auth'; - - const appDomain = 'https://www.myapp.com'; - - const appConfig = new AppConfig(['store_write'], appDomain); - const userSession = new UserSession({ appConfig }); - - // The authentication payloads are encrypted during transit, the encryption key generated below provides this - const transitKey = userSession.generateAndStoreTransitKey(); - - // The Stacks auth process will open a compatible Stacks authenticator or browser extension to perform the authentication. So you will need to provide a redirect URL which the authenticator or extension can redirect to with the authentication payload. This page should process the authentication payload. - const redirectUri = 'https://www.myapp.com/auth'; - - // Set the location of your app manifest file. This file contains information about your app that is shown to the user during authentication. - const manifestUri = 'https://www.myapp.com/manifest.json'; - - // Generate the authentication request payload - const authRequest = userSession.makeAuthRequest( - transitKey, - redirectUri, - manifestUri - ); - - ``` - - - - - - - - -
- - - -
- -

`UserSession`

- -The Stacks authentication process enables secure user sign-in for web apps by generating and handling encrypted authentication requests. It involves setting up an app domain, configuring permissions, and creating a `UserSession` to manage user data. - -### Functions - - - -Determines if there is an incoming authentication response. - - - - - -Processes the response and provides a `userData` object containing the user's identity, BNS username and profile information. - - - - - -Checks if the user is already authenticated. - - - - - -Retrieves the user's profile data if the user is already authenticated. - - - - - -Encrypts user data for secure storage. - - - - - -Decrypts user data for secure storage. - - - -
- - - - - - Handle incoming authentication response - - - Check if a user is signed in - - - Load data for signed in user - - - Signing out a user - - - Encrypting user data - - - Decrypting user data - - - - ```ts - const isPending = userSession.isSignInPending(); - - if (isPending) { - userSession.handlePendingSignIn().then(userData => { - // Do something with userData - }); - } - ``` - - - ```ts - const isSignedIn = userSession.isUserSignedIn(); - ``` - - - ```ts - const isSignedIn = userSession.isUserSignedIn(); - - if (isSignedIn) { - // Do something with the signed in user - const userData = userSession.loadUserData(); - } - ``` - - - ```ts - function logout() { - userSession.signUserOut(); - } - ``` - - - ```ts - const message = 'My secret message'; - - const cipherText = await userSession.encryptContent(message); - ``` - - - ```ts - const message = 'My secret message'; - - const cipherText = await userSession.encryptContent(message); - const plainText = await userSession.decryptContent(cipherText); - ``` - - - - - - - Note that encryption here uses the user's private key associated with your app only. If you need to share this data with another app or other users, you should use the equivalent methods from `@stacks/encryption` and provide a custom private key. - - - - - - -
- -
diff --git a/content/docs/stacks/api/client/index.mdx b/content/docs/stacks/api/client/index.mdx deleted file mode 100644 index 2d8fc25c8..000000000 --- a/content/docs/stacks/api/client/index.mdx +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: Overview -description: Interact with the Stacks blockchain using a JavaScript client library. -toc: false ---- - -import { Accordion, Accordions } from "fumadocs-ui/components/accordion"; -import { Blocks, Braces, CircleUserRound } from 'lucide-react'; -import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; - -The `@stacks/blockchain-api-client` library provides a robust interface for interacting with the Stacks Blockchain API by offering type-safe methods to access REST and WebSocket endpoints. - -The client includes automatically generated HTTP API methods, comprehensive Schemas for Clarity smart contract values, and a WebSocket client for real-time data streaming. - -```ts -import { AccountsApi } from '@stacks/blockchain-api-client'; - -const accounts = new AccountsApi(apiConfig); - -await accounts.getAccountTransactions({ - principal: 'ST000000000000000000002AMW42H', -}); -``` - -### Using WebSockets - -```ts -import { connectWebSocketClient } from '@stacks/blockchain-api-client'; -const client = await connectWebSocketClient('ws://api.hiro.so/'); -const sub = await client.subscribeAddressTransactions(contractCall.txId, event => { - console.log(event); -}); - -await sub.unsubscribe(); -``` diff --git a/content/docs/stacks/api/faucets/index.mdx b/content/docs/stacks/api/faucets/index.mdx deleted file mode 100644 index e633c72b4..000000000 --- a/content/docs/stacks/api/faucets/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Faucets -index: true -toc: false -description: Distribute testnet tokens to specified addresses. ---- \ No newline at end of file diff --git a/content/docs/stacks/api/faucets/stx.mdx b/content/docs/stacks/api/faucets/stx.mdx deleted file mode 100644 index 8ea882f36..000000000 --- a/content/docs/stacks/api/faucets/stx.mdx +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: STX Testnet tokens -description: Delivers testnet STX tokens to a specified address. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get STX testnet tokens - -Add 500 STX tokens to the specified testnet address. Testnet STX addresses begin with `ST`. If the `stacking` -parameter is set to `true`, the faucet will add the required number of tokens for individual stacking to the -specified testnet address. - -The endpoint returns the transaction ID, which you can use to view the transaction in the -[Stacks Explorer](https://explorer.hiro.so/?chain=testnet). The tokens are delivered once the transaction has -been included in an anchor block. - -A common reason for failed faucet transactions is that the faucet has run out of tokens. If you are experiencing -failed faucet transactions to a testnet address, you can get help in [Discord](https://stacks.chat). - - -This is a testnet only endpoint. This endpoint will not work on the mainnet. - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | -| `500` | Faucet call failed | - - - - - - - - - - - - - -```terminal -$ curl -X POST "https://api.testnet.hiro.so/extended/v1/faucets/stx" -``` - - - - - -```js -fetch("https://api.testnet.hiro.so/extended/v1/faucets/stx", { - method: "POST" -}); -``` - - - - - - - - - -POST request that initiates a transfer of tokens to a specified testnet address - - - - - -```json -{ - "success": true, - "txId": "string", - "txRaw": "string" -} -``` - - - - - -```ts -/** - * POST request that initiates a transfer of tokens to a specified testnet address - */ -export interface RunFaucetResponse { - /** - * Indicates if the faucet call was successful - */ - success: boolean; - /** - * The transaction ID for the faucet call - */ - txId?: string; - /** - * Raw transaction in hex string representation - */ - txRaw?: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/fees/fee-rate.mdx b/content/docs/stacks/api/fees/fee-rate.mdx deleted file mode 100644 index 18adec385..000000000 --- a/content/docs/stacks/api/fees/fee-rate.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Get fee rate -description: Retrieves an estimated fee rate for transactions. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Fetch fee rate - - -This endpoint is deprecated in favor of [Get fee estimate](/stacks/api/fees/estimate). - - -Retrieves estimated fee rate. - -### Request Body - - - -A serialized transaction - - - -| Status code | Description | -| :------ | :------ | -| `200` | Transaction fee rate | - - - - - - - - - - - - - -```terminal -$ curl -X POST "https://api.hiro.so/extended/v1/fee_rate" \ - -d '{ - "transaction": "string" -}' -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/fee_rate", { - method: "POST" -}); -``` - - - - - - - - - -Get fee rate information. - - - - - -```json -{ - "fee_rate": 0 -} -``` - - - - - -```ts -/** - * Get fee rate information. - */ -export interface FeeRate { - fee_rate: number; -} -``` - - - - - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/api/fees/index.mdx b/content/docs/stacks/api/fees/index.mdx deleted file mode 100644 index 33c4d61fe..000000000 --- a/content/docs/stacks/api/fees/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Fees -index: true -toc: false -description: Provide estimates, rates, and approximate calculations for transaction costs. ---- \ No newline at end of file diff --git a/content/docs/stacks/api/fees/meta.json b/content/docs/stacks/api/fees/meta.json deleted file mode 100644 index a4e2fce8e..000000000 --- a/content/docs/stacks/api/fees/meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "title": "Fees", - "pages": ["..."], - "defaultOpen": false -} \ No newline at end of file diff --git a/content/docs/stacks/api/index.mdx b/content/docs/stacks/api/index.mdx deleted file mode 100644 index 7419a2333..000000000 --- a/content/docs/stacks/api/index.mdx +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Overview -description: Query the Stacks blockchain with the Stacks Blockchain API. ---- - -import { SecondaryCard } from '@/components/card'; - -The Stacks Blockchain API expands the intentionally minimal RPC endpoints available in Stacks nodes and indexes, cleans, and enriches on-chain data to put everything you need at your fingertips. Who knew getting reliable blockchain data could be this easy? - -## Popular endpoints - - -If you're looking for direct access to the Stacks node, including the ability to broadcast transactions and interact with smart contracts, check out our [Stacks Node RPC](/stacks/rpc-api) documentation. - - - - - - - - -## Related tools - -- **[Stacks Node RPC](/stacks/rpc-api)**: Fetch data and broadcast transactions from the Stacks Node RPC API. -- **[Token Metadata API](/stacks/token-metadata-api)**: Fetch fungible and non-fungible token data on the Stacks blockchain. -- **[Stacks Explorer](https://explorer.hiro.so)**: Looking for a front end to verify activity on the Stacks blockchain? Try the Stacks Explorer. - -
- - -Reach out to us on the #api channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET. - - - diff --git a/content/docs/stacks/api/info/circulating-stx-supply-in-plain-text.mdx b/content/docs/stacks/api/info/circulating-stx-supply-in-plain-text.mdx deleted file mode 100644 index fee827a27..000000000 --- a/content/docs/stacks/api/info/circulating-stx-supply-in-plain-text.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Get circulating STX supply in plain text format -description: Retrieves the circulating STX supply as plain text. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get circulating STX supply in plain text format - -Retrieves the STX tokens currently in circulation that have been unlocked as plain text. - -| Status code | Description | -| :------ | :------ | -| `200` | success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/stx_supply/circulating/plain" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/stx_supply/circulating/plain", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns network target block times - - - - - -```json -"string" -``` - - - - - -```ts -/** - * GET request that returns network target block times - */ -export type GetStxCirculatingSupplyPlainResponse = string; -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/info/index.mdx b/content/docs/stacks/api/info/index.mdx deleted file mode 100644 index 4106173a5..000000000 --- a/content/docs/stacks/api/info/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Info -index: true -toc: false -description: Retrieves information about the Core API and the Stacks network. ---- diff --git a/content/docs/stacks/api/info/legacy-total-and-unlocked-stx-supply.mdx b/content/docs/stacks/api/info/legacy-total-and-unlocked-stx-supply.mdx deleted file mode 100644 index 223228c4e..000000000 --- a/content/docs/stacks/api/info/legacy-total-and-unlocked-stx-supply.mdx +++ /dev/null @@ -1,150 +0,0 @@ ---- -title: Get total and unlocked STX supply (legacy) -description: Retrieves the total and unlocked STX supply in legacy format 1.0 API. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get total and unlocked STX supply (results formatted the same as the legacy 1.0 API) - -Retrieves total supply of STX tokens including those currently in circulation that have been unlocked. - - -This uses the estimated future total supply for the year 2050. - - -### Query Parameters - - - -Supply details are queried from specified block height. If the block height is not specified, the latest block height is taken as default value. - -Example: `200` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/stx_supply/legacy_format?height=200" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/stx_supply/legacy_format?height=200", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns network target block times - - - - - -```json -{ - "unlockedPercent": "string", - "totalStacks": "string", - "totalStacksFormatted": "string", - "unlockedSupply": "string", - "unlockedSupplyFormatted": "string", - "blockHeight": "string" -} -``` - - - - - -```ts -/** - * GET request that returns network target block times - */ -export interface GetStxSupplyLegacyFormatResponse { - /** - * String quoted decimal number of the percentage of STX that have unlocked - */ - unlockedPercent: string; - /** - * String quoted decimal number of the total possible number of STX - */ - totalStacks: string; - /** - * Same as `totalStacks` but formatted with comma thousands separators - */ - totalStacksFormatted: string; - /** - * String quoted decimal number of the STX that have been mined or unlocked - */ - unlockedSupply: string; - /** - * Same as `unlockedSupply` but formatted with comma thousands separators - */ - unlockedSupplyFormatted: string; - /** - * The block height at which this information was queried - */ - blockHeight: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/info/network-block-time.mdx b/content/docs/stacks/api/info/network-block-time.mdx deleted file mode 100644 index 4a37c5c0f..000000000 --- a/content/docs/stacks/api/info/network-block-time.mdx +++ /dev/null @@ -1,117 +0,0 @@ ---- -title: Get the network target block time -description: Retrieves the target block times for mainnet and testnet. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get the network target block time - -Retrieves the target block times for mainnet and testnet. The block time is hardcoded and will change throughout the implementation phases of the testnet. - -| Status code | Description | -| :------ | :------ | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/info/network_block_times" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/info/network_block_times", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns network target block times - - - - - -```json -{ - "mainnet": { - "target_block_time": 0 - }, - "testnet": { - "target_block_time": 0 - } -} -``` - - - - - -```ts -/** - * GET request that returns network target block times - */ -export interface NetworkBlockTimesResponse { - mainnet: TargetBlockTime; - testnet: TargetBlockTime; -} -export interface TargetBlockTime { - target_block_time: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/info/network-given-block-time.mdx b/content/docs/stacks/api/info/network-given-block-time.mdx deleted file mode 100644 index 297578c02..000000000 --- a/content/docs/stacks/api/info/network-given-block-time.mdx +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: Get a given network's target block time -description: Retrieves the target block time for a given network. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get a given network's target block time - -Retrieves the target block time for a given network. The network can be mainnet or testnet. The block time is hardcoded and will change throughout the implementation phases of the testnet. -### Path Parameters - - - -the target block time for a given network (testnet, mainnet). - -Example: `"mainnet"` - -Value in: `"testnet" | "mainnet"` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/info/network_block_time/mainnet" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/info/network_block_time/mainnet", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "target_block_time": 0 -} -``` - - - - - -```ts -export interface TargetBlockTime { - target_block_time: number; -} -``` - - - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/info/status.mdx b/content/docs/stacks/api/info/status.mdx deleted file mode 100644 index 2cdb7e737..000000000 --- a/content/docs/stacks/api/info/status.mdx +++ /dev/null @@ -1,160 +0,0 @@ ---- -title: Get API status -description: Retrieves the running status of the Stacks Blockchain API. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## API status - -Retrieves the running status of the Stacks Blockchain API, including the server version and current chain tip information. - -| Status code | Description | -| :------ | :------ | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended" -``` - - - - - -```js -fetch("https://api.hiro.so/extended", { - method: "GET" -}); -``` - - - - - - - - - -GET blockchain API status - - - - - -```json -{ - "server_version": "string", - "status": "string", - "pox_v1_unlock_height": 0, - "pox_v2_unlock_height": 0, - "pox_v3_unlock_height": 0, - "chain_tip": { - "block_height": 0, - "block_hash": "string", - "index_block_hash": "string", - "microblock_hash": "string", - "microblock_sequence": 0, - "burn_block_height": 0 - } -} -``` - - - - - -```ts -/** - * GET blockchain API status - */ -export interface ServerStatusResponse { - /** - * the server version that is currently running - */ - server_version?: string; - /** - * the current server status - */ - status: string; - pox_v1_unlock_height?: number; - pox_v2_unlock_height?: number; - pox_v3_unlock_height?: number; - chain_tip?: ChainTip; -} -/** - * Current chain tip information - */ -export interface ChainTip { - /** - * the current block height - */ - block_height: number; - /** - * the current block hash - */ - block_hash: string; - /** - * the current index block hash - */ - index_block_hash: string; - /** - * the current microblock hash - */ - microblock_hash?: string; - /** - * the current microblock sequence number - */ - microblock_sequence?: number; - /** - * the current burn chain block height - */ - burn_block_height: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/info/total-and-unlocked-stx-supply.mdx b/content/docs/stacks/api/info/total-and-unlocked-stx-supply.mdx deleted file mode 100644 index f2ad807e8..000000000 --- a/content/docs/stacks/api/info/total-and-unlocked-stx-supply.mdx +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: Get total and unlocked STX supply -description: Retrieves the total and unlocked STX supply. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get total and unlocked STX supply - -Retrieves the total and unlocked STX supply. - -### Query Parameters - - - -Supply details are queried from specified block height. If the block height is not specified, the latest block height is taken as default value. Note that the `block height` is referred to the stacks blockchain. - -Minimum: `0` - - - -| Status code | Description | -| :----------- | :----------- | -| `200` | GET request that returns total and unlocked STX supply | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/stx_supply" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/stx_supply", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns network target block times - - - - - -```json -{ - "unlocked_percent": "string", - "total_stx": "string", - "total_stx_year_2050": "string", - "unlocked_stx": "string", - "block_height": 0 -} -``` - - - - - -```ts -/** - * GET request that returns network target block times - */ -export interface GetStxSupplyResponse { - /** - * String quoted decimal number of the percentage of STX that have unlocked - */ - unlocked_percent: string; - /** - * String quoted decimal number of the total circulating number of STX (at the input block height if provided, otherwise the current block height) - */ - total_stx: string; - /** - * String quoted decimal number of total circulating STX supply in year 2050. STX supply grows approx 0.3% annually thereafter in perpetuity. - */ - total_stx_year_2050: string; - /** - * String quoted decimal number of the STX that have been mined or unlocked - */ - unlocked_stx: string; - /** - * The block height at which this information was queried - */ - block_height: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/info/total-stx-supply-in-plain-text.mdx b/content/docs/stacks/api/info/total-stx-supply-in-plain-text.mdx deleted file mode 100644 index c43e3f576..000000000 --- a/content/docs/stacks/api/info/total-stx-supply-in-plain-text.mdx +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: Get total STX supply in plain text format -description: Retrieves the total STX supply as plain text. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get total STX supply in plain text format - -Retrieves the total supply for STX tokens as plain text. - - -This uses the estimated future total supply for the year 2050. - - -| Status code | Description | -| :------ | :------ | -| `200` | success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/stx_supply/total/plain" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/stx_supply/total/plain", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns network target block times - - - - - -```json -"string" -``` - - - - - -```ts -/** - * GET request that returns network target block times - */ -export type GetStxTotalSupplyPlainResponse = string; -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/mempool/index.mdx b/content/docs/stacks/api/mempool/index.mdx deleted file mode 100644 index a0c83717c..000000000 --- a/content/docs/stacks/api/mempool/index.mdx +++ /dev/null @@ -1,5 +0,0 @@ ---- -title: Mempool -index: true -toc: false -description: Retrieve information around transaction fees and priorities in the mempool. diff --git a/content/docs/stacks/api/mempool/transaction-fee-priorities.mdx b/content/docs/stacks/api/mempool/transaction-fee-priorities.mdx deleted file mode 100644 index 1e04567b8..000000000 --- a/content/docs/stacks/api/mempool/transaction-fee-priorities.mdx +++ /dev/null @@ -1,155 +0,0 @@ ---- -title: Get transaction fee priorities -description: Retrieves estimated fee priorities (in micro-STX) for all transactions that are currently in the mempool. Also returns priorities separated by transaction type. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get mempool transaction fee priorities - -Returns estimated fee priorities (in micro-STX) for all transactions that are currently in the mempool. Also returns priorities separated by transaction type. - - -| Status code | Description | -| :------ | :------ | -| `200` | Mempool fee priorities | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v2/mempool/fees" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/mempool/fees", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns fee priorities from mempool transactions - - - - - -```json -{ - "all": { - "no_priority": 0, - "low_priority": 0, - "medium_priority": 0, - "high_priority": 0 - }, - "token_transfer": { - "no_priority": 0, - "low_priority": 0, - "medium_priority": 0, - "high_priority": 0 - }, - "smart_contract": { - "no_priority": 0, - "low_priority": 0, - "medium_priority": 0, - "high_priority": 0 - }, - "contract_call": { - "no_priority": 0, - "low_priority": 0, - "medium_priority": 0, - "high_priority": 0 - } -} -``` - - - - - -```ts -/** - * GET request that returns fee priorities from mempool transactions - */ -export interface MempoolFeePriorities { - all: { - no_priority: number; - low_priority: number; - medium_priority: number; - high_priority: number; - }; - token_transfer?: { - no_priority: number; - low_priority: number; - medium_priority: number; - high_priority: number; - }; - smart_contract?: { - no_priority: number; - low_priority: number; - medium_priority: number; - high_priority: number; - }; - contract_call?: { - no_priority: number; - low_priority: number; - medium_priority: number; - high_priority: number; - }; -} -``` - - - - - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/api/meta.json b/content/docs/stacks/api/meta.json deleted file mode 100644 index 402e9e0d4..000000000 --- a/content/docs/stacks/api/meta.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "title": "Stacks API", - "root": true, - "pages": [ - "---Stacks Blockchain API---", - "index", - "usage", - "architecture", - "txs", - "---Concepts---", - "concepts/pagination", - "concepts/requesting-proofs", - "concepts/nonce-handling", - "---API Reference---", - "accounts", - "transactions", - "fees", - "faucets", - "blocks", - "burn-blocks", - "mempool", - "smart-contracts", - "proof-of-transfer", - "names", - "tokens", - "non-fungible-tokens", - "stacking-pool", - "stacking-rewards", - "search", - "info" - ] -} diff --git a/content/docs/stacks/api/microblocks/index.mdx b/content/docs/stacks/api/microblocks/index.mdx deleted file mode 100644 index 0a8e4894b..000000000 --- a/content/docs/stacks/api/microblocks/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Microblocks -index: true -toc: false -description: Retrieve and manage recent microblocks and their associated transactions. ---- \ No newline at end of file diff --git a/content/docs/stacks/api/microblocks/meta.json b/content/docs/stacks/api/microblocks/meta.json deleted file mode 100644 index 3be5388b9..000000000 --- a/content/docs/stacks/api/microblocks/meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "title": "Microblocks", - "pages": ["..."], - "defaultOpen": false -} \ No newline at end of file diff --git a/content/docs/stacks/api/names/historical-zonefile.mdx b/content/docs/stacks/api/names/historical-zonefile.mdx deleted file mode 100644 index f2e5f812b..000000000 --- a/content/docs/stacks/api/names/historical-zonefile.mdx +++ /dev/null @@ -1,197 +0,0 @@ ---- -title: Get historical zone file -description: Retrieves the historical zone file for a specific name. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get historical zone file - -Retrieves the historical zonefile specified by the username and zone hash. -### Path Parameters - - - -fully-qualified name - -Example: `"muneeb.id"` - - - - - -zone file hash - -Example: `"b100a68235244b012854a95f9114695679002af9"` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | -| `400` | Error | -| `404` | Error | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/v1/names/muneeb.id/zonefile/b100a68235244b012854a95f9114695679002af9" -``` - - - - - -```js -fetch("https://api.hiro.so/v1/names/muneeb.id/zonefile/b100a68235244b012854a95f9114695679002af9", { - method: "GET" -}); -``` - - - - - - - - - -Fetches the historical zonefile specified by the username and zone hash. - - - - - -```json -{ - "zonefile": "string" -} -``` - - - - - -```ts -/** - * Fetches the historical zonefile specified by the username and zone hash. - */ -export type BnsFetchHistoricalZoneFileResponse = - | { - zonefile?: string; - } - | { - error?: string; - }; -``` - - - - - - - - - -Error - - - - - -```json -{ - "error": "string" -} -``` - - - - - -```ts -/** - * Error - */ -export interface BnsError { - error?: string; -} -``` - - - - - - - - - -Error - - - - - -```json -{ - "error": "string" -} -``` - - - - - -```ts -/** - * Error - */ -export interface BnsError { - error?: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/names/index.mdx b/content/docs/stacks/api/names/index.mdx deleted file mode 100644 index b1e2ce35f..000000000 --- a/content/docs/stacks/api/names/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Names -index: true -toc: false -description: Manages and retrieve information on blockchain namespaces, names, and related details. ---- \ No newline at end of file diff --git a/content/docs/stacks/api/names/name-details.mdx b/content/docs/stacks/api/names/name-details.mdx deleted file mode 100644 index 456a2805c..000000000 --- a/content/docs/stacks/api/names/name-details.mdx +++ /dev/null @@ -1,201 +0,0 @@ ---- -title: Get name details -description: Retrieves details of a given name including the address, status and last transaction ID. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get name details - -Retrieves details of a given name including the `address`, `status` and last transaction id - `last_txid`. -### Path Parameters - - - -fully-qualified name - -Example: `"muneeb.id"` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | -| `400` | Error | -| `404` | Error | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/v1/names/muneeb.id" -``` - - - - - -```js -fetch("https://api.hiro.so/v1/names/muneeb.id", { - method: "GET" -}); -``` - - - - - - - - - -Get name details - - - - - -```json -{ - "address": "string", - "blockchain": "string", - "expire_block": 0, - "grace_period": 0, - "last_txid": "string", - "resolver": "string", - "status": "string", - "zonefile": "string", - "zonefile_hash": "string" -} -``` - - - - - -```ts -/** - * Get name details - */ -export interface BnsGetNameInfoResponse { - address: string; - blockchain: string; - expire_block?: number; - grace_period?: number; - last_txid: string; - resolver?: string; - status: string; - zonefile: string; - zonefile_hash: string; -} -``` - - - - - - - - - -Error - - - - - -```json -{ - "error": "string" -} -``` - - - - - -```ts -/** - * Error - */ -export interface BnsError { - error?: string; -} -``` - - - - - - - - - -Error - - - - - -```json -{ - "error": "string" -} -``` - - - - - -```ts -/** - * Error - */ -export interface BnsError { - error?: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/names/name-subdomains.mdx b/content/docs/stacks/api/names/name-subdomains.mdx deleted file mode 100644 index ee76f0ad5..000000000 --- a/content/docs/stacks/api/names/name-subdomains.mdx +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: Get name subdomains -description: Retrieves the list of subdomains for a specific name. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get name subdomains - -Retrieves the list of subdomains for a specific name -### Path Parameters - - - -fully-qualified name - -Example: `"id.blockstack"` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/v1/names/id.blockstack/subdomains" -``` - - - - - -```js -fetch("https://api.hiro.so/v1/names/id.blockstack/subdomains", { - method: "GET" -}); -``` - - - - - - - - - -Fetch a list of subdomains in a name. - - - - - -```json -[ - "string" -] -``` - - - - - -```ts -/** - * Fetch a list of subdomains in a name. - */ -export type GetAllSubdomainsInName = string[]; -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/names/name-zonefile.mdx b/content/docs/stacks/api/names/name-zonefile.mdx deleted file mode 100644 index d365f796b..000000000 --- a/content/docs/stacks/api/names/name-zonefile.mdx +++ /dev/null @@ -1,189 +0,0 @@ ---- -title: Get name zone file -description: Retrieves the zone file for a specific name. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get name zone file - -Retrieves a user’s raw zone file. This only works for RFC-compliant zone files. This method returns an error for names that have non-standard zone files. -### Path Parameters - - - -fully-qualified name - -Example: `"bar.test"` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | -| `400` | Error | -| `404` | Error | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/v1/names/bar.test/zonefile" -``` - - - - - -```js -fetch("https://api.hiro.so/v1/names/bar.test/zonefile", { - method: "GET" -}); -``` - - - - - - - - - -Fetch a user's raw zone file. This only works for RFC-compliant zone files. This method returns an error for names that have non-standard zone files. - - - - - -```json -{ - "zonefile": "string" -} -``` - - - - - -```ts -/** - * Fetch a user's raw zone file. This only works for RFC-compliant zone files. This method returns an error for names that have non-standard zone files. - */ -export type BnsFetchFileZoneResponse = - | { - zonefile?: string; - } - | { - error?: string; - }; -``` - - - - - - - - - -Error - - - - - -```json -{ - "error": "string" -} -``` - - - - - -```ts -/** - * Error - */ -export interface BnsError { - error?: string; -} -``` - - - - - - - - - -Error - - - - - -```json -{ - "error": "string" -} -``` - - - - - -```ts -/** - * Error - */ -export interface BnsError { - error?: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/names/names.mdx b/content/docs/stacks/api/names/names.mdx deleted file mode 100644 index 29e4e3cd3..000000000 --- a/content/docs/stacks/api/names/names.mdx +++ /dev/null @@ -1,150 +0,0 @@ ---- -title: Get all names -description: Retrieves a list of all names known to the node. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get all names - -Retrieves a list of all names known to the node. - -### Query Parameters - - - -names are defaulted to page 1 with 100 results. You can query specific page results by using the 'page' query parameter. - -Example: `22` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | -| `400` | Error | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/v1/names?page=22" -``` - - - - - -```js -fetch("https://api.hiro.so/v1/names?page=22", { - method: "GET" -}); -``` - - - - - - - - - -Fetch a list of all names known to the node. - - - - - -```json -[ - "string" -] -``` - - - - - -```ts -/** - * Fetch a list of all names known to the node. - */ -export type BnsGetAllNamesResponse = string[]; -``` - - - - - - - - - -Error - - - - - -```json -{ - "error": "string" -} -``` - - - - - -```ts -/** - * Error - */ -export interface BnsError { - error?: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/names/namespace-names.mdx b/content/docs/stacks/api/names/namespace-names.mdx deleted file mode 100644 index d089c684b..000000000 --- a/content/docs/stacks/api/names/namespace-names.mdx +++ /dev/null @@ -1,193 +0,0 @@ ---- -title: Get namespace names -description: Retrieves a list of names within a given namespace. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get namespace names - -Retrieves a list of names within a given namespace. -### Path Parameters - - - -the namespace to fetch names from. - -Example: `"id"` - - - -### Query Parameters - - - -namespace values are defaulted to page 1 with 100 results. You can query specific page results by using the 'page' query parameter. - -Example: `22` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | -| `400` | Error | -| `404` | Error | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/v1/namespaces/id/names?page=22" -``` - - - - - -```js -fetch("https://api.hiro.so/v1/namespaces/id/names?page=22", { - method: "GET" -}); -``` - - - - - - - - - -Fetch a list of names from the namespace. - - - - - -```json -[ - "string" -] -``` - - - - - -```ts -/** - * Fetch a list of names from the namespace. - */ -export type BnsGetAllNamespacesNamesResponse = string[]; -``` - - - - - - - - - -Error - - - - - -```json -{ - "error": "string" -} -``` - - - - - -```ts -/** - * Error - */ -export interface BnsError { - error?: string; -} -``` - - - - - - - - - -Error - - - - - -```json -{ - "error": "string" -} -``` - - - - - -```ts -/** - * Error - */ -export interface BnsError { - error?: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/names/namespaces.mdx b/content/docs/stacks/api/names/namespaces.mdx deleted file mode 100644 index ca9fe2bfa..000000000 --- a/content/docs/stacks/api/names/namespaces.mdx +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Get all namespaces -description: Retrieves a list of all namespaces known to the node. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get all namespaces - -Retrieves a list of all namespaces known to the node. - -| Status code | Description | -| :------ | :------ | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/v1/namespaces" -``` - - - - - -```js -fetch("https://api.hiro.so/v1/namespaces", { - method: "GET" -}); -``` - - - - - - - - - -Fetch a list of all namespaces known to the node. - - - - - -```json -{ - "namespaces": [ - "string" - ] -} -``` - - - - - -```ts -/** - * Fetch a list of all namespaces known to the node. - */ -export interface BnsGetAllNamespacesResponse { - namespaces: string[]; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/names/owned-by-address.mdx b/content/docs/stacks/api/names/owned-by-address.mdx deleted file mode 100644 index 09610a239..000000000 --- a/content/docs/stacks/api/names/owned-by-address.mdx +++ /dev/null @@ -1,161 +0,0 @@ ---- -title: Get names owned by address -description: Retrieves the list of names owned by a specific address. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get names owned by address - -Retrieves a list of names owned by the address provided. -### Path Parameters - - - -the layer-1 blockchain for the address - -Example: `"bitcoin"` - - - - - -the address to lookup - -Example: `"1QJQxDas5JhdiXhEbNS14iNjr8auFT96GP"` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | -| `404` | Error | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/v1/addresses/bitcoin/1QJQxDas5JhdiXhEbNS14iNjr8auFT96GP" -``` - - - - - -```js -fetch("https://api.hiro.so/v1/addresses/bitcoin/1QJQxDas5JhdiXhEbNS14iNjr8auFT96GP", { - method: "GET" -}); -``` - - - - - - - - - -Retrieves a list of names owned by the address provided. - - - - - -```json -{ - "names": [ - "string" - ] -} -``` - - - - - -```ts -/** - * Retrieves a list of names owned by the address provided. - */ -export interface BnsNamesOwnByAddressResponse { - names: string[]; -} -``` - - - - - - - - - -Error - - - - - -```json -{ - "error": "string" -} -``` - - - - - -```ts -/** - * Error - */ -export interface BnsError { - error?: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/non-fungible-tokens/history.mdx b/content/docs/stacks/api/non-fungible-tokens/history.mdx deleted file mode 100644 index 4f1c5fdd8..000000000 --- a/content/docs/stacks/api/non-fungible-tokens/history.mdx +++ /dev/null @@ -1,688 +0,0 @@ ---- -title: Get non-fungible token history -description: Retrieves the history of a non-fungible token. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Non-Fungible Token history - -Retrieves all events relevant to a Non-Fungible Token. Useful to determine the ownership history of a particular asset. - -More information on Non-Fungible Tokens on the Stacks blockchain can be found [here](https://docs.stacks.co/write-smart-contracts/tokens#non-fungible-tokens-nfts). - -### Query Parameters - - - -token asset class identifier - -Example: `"SP2X0TZ59D5SZ8ACQ6YMCHHNR2ZN51Z32E2CJ173.the-explorer-guild::The-Explorer-Guild"` - - - - - -hex representation of the token's unique value - -Example: `"0x0100000000000000000000000000000803"` - - - - - -max number of events to fetch - -Default: `50` - - - - - -index of first event to fetch - -Example: `42000` - -Default: `0` - - - - - -whether or not to include events from unconfirmed transactions - -Example: `true` - -Default: `false` - - - - - -whether or not to include the complete transaction metadata instead of just `tx_id`. Enabling this option can affect performance and response times. - -Default: `false` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Non-Fungible Token event history | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/tokens/nft/history?asset_identifier=SP2X0TZ59D5SZ8ACQ6YMCHHNR2ZN51Z32E2CJ173.the-explorer-guild%3A%3AThe-Explorer-Guild&value=0x0100000000000000000000000000000803&limit=50&offset=42000&unanchored=true&tx_metadata=false" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/tokens/nft/history?asset_identifier=SP2X0TZ59D5SZ8ACQ6YMCHHNR2ZN51Z32E2CJ173.the-explorer-guild%3A%3AThe-Explorer-Guild&value=0x0100000000000000000000000000000803&limit=50&offset=42000&unanchored=true&tx_metadata=false", { - method: "GET" -}); -``` - - - - - - - - - -List of Non-Fungible Token history events - - - - - -```json -{ - "limit": 200, - "offset": 0, - "total": 0, - "results": [ - { - "sender": "string", - "recipient": "string", - "event_index": 0, - "asset_event_type": "string", - "tx_id": "string" - } - ] -} -``` - - - - - -```ts -/** - * Describes an event from the history of a Non-Fungible Token - */ -export type NonFungibleTokenHistoryEvent = - | NonFungibleTokenHistoryEventWithTxId - | NonFungibleTokenHistoryEventWithTxMetadata; -/** - * Describes all transaction types on Stacks 2.0 blockchain - */ -export type Transaction = - | TokenTransferTransaction - | SmartContractTransaction - | ContractCallTransaction - | PoisonMicroblockTransaction - | CoinbaseTransaction - | TenureChangeTransaction; -/** - * Describes representation of a Type-0 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-0-transferring-an-asset - */ -export type TokenTransferTransaction = AbstractTransaction & TokenTransferTransactionMetadata; -/** - * Anchored transaction metadata. All mined/anchored Stacks transactions have these properties. - */ -export type AbstractTransaction = BaseTransaction & { - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - tx_status: TransactionStatus; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - /** - * List of transaction events - */ - events: TransactionEvent[]; -}; -export type PostConditionMode = "allow" | "deny"; -/** - * Post-conditionscan limit the damage done to a user's assets - */ -export type PostCondition = PostConditionStx | PostConditionFungible | PostConditionNonFungible; -export type PostConditionStx = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - amount: string; - type: "stx"; -}; -export type PostConditionPrincipal = - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_origin"; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_standard"; - address: string; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_contract"; - address: string; - contract_name: string; - }; -/** - * A fungible condition code encodes a statement being made for either STX or a fungible token, with respect to the originating account. - */ -export type PostConditionFungibleConditionCode = - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; -export type PostConditionFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - type: "fungible"; - amount: string; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -export type PostConditionNonFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionNonFungibleConditionCode; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -/** - * A non-fungible condition code encodes a statement being made about a non-fungible token, with respect to whether or not the particular non-fungible token is owned by the account. - */ -export type PostConditionNonFungibleConditionCode = "sent" | "not_sent"; -/** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ -export type TransactionAnchorModeType = "on_chain_only" | "off_chain_only" | "any"; -/** - * Status of the transaction - */ -export type TransactionStatus = "success" | "abort_by_response" | "abort_by_post_condition"; -export type TransactionEvent = - | TransactionEventSmartContractLog - | TransactionEventStxLock - | TransactionEventStxAsset - | TransactionEventFungibleAsset - | TransactionEventNonFungibleAsset; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventSmartContractLog = AbstractTransactionEvent & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxLock = AbstractTransactionEvent & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxAsset = AbstractTransactionEvent & { - event_type: "stx_asset"; - tx_id: string; - asset: TransactionEventAsset; -}; -export type TransactionEventAssetType = "transfer" | "mint" | "burn"; -export type TransactionEventFungibleAsset = AbstractTransactionEvent & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type TransactionEventNonFungibleAsset = AbstractTransactionEvent & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Describes representation of a Type-1 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export type SmartContractTransaction = AbstractTransaction & SmartContractTransactionMetadata; -/** - * Describes representation of a Type 2 Stacks 2.0 transaction: Contract Call - */ -export type ContractCallTransaction = AbstractTransaction & ContractCallTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type PoisonMicroblockTransaction = AbstractTransaction & PoisonMicroblockTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type CoinbaseTransaction = AbstractTransaction & CoinbaseTransactionMetadata; -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export type TenureChangeTransaction = AbstractTransaction & TenureChangeTransactionMetadata; - -/** - * List of Non-Fungible Token history events - */ -export interface NonFungibleTokenHistoryEventList { - /** - * The number of events to return - */ - limit: number; - /** - * The number to events to skip (starting at `0`) - */ - offset: number; - /** - * The number of events available - */ - total: number; - results: NonFungibleTokenHistoryEvent[]; -} -/** - * Non-Fungible Token history event with transaction id - */ -export interface NonFungibleTokenHistoryEventWithTxId { - sender?: string; - recipient?: string; - event_index: number; - asset_event_type: string; - tx_id: string; -} -/** - * Non-Fungible Token history event with transaction metadata - */ -export interface NonFungibleTokenHistoryEventWithTxMetadata { - sender?: string; - recipient?: string; - event_index: number; - asset_event_type: string; - tx: Transaction; -} -/** - * Transaction properties that are available from a raw serialized transactions. These are available for transactions in the mempool as well as mined transactions. - */ -export interface BaseTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: PostConditionMode; - post_conditions: PostCondition[]; - anchor_mode: TransactionAnchorModeType; -} -export interface AbstractTransactionEvent { - event_index: number; -} -export interface TransactionEventAsset { - asset_event_type?: TransactionEventAssetType; - asset_id?: string; - sender?: string; - recipient?: string; - amount?: string; - value?: string; - memo?: string; -} -/** - * Metadata associated with token-transfer type transactions - */ -export interface TokenTransferTransactionMetadata { - tx_type: "token_transfer"; - token_transfer: { - recipient_address: string; - /** - * Transfer amount as Integer string (64-bit unsigned integer) - */ - amount: string; - /** - * Hex encoded arbitrary message, up to 34 bytes length (should try decoding to an ASCII string) - */ - memo: string; - }; -} -/** - * Metadata associated with a contract-deploy type transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export interface SmartContractTransactionMetadata { - tx_type: "smart_contract"; - smart_contract: { - /** - * The Clarity version of the contract, only specified for versioned contract transactions, otherwise null - */ - clarity_version?: number; - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Clarity code of the smart contract being deployed - */ - source_code: string; - }; -} -/** - * Metadata associated with a contract-call type transaction - */ -export interface ContractCallTransactionMetadata { - tx_type: "contract_call"; - contract_call: { - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Name of the Clarity function to be invoked - */ - function_name: string; - /** - * Function definition, including function name and type as well as parameter names and types - */ - function_signature: string; - /** - * List of arguments used to invoke the function - */ - function_args?: { - hex: string; - repr: string; - name: string; - type: string; - }[]; - }; -} -/** - * Metadata associated with a poison-microblock type transaction - */ -export interface PoisonMicroblockTransactionMetadata { - tx_type: "poison_microblock"; - poison_microblock: { - /** - * Hex encoded microblock header - */ - microblock_header_1: string; - /** - * Hex encoded microblock header - */ - microblock_header_2: string; - }; -} -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export interface CoinbaseTransactionMetadata { - tx_type: "coinbase"; - coinbase_payload: { - /** - * Hex encoded 32-byte scratch space for block leader's use - */ - data: string; - /** - * A principal that will receive the miner rewards for this coinbase transaction. Can be either a standard principal or contract principal. Only specified for `coinbase-to-alt-recipient` transaction types, otherwise null. - */ - alt_recipient?: string; - /** - * Hex encoded 80-byte VRF proof - */ - vrf_proof?: string; - }; -} -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export interface TenureChangeTransactionMetadata { - tx_type: "tenure_change"; - tenure_change_payload?: { - /** - * Consensus hash of this tenure. Corresponds to the sortition in which the miner of this block was chosen. - */ - tenure_consensus_hash: string; - /** - * Consensus hash of the previous tenure. Corresponds to the sortition of the previous winning block-commit. - */ - prev_tenure_consensus_hash: string; - /** - * Current consensus hash on the underlying burnchain. Corresponds to the last-seen sortition. - */ - burn_view_consensus_hash: string; - /** - * (Hex string) Stacks Block hash - */ - previous_tenure_end: string; - /** - * The number of blocks produced in the previous tenure. - */ - previous_tenure_blocks: number; - /** - * Cause of change in mining tenure. Depending on cause, tenure can be ended or extended. - */ - cause: "block_found" | "extended"; - /** - * (Hex string) The ECDSA public key hash of the current tenure. - */ - pubkey_hash: string; - }; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/non-fungible-tokens/holdings.mdx b/content/docs/stacks/api/non-fungible-tokens/holdings.mdx deleted file mode 100644 index 0fe127495..000000000 --- a/content/docs/stacks/api/non-fungible-tokens/holdings.mdx +++ /dev/null @@ -1,711 +0,0 @@ ---- -title: Get non-fungible token holdings -description: Retrieves a list of non-fungible tokens owned by the given principal (STX address or smart contract ID). -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Non-Fungible Token holdings - -Retrieves the list of Non-Fungible Tokens owned by the given principal (STX address or Smart Contract ID). -Results can be filtered by one or more asset identifiers and can include metadata about the transaction that made the principal own each token. - -More information on Non-Fungible Tokens on the Stacks blockchain can be found [here](https://docs.stacks.co/write-smart-contracts/tokens#non-fungible-tokens-nfts). - -### Query Parameters - - - -token owner's STX address or Smart Contract ID - -Example: `"SPNWZ5V2TPWGQGVDR6T7B6RQ4XMGZ4PXTEE0VQ0S.marketplace-v3"` - - - -"} required={false} deprecated={false}> - -identifiers of the token asset classes to filter for - -Example: `"SPQZF23W7SEYBFG5JQ496NMY0G7379SRYEDREMSV.Candy::candy"` - - - - - -max number of tokens to fetch - -Default: `50` - - - - - -index of first tokens to fetch - -Example: `42000` - -Default: `0` - - - - - -whether or not to include tokens from unconfirmed transactions - -Example: `true` - -Default: `false` - - - - - -whether or not to include the complete transaction metadata instead of just `tx_id`. Enabling this option can affect performance and response times. - -Default: `false` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of Non-Fungible Token holdings | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/tokens/nft/holdings?principal=SPNWZ5V2TPWGQGVDR6T7B6RQ4XMGZ4PXTEE0VQ0S.marketplace-v3&asset_identifiers=SPQZF23W7SEYBFG5JQ496NMY0G7379SRYEDREMSV.Candy%3A%3Acandy&limit=50&offset=42000&unanchored=true&tx_metadata=false" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/tokens/nft/holdings?principal=SPNWZ5V2TPWGQGVDR6T7B6RQ4XMGZ4PXTEE0VQ0S.marketplace-v3&asset_identifiers=SPQZF23W7SEYBFG5JQ496NMY0G7379SRYEDREMSV.Candy%3A%3Acandy&limit=50&offset=42000&unanchored=true&tx_metadata=false", { - method: "GET" -}); -``` - - - - - - - - - -List of Non-Fungible Token holdings - - - - - -```json -{ - "limit": 200, - "offset": 0, - "total": 0, - "results": [ - { - "asset_identifier": "string", - "value": { - "hex": "string", - "repr": "string" - }, - "block_height": 0, - "tx_id": "string" - } - ] -} -``` - - - - - -```ts -/** - * Describes the ownership of a Non-Fungible Token - */ -export type NonFungibleTokenHolding = NonFungibleTokenHoldingWithTxId | NonFungibleTokenHoldingWithTxMetadata; -/** - * Describes all transaction types on Stacks 2.0 blockchain - */ -export type Transaction = - | TokenTransferTransaction - | SmartContractTransaction - | ContractCallTransaction - | PoisonMicroblockTransaction - | CoinbaseTransaction - | TenureChangeTransaction; -/** - * Describes representation of a Type-0 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-0-transferring-an-asset - */ -export type TokenTransferTransaction = AbstractTransaction & TokenTransferTransactionMetadata; -/** - * Anchored transaction metadata. All mined/anchored Stacks transactions have these properties. - */ -export type AbstractTransaction = BaseTransaction & { - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - tx_status: TransactionStatus; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - /** - * List of transaction events - */ - events: TransactionEvent[]; -}; -export type PostConditionMode = "allow" | "deny"; -/** - * Post-conditionscan limit the damage done to a user's assets - */ -export type PostCondition = PostConditionStx | PostConditionFungible | PostConditionNonFungible; -export type PostConditionStx = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - amount: string; - type: "stx"; -}; -export type PostConditionPrincipal = - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_origin"; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_standard"; - address: string; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_contract"; - address: string; - contract_name: string; - }; -/** - * A fungible condition code encodes a statement being made for either STX or a fungible token, with respect to the originating account. - */ -export type PostConditionFungibleConditionCode = - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; -export type PostConditionFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - type: "fungible"; - amount: string; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -export type PostConditionNonFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionNonFungibleConditionCode; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -/** - * A non-fungible condition code encodes a statement being made about a non-fungible token, with respect to whether or not the particular non-fungible token is owned by the account. - */ -export type PostConditionNonFungibleConditionCode = "sent" | "not_sent"; -/** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ -export type TransactionAnchorModeType = "on_chain_only" | "off_chain_only" | "any"; -/** - * Status of the transaction - */ -export type TransactionStatus = "success" | "abort_by_response" | "abort_by_post_condition"; -export type TransactionEvent = - | TransactionEventSmartContractLog - | TransactionEventStxLock - | TransactionEventStxAsset - | TransactionEventFungibleAsset - | TransactionEventNonFungibleAsset; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventSmartContractLog = AbstractTransactionEvent & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxLock = AbstractTransactionEvent & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxAsset = AbstractTransactionEvent & { - event_type: "stx_asset"; - tx_id: string; - asset: TransactionEventAsset; -}; -export type TransactionEventAssetType = "transfer" | "mint" | "burn"; -export type TransactionEventFungibleAsset = AbstractTransactionEvent & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type TransactionEventNonFungibleAsset = AbstractTransactionEvent & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Describes representation of a Type-1 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export type SmartContractTransaction = AbstractTransaction & SmartContractTransactionMetadata; -/** - * Describes representation of a Type 2 Stacks 2.0 transaction: Contract Call - */ -export type ContractCallTransaction = AbstractTransaction & ContractCallTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type PoisonMicroblockTransaction = AbstractTransaction & PoisonMicroblockTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type CoinbaseTransaction = AbstractTransaction & CoinbaseTransactionMetadata; -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export type TenureChangeTransaction = AbstractTransaction & TenureChangeTransactionMetadata; - -/** - * List of Non-Fungible Token holdings - */ -export interface NonFungibleTokenHoldingsList { - /** - * The number of Non-Fungible Token holdings to return - */ - limit: number; - /** - * The number to Non-Fungible Token holdings to skip (starting at `0`) - */ - offset: number; - /** - * The number of Non-Fungible Token holdings available - */ - total: number; - results: NonFungibleTokenHolding[]; -} -/** - * Ownership of a Non-Fungible Token - */ -export interface NonFungibleTokenHoldingWithTxId { - asset_identifier: string; - /** - * Non-Fungible Token value - */ - value: { - /** - * Hex string representing the identifier of the Non-Fungible Token - */ - hex: string; - /** - * Readable string of the Non-Fungible Token identifier - */ - repr: string; - }; - block_height: number; - tx_id: string; -} -/** - * Ownership of a Non-Fungible Token with transaction metadata - */ -export interface NonFungibleTokenHoldingWithTxMetadata { - asset_identifier: string; - /** - * Non-Fungible Token value - */ - value: { - /** - * Hex string representing the identifier of the Non-Fungible Token - */ - hex: string; - /** - * Readable string of the Non-Fungible Token identifier - */ - repr: string; - }; - block_height: number; - tx: Transaction; -} -/** - * Transaction properties that are available from a raw serialized transactions. These are available for transactions in the mempool as well as mined transactions. - */ -export interface BaseTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: PostConditionMode; - post_conditions: PostCondition[]; - anchor_mode: TransactionAnchorModeType; -} -export interface AbstractTransactionEvent { - event_index: number; -} -export interface TransactionEventAsset { - asset_event_type?: TransactionEventAssetType; - asset_id?: string; - sender?: string; - recipient?: string; - amount?: string; - value?: string; - memo?: string; -} -/** - * Metadata associated with token-transfer type transactions - */ -export interface TokenTransferTransactionMetadata { - tx_type: "token_transfer"; - token_transfer: { - recipient_address: string; - /** - * Transfer amount as Integer string (64-bit unsigned integer) - */ - amount: string; - /** - * Hex encoded arbitrary message, up to 34 bytes length (should try decoding to an ASCII string) - */ - memo: string; - }; -} -/** - * Metadata associated with a contract-deploy type transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export interface SmartContractTransactionMetadata { - tx_type: "smart_contract"; - smart_contract: { - /** - * The Clarity version of the contract, only specified for versioned contract transactions, otherwise null - */ - clarity_version?: number; - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Clarity code of the smart contract being deployed - */ - source_code: string; - }; -} -/** - * Metadata associated with a contract-call type transaction - */ -export interface ContractCallTransactionMetadata { - tx_type: "contract_call"; - contract_call: { - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Name of the Clarity function to be invoked - */ - function_name: string; - /** - * Function definition, including function name and type as well as parameter names and types - */ - function_signature: string; - /** - * List of arguments used to invoke the function - */ - function_args?: { - hex: string; - repr: string; - name: string; - type: string; - }[]; - }; -} -/** - * Metadata associated with a poison-microblock type transaction - */ -export interface PoisonMicroblockTransactionMetadata { - tx_type: "poison_microblock"; - poison_microblock: { - /** - * Hex encoded microblock header - */ - microblock_header_1: string; - /** - * Hex encoded microblock header - */ - microblock_header_2: string; - }; -} -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export interface CoinbaseTransactionMetadata { - tx_type: "coinbase"; - coinbase_payload: { - /** - * Hex encoded 32-byte scratch space for block leader's use - */ - data: string; - /** - * A principal that will receive the miner rewards for this coinbase transaction. Can be either a standard principal or contract principal. Only specified for `coinbase-to-alt-recipient` transaction types, otherwise null. - */ - alt_recipient?: string; - /** - * Hex encoded 80-byte VRF proof - */ - vrf_proof?: string; - }; -} -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export interface TenureChangeTransactionMetadata { - tx_type: "tenure_change"; - tenure_change_payload?: { - /** - * Consensus hash of this tenure. Corresponds to the sortition in which the miner of this block was chosen. - */ - tenure_consensus_hash: string; - /** - * Consensus hash of the previous tenure. Corresponds to the sortition of the previous winning block-commit. - */ - prev_tenure_consensus_hash: string; - /** - * Current consensus hash on the underlying burnchain. Corresponds to the last-seen sortition. - */ - burn_view_consensus_hash: string; - /** - * (Hex string) Stacks Block hash - */ - previous_tenure_end: string; - /** - * The number of blocks produced in the previous tenure. - */ - previous_tenure_blocks: number; - /** - * Cause of change in mining tenure. Depending on cause, tenure can be ended or extended. - */ - cause: "block_found" | "extended"; - /** - * (Hex string) The ECDSA public key hash of the current tenure. - */ - pubkey_hash: string; - }; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/non-fungible-tokens/index.mdx b/content/docs/stacks/api/non-fungible-tokens/index.mdx deleted file mode 100644 index 14ac1c364..000000000 --- a/content/docs/stacks/api/non-fungible-tokens/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Non-fungible tokens -index: true -toc: false -description: Read-only endpoints to obtain non-fungible token details. ---- diff --git a/content/docs/stacks/api/non-fungible-tokens/mints.mdx b/content/docs/stacks/api/non-fungible-tokens/mints.mdx deleted file mode 100644 index 1f9d209df..000000000 --- a/content/docs/stacks/api/non-fungible-tokens/mints.mdx +++ /dev/null @@ -1,702 +0,0 @@ ---- -title: Get non-fungible token mints -description: Retrieves a list of non-fungible token mints for a given asset identifier. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Non-Fungible Token mints - -Retrieves all mint events for a Non-Fungible Token asset class. Useful to determine which NFTs of a particular collection have been claimed. - -More information on Non-Fungible Tokens on the Stacks blockchain can be found [here](https://docs.stacks.co/write-smart-contracts/tokens#non-fungible-tokens-nfts). - -### Query Parameters - - - -token asset class identifier - -Example: `"SP2X0TZ59D5SZ8ACQ6YMCHHNR2ZN51Z32E2CJ173.the-explorer-guild::The-Explorer-Guild"` - - - - - -max number of events to fetch - -Default: `50` - - - - - -index of first event to fetch - -Example: `42000` - -Default: `0` - - - - - -whether or not to include events from unconfirmed transactions - -Example: `true` - -Default: `false` - - - - - -whether or not to include the complete transaction metadata instead of just `tx_id`. Enabling this option can affect performance and response times. - -Default: `false` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Non-Fungible Token mints | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/tokens/nft/mints?asset_identifier=SP2X0TZ59D5SZ8ACQ6YMCHHNR2ZN51Z32E2CJ173.the-explorer-guild%3A%3AThe-Explorer-Guild&limit=50&offset=42000&unanchored=true&tx_metadata=false" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/tokens/nft/mints?asset_identifier=SP2X0TZ59D5SZ8ACQ6YMCHHNR2ZN51Z32E2CJ173.the-explorer-guild%3A%3AThe-Explorer-Guild&limit=50&offset=42000&unanchored=true&tx_metadata=false", { - method: "GET" -}); -``` - - - - - - - - - -List of Non-Fungible Token mint events for an asset identifier - - - - - -```json -{ - "limit": 200, - "offset": 0, - "total": 0, - "results": [ - { - "recipient": "string", - "event_index": 0, - "value": { - "hex": "string", - "repr": "string" - }, - "tx_id": "string" - } - ] -} -``` - - - - - -```ts -/** - * Describes the minting of a Non-Fungible Token - */ -export type NonFungibleTokenMint = NonFungibleTokenMintWithTxId | NonFungibleTokenMintWithTxMetadata; -/** - * Describes all transaction types on Stacks 2.0 blockchain - */ -export type Transaction = - | TokenTransferTransaction - | SmartContractTransaction - | ContractCallTransaction - | PoisonMicroblockTransaction - | CoinbaseTransaction - | TenureChangeTransaction; -/** - * Describes representation of a Type-0 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-0-transferring-an-asset - */ -export type TokenTransferTransaction = AbstractTransaction & TokenTransferTransactionMetadata; -/** - * Anchored transaction metadata. All mined/anchored Stacks transactions have these properties. - */ -export type AbstractTransaction = BaseTransaction & { - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - tx_status: TransactionStatus; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - /** - * List of transaction events - */ - events: TransactionEvent[]; -}; -export type PostConditionMode = "allow" | "deny"; -/** - * Post-conditionscan limit the damage done to a user's assets - */ -export type PostCondition = PostConditionStx | PostConditionFungible | PostConditionNonFungible; -export type PostConditionStx = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - amount: string; - type: "stx"; -}; -export type PostConditionPrincipal = - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_origin"; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_standard"; - address: string; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_contract"; - address: string; - contract_name: string; - }; -/** - * A fungible condition code encodes a statement being made for either STX or a fungible token, with respect to the originating account. - */ -export type PostConditionFungibleConditionCode = - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; -export type PostConditionFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - type: "fungible"; - amount: string; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -export type PostConditionNonFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionNonFungibleConditionCode; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -/** - * A non-fungible condition code encodes a statement being made about a non-fungible token, with respect to whether or not the particular non-fungible token is owned by the account. - */ -export type PostConditionNonFungibleConditionCode = "sent" | "not_sent"; -/** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ -export type TransactionAnchorModeType = "on_chain_only" | "off_chain_only" | "any"; -/** - * Status of the transaction - */ -export type TransactionStatus = "success" | "abort_by_response" | "abort_by_post_condition"; -export type TransactionEvent = - | TransactionEventSmartContractLog - | TransactionEventStxLock - | TransactionEventStxAsset - | TransactionEventFungibleAsset - | TransactionEventNonFungibleAsset; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventSmartContractLog = AbstractTransactionEvent & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxLock = AbstractTransactionEvent & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxAsset = AbstractTransactionEvent & { - event_type: "stx_asset"; - tx_id: string; - asset: TransactionEventAsset; -}; -export type TransactionEventAssetType = "transfer" | "mint" | "burn"; -export type TransactionEventFungibleAsset = AbstractTransactionEvent & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type TransactionEventNonFungibleAsset = AbstractTransactionEvent & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Describes representation of a Type-1 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export type SmartContractTransaction = AbstractTransaction & SmartContractTransactionMetadata; -/** - * Describes representation of a Type 2 Stacks 2.0 transaction: Contract Call - */ -export type ContractCallTransaction = AbstractTransaction & ContractCallTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type PoisonMicroblockTransaction = AbstractTransaction & PoisonMicroblockTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type CoinbaseTransaction = AbstractTransaction & CoinbaseTransactionMetadata; -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export type TenureChangeTransaction = AbstractTransaction & TenureChangeTransactionMetadata; - -/** - * List of Non-Fungible Token mint events for an asset identifier - */ -export interface NonFungibleTokenMintList { - /** - * The number of mint events to return - */ - limit: number; - /** - * The number to mint events to skip (starting at `0`) - */ - offset: number; - /** - * The number of mint events available - */ - total: number; - results: NonFungibleTokenMint[]; -} -/** - * Non-Fungible Token mint event with transaction id - */ -export interface NonFungibleTokenMintWithTxId { - recipient?: string; - event_index: number; - /** - * Non-Fungible Token value - */ - value: { - /** - * Hex string representing the identifier of the Non-Fungible Token - */ - hex: string; - /** - * Readable string of the Non-Fungible Token identifier - */ - repr: string; - }; - tx_id: string; -} -/** - * Non-Fungible Token mint event with transaction metadata - */ -export interface NonFungibleTokenMintWithTxMetadata { - recipient?: string; - event_index: number; - /** - * Non-Fungible Token value - */ - value: { - /** - * Hex string representing the identifier of the Non-Fungible Token - */ - hex: string; - /** - * Readable string of the Non-Fungible Token identifier - */ - repr: string; - }; - tx: Transaction; -} -/** - * Transaction properties that are available from a raw serialized transactions. These are available for transactions in the mempool as well as mined transactions. - */ -export interface BaseTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: PostConditionMode; - post_conditions: PostCondition[]; - anchor_mode: TransactionAnchorModeType; -} -export interface AbstractTransactionEvent { - event_index: number; -} -export interface TransactionEventAsset { - asset_event_type?: TransactionEventAssetType; - asset_id?: string; - sender?: string; - recipient?: string; - amount?: string; - value?: string; - memo?: string; -} -/** - * Metadata associated with token-transfer type transactions - */ -export interface TokenTransferTransactionMetadata { - tx_type: "token_transfer"; - token_transfer: { - recipient_address: string; - /** - * Transfer amount as Integer string (64-bit unsigned integer) - */ - amount: string; - /** - * Hex encoded arbitrary message, up to 34 bytes length (should try decoding to an ASCII string) - */ - memo: string; - }; -} -/** - * Metadata associated with a contract-deploy type transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export interface SmartContractTransactionMetadata { - tx_type: "smart_contract"; - smart_contract: { - /** - * The Clarity version of the contract, only specified for versioned contract transactions, otherwise null - */ - clarity_version?: number; - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Clarity code of the smart contract being deployed - */ - source_code: string; - }; -} -/** - * Metadata associated with a contract-call type transaction - */ -export interface ContractCallTransactionMetadata { - tx_type: "contract_call"; - contract_call: { - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Name of the Clarity function to be invoked - */ - function_name: string; - /** - * Function definition, including function name and type as well as parameter names and types - */ - function_signature: string; - /** - * List of arguments used to invoke the function - */ - function_args?: { - hex: string; - repr: string; - name: string; - type: string; - }[]; - }; -} -/** - * Metadata associated with a poison-microblock type transaction - */ -export interface PoisonMicroblockTransactionMetadata { - tx_type: "poison_microblock"; - poison_microblock: { - /** - * Hex encoded microblock header - */ - microblock_header_1: string; - /** - * Hex encoded microblock header - */ - microblock_header_2: string; - }; -} -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export interface CoinbaseTransactionMetadata { - tx_type: "coinbase"; - coinbase_payload: { - /** - * Hex encoded 32-byte scratch space for block leader's use - */ - data: string; - /** - * A principal that will receive the miner rewards for this coinbase transaction. Can be either a standard principal or contract principal. Only specified for `coinbase-to-alt-recipient` transaction types, otherwise null. - */ - alt_recipient?: string; - /** - * Hex encoded 80-byte VRF proof - */ - vrf_proof?: string; - }; -} -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export interface TenureChangeTransactionMetadata { - tx_type: "tenure_change"; - tenure_change_payload?: { - /** - * Consensus hash of this tenure. Corresponds to the sortition in which the miner of this block was chosen. - */ - tenure_consensus_hash: string; - /** - * Consensus hash of the previous tenure. Corresponds to the sortition of the previous winning block-commit. - */ - prev_tenure_consensus_hash: string; - /** - * Current consensus hash on the underlying burnchain. Corresponds to the last-seen sortition. - */ - burn_view_consensus_hash: string; - /** - * (Hex string) Stacks Block hash - */ - previous_tenure_end: string; - /** - * The number of blocks produced in the previous tenure. - */ - previous_tenure_blocks: number; - /** - * Cause of change in mining tenure. Depending on cause, tenure can be ended or extended. - */ - cause: "block_found" | "extended"; - /** - * (Hex string) The ECDSA public key hash of the current tenure. - */ - pubkey_hash: string; - }; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/proof-of-transfer/cycle.mdx b/content/docs/stacks/api/proof-of-transfer/cycle.mdx deleted file mode 100644 index d471cd8f4..000000000 --- a/content/docs/stacks/api/proof-of-transfer/cycle.mdx +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: Get PoX cycle -description: Retrieves details for a PoX cycle. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get PoX cycle - -Retrieves details for a PoX cycle -### Path Parameters - - - -PoX cycle number - -Example: `56` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Details for cycle | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v2/pox/cycles/56" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/pox/cycles/56", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "block_height": 0, - "index_block_hash": "string", - "cycle_number": 0, - "total_weight": 0, - "total_stacked_amount": "string", - "total_signers": 0 -} -``` - - - - - -```ts -export interface PoxCycle { - block_height: number; - index_block_hash: string; - cycle_number: number; - total_weight: number; - total_stacked_amount: string; - total_signers: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/proof-of-transfer/cycles.mdx b/content/docs/stacks/api/proof-of-transfer/cycles.mdx deleted file mode 100644 index 88c874747..000000000 --- a/content/docs/stacks/api/proof-of-transfer/cycles.mdx +++ /dev/null @@ -1,160 +0,0 @@ ---- -title: Get PoX cycles -description: Retrieves a list of PoX cycles. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get PoX cycles - -Retrieves a list of PoX cycles - -### Query Parameters - - - -max number of cycles to fetch - -Default: `20` - -Maximum: `60` - - - - - -index of first cycle to fetch - -Example: `20` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of cycles | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v2/pox/cycles?limit=20&offset=20" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/pox/cycles?limit=20&offset=20", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns PoX cycles - - - - - -```json -{ - "limit": 200, - "offset": 0, - "total": 0, - "results": [ - { - "block_height": 0, - "index_block_hash": "string", - "cycle_number": 0, - "total_weight": 0, - "total_stacked_amount": "string", - "total_signers": 0 - } - ] -} -``` - - - - - -```ts -/** - * GET request that returns PoX cycles - */ -export interface PoxCycleListResponse { - /** - * The number of cycles to return - */ - limit: number; - /** - * The number to cycles to skip (starting at `0`) - */ - offset: number; - /** - * The total number of cycles - */ - total: number; - results: PoxCycle[]; -} -export interface PoxCycle { - block_height: number; - index_block_hash: string; - cycle_number: number; - total_weight: number; - total_stacked_amount: string; - total_signers: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/proof-of-transfer/index.mdx b/content/docs/stacks/api/proof-of-transfer/index.mdx deleted file mode 100644 index ffd2bc813..000000000 --- a/content/docs/stacks/api/proof-of-transfer/index.mdx +++ /dev/null @@ -1,7 +0,0 @@ ---- -title: Proof of Transfer -index: true -toc: false -description: Retrieve information on PoX cycles, signers, and stackers. ---- - diff --git a/content/docs/stacks/api/proof-of-transfer/meta.json b/content/docs/stacks/api/proof-of-transfer/meta.json deleted file mode 100644 index 7f4e55e5e..000000000 --- a/content/docs/stacks/api/proof-of-transfer/meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "title": "Proof of Transfer", - "pages": [ - "cycles", - "cycle", - "signers-in-cycle", - "signer-in-cycle", - "stackers-for-signer-in-cycle" - ], - "defaultOpen": false -} \ No newline at end of file diff --git a/content/docs/stacks/api/proof-of-transfer/signer-in-cycle.mdx b/content/docs/stacks/api/proof-of-transfer/signer-in-cycle.mdx deleted file mode 100644 index e5ca9ce59..000000000 --- a/content/docs/stacks/api/proof-of-transfer/signer-in-cycle.mdx +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: Get signer in PoX cycle -description: Retrieves details for a signer in a PoX cycle. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get signer in PoX cycle - -Retrieves details for a signer in a PoX cycle -### Path Parameters - - - -PoX cycle number - -Example: `56` - - - - - -Signer key - -Example: `"0x038e3c4529395611be9abf6fa3b6987e81d402385e3d605a073f42f407565a4a3d"` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Details for PoX signer | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v2/pox/cycles/56/signers/0x038e3c4529395611be9abf6fa3b6987e81d402385e3d605a073f42f407565a4a3d" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/pox/cycles/56/signers/0x038e3c4529395611be9abf6fa3b6987e81d402385e3d605a073f42f407565a4a3d", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "signing_key": "string", - "signer_address": "string", - "weight": 0, - "stacked_amount": "string", - "weight_percent": 0, - "stacked_amount_percent": 0, - "solo_stacker_count": 0, - "pooled_stacker_count": 0 -} -``` - - - - - -```ts -export interface PoxSigner { - signing_key: string; - /** - * The Stacks address derived from the signing_key. - */ - signer_address: string; - weight: number; - stacked_amount: string; - weight_percent: number; - stacked_amount_percent: number; - /** - * The number of solo stackers associated with this signer. - */ - solo_stacker_count: number; - /** - * The number of pooled stackers associated with this signer. - */ - pooled_stacker_count: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/proof-of-transfer/signers-in-cycle.mdx b/content/docs/stacks/api/proof-of-transfer/signers-in-cycle.mdx deleted file mode 100644 index 4bb6f888c..000000000 --- a/content/docs/stacks/api/proof-of-transfer/signers-in-cycle.mdx +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: Get signers in PoX cycle -description: Retrieves a list of signers in a PoX cycle. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get signers in PoX cycle - -Retrieves a list of signers in a PoX cycle -### Path Parameters - - - -PoX cycle number - -Example: `56` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of signers for cycle | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v2/pox/cycles/56/signers" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/pox/cycles/56/signers", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns signers for a PoX cycle - - - - - -```json -{ - "limit": 200, - "offset": 0, - "total": 0, - "results": [ - { - "signing_key": "string", - "signer_address": "string", - "weight": 0, - "stacked_amount": "string", - "weight_percent": 0, - "stacked_amount_percent": 0, - "solo_stacker_count": 0, - "pooled_stacker_count": 0 - } - ] -} -``` - - - - - -```ts -/** - * GET request that returns signers for a PoX cycle - */ -export interface PoxCycleSignersListResponse { - /** - * The number of signers to return - */ - limit: number; - /** - * The number to signers to skip (starting at `0`) - */ - offset: number; - /** - * The total number of signers - */ - total: number; - results: PoxSigner[]; -} -export interface PoxSigner { - signing_key: string; - /** - * The Stacks address derived from the signing_key. - */ - signer_address: string; - weight: number; - stacked_amount: string; - weight_percent: number; - stacked_amount_percent: number; - /** - * The number of solo stackers associated with this signer. - */ - solo_stacker_count: number; - /** - * The number of pooled stackers associated with this signer. - */ - pooled_stacker_count: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/proof-of-transfer/stackers-for-signer-in-cycle.mdx b/content/docs/stacks/api/proof-of-transfer/stackers-for-signer-in-cycle.mdx deleted file mode 100644 index 55b2e08ed..000000000 --- a/content/docs/stacks/api/proof-of-transfer/stackers-for-signer-in-cycle.mdx +++ /dev/null @@ -1,153 +0,0 @@ ---- -title: Get stackers for signer in PoX cycle -description: Retrieves a list of stackers for a signer in a PoX cycle. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get stackers for signer in PoX cycle - -Retrieves a list of stackers for a signer in a PoX cycle -### Path Parameters - - - -PoX cycle number - -Example: `56` - - - - - -Signer key - -Example: `"0x038e3c4529395611be9abf6fa3b6987e81d402385e3d605a073f42f407565a4a3d"` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of stackers | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v2/pox/cycles/56/signers/0x038e3c4529395611be9abf6fa3b6987e81d402385e3d605a073f42f407565a4a3d/stackers" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/pox/cycles/56/signers/0x038e3c4529395611be9abf6fa3b6987e81d402385e3d605a073f42f407565a4a3d/stackers", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns stackers for a signer in a PoX cycle - - - - - -```json -{ - "limit": 200, - "offset": 0, - "total": 0, - "results": [ - { - "stacker_address": "string", - "stacked_amount": "string", - "pox_address": "string", - "stacker_type": "solo" - } - ] -} -``` - - - - - -```ts -/** - * GET request that returns stackers for a signer in a PoX cycle - */ -export interface PoxCycleSignerStackersListResponse { - /** - * The number of stackers to return - */ - limit: number; - /** - * The number to stackers to skip (starting at `0`) - */ - offset: number; - /** - * The total number of stackers - */ - total: number; - results: PoxStacker[]; -} -export interface PoxStacker { - stacker_address: string; - stacked_amount: string; - pox_address: string; - stacker_type: "solo" | "pooled"; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/search/index.mdx b/content/docs/stacks/api/search/index.mdx deleted file mode 100644 index e3684bf00..000000000 --- a/content/docs/stacks/api/search/index.mdx +++ /dev/null @@ -1,7 +0,0 @@ ---- -title: Search -index: true -toc: false -description: Search for a principal by ID. ---- - diff --git a/content/docs/stacks/api/search/search-by-id.mdx b/content/docs/stacks/api/search/search-by-id.mdx deleted file mode 100644 index 6973534d9..000000000 --- a/content/docs/stacks/api/search/search-by-id.mdx +++ /dev/null @@ -1,999 +0,0 @@ ---- -title: Search by ID -description: Search blocks, transactions, contracts, or accounts by hash/ID. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Search - -Search blocks, transactions, contracts, or accounts by hash/ID -### Path Parameters - - - -The hex hash string for a block or transaction, account address, or contract address - -Example: `"0xcf8b233f19f6c07d2dc1963302d2436efd36e9afac127bf6582824a13961c06d"` - - -### Query Parameters - - - -This includes the detailed data for purticular hash in the response - - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | -| `404` | Not found | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/search/0xcf8b233f19f6c07d2dc1963302d2436efd36e9afac127bf6582824a13961c06d?include_metadata=true" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/search/0xcf8b233f19f6c07d2dc1963302d2436efd36e9afac127bf6582824a13961c06d?include_metadata=true", { - method: "GET" -}); -``` - - - - - - - - - -complete search result for terms - - - - - -```json -{ - "found": false, - "result": { - "entity_type": "standard_address" - }, - "error": "string" -} -``` - - - - - -```ts -/** - * complete search result for terms - */ -export type SearchResult = SearchErrorResult | SearchSuccessResult; -/** - * Search success result - */ -export type SearchSuccessResult = - | AddressSearchResult - | BlockSearchResult - | ContractSearchResult - | MempoolTxSearchResult - | TxSearchResult; -/** - * GET request that returns address balances - */ -export type AddressStxBalanceResponse = StxBalance & { - token_offering_locked?: AddressTokenOfferingLocked; -}; -/** - * Describes all transaction types on Stacks 2.0 blockchain - */ -export type MempoolTransaction = - | MempoolTokenTransferTransaction - | MempoolSmartContractTransaction - | MempoolContractCallTransaction - | MempoolPoisonMicroblockTransaction - | MempoolCoinbaseTransaction - | MempoolTenureChangeTransaction; -/** - * Describes representation of a Type-0 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-0-transferring-an-asset - */ -export type MempoolTokenTransferTransaction = AbstractMempoolTransaction & TokenTransferTransactionMetadata; -/** - * Abstract transaction. This schema makes up all properties common between all Stacks 2.0 transaction types - */ -export type AbstractMempoolTransaction = BaseTransaction & { - tx_status: MempoolTransactionStatus; - /** - * A unix timestamp (in seconds) indicating when the transaction broadcast was received by the node. - */ - receipt_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when the transaction broadcast was received by the node. - */ - receipt_time_iso: string; -}; -export type PostConditionMode = "allow" | "deny"; -/** - * Post-conditionscan limit the damage done to a user's assets - */ -export type PostCondition = PostConditionStx | PostConditionFungible | PostConditionNonFungible; -export type PostConditionStx = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - amount: string; - type: "stx"; -}; -export type PostConditionPrincipal = - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_origin"; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_standard"; - address: string; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_contract"; - address: string; - contract_name: string; - }; -/** - * A fungible condition code encodes a statement being made for either STX or a fungible token, with respect to the originating account. - */ -export type PostConditionFungibleConditionCode = - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; -export type PostConditionFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - type: "fungible"; - amount: string; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -export type PostConditionNonFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionNonFungibleConditionCode; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -/** - * A non-fungible condition code encodes a statement being made about a non-fungible token, with respect to whether or not the particular non-fungible token is owned by the account. - */ -export type PostConditionNonFungibleConditionCode = "sent" | "not_sent"; -/** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ -export type TransactionAnchorModeType = "on_chain_only" | "off_chain_only" | "any"; -/** - * Status of the transaction - */ -export type MempoolTransactionStatus = - | "pending" - | "dropped_replace_by_fee" - | "dropped_replace_across_fork" - | "dropped_too_expensive" - | "dropped_stale_garbage_collect" - | "dropped_problematic"; -/** - * Describes representation of a Type-1 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export type MempoolSmartContractTransaction = AbstractMempoolTransaction & SmartContractTransactionMetadata; -/** - * Describes representation of a Type 2 Stacks 2.0 transaction: Contract Call - */ -export type MempoolContractCallTransaction = AbstractMempoolTransaction & ContractCallTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type MempoolPoisonMicroblockTransaction = AbstractMempoolTransaction & PoisonMicroblockTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type MempoolCoinbaseTransaction = AbstractMempoolTransaction & CoinbaseTransactionMetadata; -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export type MempoolTenureChangeTransaction = AbstractMempoolTransaction & TenureChangeTransactionMetadata; -/** - * Describes all transaction types on Stacks 2.0 blockchain - */ -export type Transaction = - | TokenTransferTransaction - | SmartContractTransaction - | ContractCallTransaction - | PoisonMicroblockTransaction - | CoinbaseTransaction - | TenureChangeTransaction; -/** - * Describes representation of a Type-0 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-0-transferring-an-asset - */ -export type TokenTransferTransaction = AbstractTransaction & TokenTransferTransactionMetadata; -/** - * Anchored transaction metadata. All mined/anchored Stacks transactions have these properties. - */ -export type AbstractTransaction = BaseTransaction & { - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - tx_status: TransactionStatus; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - /** - * List of transaction events - */ - events: TransactionEvent[]; -}; -/** - * Status of the transaction - */ -export type TransactionStatus = "success" | "abort_by_response" | "abort_by_post_condition"; -export type TransactionEvent = - | TransactionEventSmartContractLog - | TransactionEventStxLock - | TransactionEventStxAsset - | TransactionEventFungibleAsset - | TransactionEventNonFungibleAsset; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventSmartContractLog = AbstractTransactionEvent & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxLock = AbstractTransactionEvent & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxAsset = AbstractTransactionEvent & { - event_type: "stx_asset"; - tx_id: string; - asset: TransactionEventAsset; -}; -export type TransactionEventAssetType = "transfer" | "mint" | "burn"; -export type TransactionEventFungibleAsset = AbstractTransactionEvent & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type TransactionEventNonFungibleAsset = AbstractTransactionEvent & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Describes representation of a Type-1 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export type SmartContractTransaction = AbstractTransaction & SmartContractTransactionMetadata; -/** - * Describes representation of a Type 2 Stacks 2.0 transaction: Contract Call - */ -export type ContractCallTransaction = AbstractTransaction & ContractCallTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type PoisonMicroblockTransaction = AbstractTransaction & PoisonMicroblockTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type CoinbaseTransaction = AbstractTransaction & CoinbaseTransactionMetadata; -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export type TenureChangeTransaction = AbstractTransaction & TenureChangeTransactionMetadata; - -/** - * Error search result - */ -export interface SearchErrorResult { - /** - * Indicates if the requested object was found or not - */ - found: boolean; - result: { - /** - * Shows the currenty category of entity it is searched in. - */ - entity_type: "standard_address" | "unknown_hash" | "contract_address" | "invalid_term"; - }; - error: string; -} -/** - * Address search result - */ -export interface AddressSearchResult { - /** - * Indicates if the requested object was found or not - */ - found: boolean; - /** - * This object carries the search result - */ - result: { - /** - * The id used to search this query. - */ - entity_id: string; - entity_type: "standard_address"; - metadata?: AddressStxBalanceResponse; - }; -} -export interface StxBalance { - balance: string; - total_sent: string; - total_received: string; - total_fees_sent: string; - total_miner_rewards_received: string; - /** - * The transaction where the lock event occurred. Empty if no tokens are locked. - */ - lock_tx_id: string; - /** - * The amount of locked STX, as string quoted micro-STX. Zero if no tokens are locked. - */ - locked: string; - /** - * The STX chain block height of when the lock event occurred. Zero if no tokens are locked. - */ - lock_height: number; - /** - * The burnchain block height of when the lock event occurred. Zero if no tokens are locked. - */ - burnchain_lock_height: number; - /** - * The burnchain block height of when the tokens unlock. Zero if no tokens are locked. - */ - burnchain_unlock_height: number; -} -/** - * Token Offering Locked - */ -export interface AddressTokenOfferingLocked { - /** - * Micro-STX amount still locked at current block height. - */ - total_locked: string; - /** - * Micro-STX amount unlocked at current block height. - */ - total_unlocked: string; - unlock_schedule: AddressUnlockSchedule[]; -} -/** - * Unlock schedule amount and block height - */ -export interface AddressUnlockSchedule { - /** - * Micro-STX amount locked at this block height. - */ - amount: string; - block_height: number; -} -/** - * Block search result - */ -export interface BlockSearchResult { - /** - * Indicates if the requested object was found or not - */ - found: boolean; - /** - * This object carries the search result - */ - result: { - /** - * The id used to search this query. - */ - entity_id: string; - entity_type: "block_hash"; - /** - * Returns basic search result information about the requested id - */ - block_data: { - /** - * If the block lies within the canonical chain - */ - canonical: boolean; - /** - * Refers to the hash of the block - */ - hash: string; - parent_block_hash: string; - burn_block_time: number; - height: number; - }; - metadata?: Block; - }; -} -/** - * A block - */ -export interface Block { - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Height of the block - */ - height: number; - /** - * Hash representing the block - */ - hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * The only hash that can uniquely identify an anchored block or an unconfirmed state trie - */ - index_block_hash: string; - /** - * Hash of the parent block - */ - parent_block_hash: string; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Hash of the anchor chain block - */ - burn_block_hash: string; - /** - * Height of the anchor chain block - */ - burn_block_height: number; - /** - * Anchor chain transaction ID - */ - miner_txid: string; - /** - * The hash of the last streamed block that precedes this block to which this block is to be appended. Not every anchored block will have a parent microblock stream. An anchored block that does not have a parent microblock stream has the parent microblock hash set to an empty string, and the parent microblock sequence number set to -1. - */ - parent_microblock_hash: string; - /** - * The hash of the last streamed block that precedes this block to which this block is to be appended. Not every anchored block will have a parent microblock stream. An anchored block that does not have a parent microblock stream has the parent microblock hash set to an empty string, and the parent microblock sequence number set to -1. - */ - parent_microblock_sequence: number; - /** - * List of transactions included in the block - */ - txs: string[]; - /** - * List of microblocks that were accepted in this anchor block. Not every anchored block will have a accepted all (or any) of the previously streamed microblocks. Microblocks that were orphaned are not included in this list. - */ - microblocks_accepted: string[]; - /** - * List of microblocks that were streamed/produced by this anchor block's miner. This list only includes microblocks that were accepted in the following anchor block. Microblocks that were orphaned are not included in this list. - */ - microblocks_streamed: string[]; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - /** - * List of txs counts in each accepted microblock - */ - microblock_tx_count: { - [k: string]: number; - }; -} -/** - * Contract search result - */ -export interface ContractSearchResult { - /** - * Indicates if the requested object was found or not - */ - found: boolean; - /** - * This object carries the search result - */ - result: { - /** - * The id used to search this query. - */ - entity_id: string; - entity_type: "contract_address"; - /** - * Returns basic search result information about the requested id - */ - tx_data?: { - /** - * If the transaction lies within the canonical chain - */ - canonical?: boolean; - /** - * Refers to the hash of the block for searched transaction - */ - block_hash?: string; - burn_block_time?: number; - block_height?: number; - tx_type?: string; - /** - * Corresponding tx_id for smart_contract - */ - tx_id?: string; - }; - metadata?: MempoolTransaction | Transaction; - }; -} -/** - * Transaction properties that are available from a raw serialized transactions. These are available for transactions in the mempool as well as mined transactions. - */ -export interface BaseTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: PostConditionMode; - post_conditions: PostCondition[]; - anchor_mode: TransactionAnchorModeType; -} -/** - * Metadata associated with token-transfer type transactions - */ -export interface TokenTransferTransactionMetadata { - tx_type: "token_transfer"; - token_transfer: { - recipient_address: string; - /** - * Transfer amount as Integer string (64-bit unsigned integer) - */ - amount: string; - /** - * Hex encoded arbitrary message, up to 34 bytes length (should try decoding to an ASCII string) - */ - memo: string; - }; -} -/** - * Metadata associated with a contract-deploy type transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export interface SmartContractTransactionMetadata { - tx_type: "smart_contract"; - smart_contract: { - /** - * The Clarity version of the contract, only specified for versioned contract transactions, otherwise null - */ - clarity_version?: number; - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Clarity code of the smart contract being deployed - */ - source_code: string; - }; -} -/** - * Metadata associated with a contract-call type transaction - */ -export interface ContractCallTransactionMetadata { - tx_type: "contract_call"; - contract_call: { - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Name of the Clarity function to be invoked - */ - function_name: string; - /** - * Function definition, including function name and type as well as parameter names and types - */ - function_signature: string; - /** - * List of arguments used to invoke the function - */ - function_args?: { - hex: string; - repr: string; - name: string; - type: string; - }[]; - }; -} -/** - * Metadata associated with a poison-microblock type transaction - */ -export interface PoisonMicroblockTransactionMetadata { - tx_type: "poison_microblock"; - poison_microblock: { - /** - * Hex encoded microblock header - */ - microblock_header_1: string; - /** - * Hex encoded microblock header - */ - microblock_header_2: string; - }; -} -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export interface CoinbaseTransactionMetadata { - tx_type: "coinbase"; - coinbase_payload: { - /** - * Hex encoded 32-byte scratch space for block leader's use - */ - data: string; - /** - * A principal that will receive the miner rewards for this coinbase transaction. Can be either a standard principal or contract principal. Only specified for `coinbase-to-alt-recipient` transaction types, otherwise null. - */ - alt_recipient?: string; - /** - * Hex encoded 80-byte VRF proof - */ - vrf_proof?: string; - }; -} -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export interface TenureChangeTransactionMetadata { - tx_type: "tenure_change"; - tenure_change_payload?: { - /** - * Consensus hash of this tenure. Corresponds to the sortition in which the miner of this block was chosen. - */ - tenure_consensus_hash: string; - /** - * Consensus hash of the previous tenure. Corresponds to the sortition of the previous winning block-commit. - */ - prev_tenure_consensus_hash: string; - /** - * Current consensus hash on the underlying burnchain. Corresponds to the last-seen sortition. - */ - burn_view_consensus_hash: string; - /** - * (Hex string) Stacks Block hash - */ - previous_tenure_end: string; - /** - * The number of blocks produced in the previous tenure. - */ - previous_tenure_blocks: number; - /** - * Cause of change in mining tenure. Depending on cause, tenure can be ended or extended. - */ - cause: "block_found" | "extended"; - /** - * (Hex string) The ECDSA public key hash of the current tenure. - */ - pubkey_hash: string; - }; -} -export interface AbstractTransactionEvent { - event_index: number; -} -export interface TransactionEventAsset { - asset_event_type?: TransactionEventAssetType; - asset_id?: string; - sender?: string; - recipient?: string; - amount?: string; - value?: string; - memo?: string; -} -/** - * Contract search result - */ -export interface MempoolTxSearchResult { - /** - * Indicates if the requested object was found or not - */ - found: boolean; - /** - * This object carries the search result - */ - result: { - /** - * The id used to search this query. - */ - entity_id: string; - entity_type: "mempool_tx_id"; - /** - * Returns basic search result information about the requested id - */ - tx_data: { - tx_type: string; - }; - metadata?: MempoolTransaction; - }; -} -/** - * Transaction search result - */ -export interface TxSearchResult { - /** - * Indicates if the requested object was found or not - */ - found: boolean; - /** - * This object carries the search result - */ - result: { - /** - * The id used to search this query. - */ - entity_id: string; - entity_type: "tx_id"; - /** - * Returns basic search result information about the requested id - */ - tx_data: { - /** - * If the transaction lies within the canonical chain - */ - canonical: boolean; - /** - * Refers to the hash of the block for searched transaction - */ - block_hash: string; - burn_block_time: number; - block_height: number; - tx_type: string; - }; - metadata?: Transaction; - }; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/smart-contracts/by-trait.mdx b/content/docs/stacks/api/smart-contracts/by-trait.mdx deleted file mode 100644 index 10ed114a5..000000000 --- a/content/docs/stacks/api/smart-contracts/by-trait.mdx +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: Get contracts by trait -description: Retrieves a list of contracts based on the following traits listed in JSON format - functions, variables, maps, fungible tokens and non-fungible tokens. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get contracts by trait - -Retrieves a list of contracts based on the following traits listed in JSON format - functions, variables, maps, fungible tokens and non-fungible tokens -### Query Parameters - - - -JSON abi of the trait. - - - - - -max number of contracts fetch - - - - - -index of first contract event to fetch - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of contracts implement given trait | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/contract/by_trait?trait_abi=string&limit=0&offset=0" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/contract/by_trait?trait_abi=string&limit=0&offset=0", { - method: "GET" -}); -``` - - - - - - - - - -GET list of contracts - - - - - -```json -{ - "limit": 0, - "offset": 0, - "results": [ - { - "tx_id": "string", - "canonical": true, - "contract_id": "string", - "block_height": 0, - "source_code": "string", - "abi": "string" - } - ] -} -``` - - - - - -```ts -/** - * GET list of contracts - */ -export interface ContractListResponse { - /** - * The number of contracts to return - */ - limit: number; - /** - * The number to contracts to skip (starting at `0`) - */ - offset: number; - results: SmartContract[]; -} -/** - * A Smart Contract Detail - */ -export interface SmartContract { - tx_id: string; - canonical: boolean; - contract_id: string; - block_height: number; - source_code: string; - abi: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/smart-contracts/events.mdx b/content/docs/stacks/api/smart-contracts/events.mdx deleted file mode 100644 index f6261e146..000000000 --- a/content/docs/stacks/api/smart-contracts/events.mdx +++ /dev/null @@ -1,224 +0,0 @@ ---- -title: Get contract events -description: Retrieves a list of events that have been triggered by a given smart contract. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get contract events - -Retrieves a list of events that have been triggered by a given `contract_id` -### Path Parameters - - - -Contract identifier formatted as `\.` - -Example: `"SP6P4EJF0VG8V0RB3TQQKJBHDQKEF6NVRD1KZE3C.satoshibles"` - - -### Query Parameters - - - -max number of contract events to fetch - - - - - -index of first contract event to fetch - -Example: `42000` - - - - - -Include transaction data from unanchored (i.e. unconfirmed) microblocks - -Example: `true` - -Default: `false` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of events | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/contract/SP6P4EJF0VG8V0RB3TQQKJBHDQKEF6NVRD1KZE3C.satoshibles/events?limit=0&offset=42000&unanchored=true" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/contract/SP6P4EJF0VG8V0RB3TQQKJBHDQKEF6NVRD1KZE3C.satoshibles/events?limit=0&offset=42000&unanchored=true", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "event_index": 0, - "event_type": "smart_contract_log", - "tx_id": "string", - "contract_log": { - "contract_id": "string", - "topic": "string", - "value": { - "hex": "string", - "repr": "string" - } - } -} -``` - - - - - -```ts -export type TransactionEvent = - | TransactionEventSmartContractLog - | TransactionEventStxLock - | TransactionEventStxAsset - | TransactionEventFungibleAsset - | TransactionEventNonFungibleAsset; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventSmartContractLog = AbstractTransactionEvent & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxLock = AbstractTransactionEvent & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxAsset = AbstractTransactionEvent & { - event_type: "stx_asset"; - tx_id: string; - asset: TransactionEventAsset; -}; -export type TransactionEventAssetType = "transfer" | "mint" | "burn"; -export type TransactionEventFungibleAsset = AbstractTransactionEvent & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type TransactionEventNonFungibleAsset = AbstractTransactionEvent & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; - -export interface AbstractTransactionEvent { - event_index: number; -} -export interface TransactionEventAsset { - asset_event_type?: TransactionEventAssetType; - asset_id?: string; - sender?: string; - recipient?: string; - amount?: string; - value?: string; - memo?: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/smart-contracts/index.mdx b/content/docs/stacks/api/smart-contracts/index.mdx deleted file mode 100644 index 32e39b1ac..000000000 --- a/content/docs/stacks/api/smart-contracts/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Smart contracts -index: true -toc: false -description: Provide information and facilitate interactions with smart contracts. ---- diff --git a/content/docs/stacks/api/smart-contracts/info.mdx b/content/docs/stacks/api/smart-contracts/info.mdx deleted file mode 100644 index b2fe5f2b3..000000000 --- a/content/docs/stacks/api/smart-contracts/info.mdx +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Get contract info -description: Retrieves details for a specific smart contract. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get contract info - -Retrieves details of a contract with a given `contract_id` - -| Status code | Description | -| :------ | :------ | -| `200` | Contract found | -| `404` | Cannot find contract of given ID | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/contract/%7Bcontract_id%7D" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/contract/%7Bcontract_id%7D", { - method: "GET" -}); -``` - - - - - - - - - -A Smart Contract Detail - - - - - -```json -{ - "tx_id": "string", - "canonical": true, - "contract_id": "string", - "block_height": 0, - "source_code": "string", - "abi": "string" -} -``` - - - - - -```ts -/** - * A Smart Contract Detail - */ -export interface SmartContract { - tx_id: string; - canonical: boolean; - contract_id: string; - block_height: number; - source_code: string; - abi: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/smart-contracts/meta.json b/content/docs/stacks/api/smart-contracts/meta.json deleted file mode 100644 index a0aff84cc..000000000 --- a/content/docs/stacks/api/smart-contracts/meta.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "title": "Smart Contracts", - "pages": [ - "status", - "info", - "source", - "by-trait", - "interface", - "map-entry", - "read-only", - "events" - ], - "defaultOpen": false -} - diff --git a/content/docs/stacks/api/smart-contracts/status.mdx b/content/docs/stacks/api/smart-contracts/status.mdx deleted file mode 100644 index fed279814..000000000 --- a/content/docs/stacks/api/smart-contracts/status.mdx +++ /dev/null @@ -1,164 +0,0 @@ ---- -title: Get contracts status -description: Retrieves the deployment status of multiple smart contracts. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get smart contracts status - -Retrieves the deployment status of multiple smart contracts. - - -### Query Parameters - -"} required={true} deprecated={false}> - -contract ids to fetch status for - -Example: `"SPQZF23W7SEYBFG5JQ496NMY0G7379SRYEDREMSV.Candy"` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of smart contract status | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v2/smart-contracts/status?contract_id=SPQZF23W7SEYBFG5JQ496NMY0G7379SRYEDREMSV.Candy" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/smart-contracts/status?contract_id=SPQZF23W7SEYBFG5JQ496NMY0G7379SRYEDREMSV.Candy", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns the deployment status of multiple smart contracts - - - - - -```json -{ - "property1": { - "found": true, - "result": { - "status": "string", - "tx_id": "string", - "contract_id": "string", - "block_height": 0 - } - }, - "property2": { - "found": true, - "result": { - "status": "string", - "tx_id": "string", - "contract_id": "string", - "block_height": 0 - } - } -} -``` - - - - - -```ts -/** - * GET request that returns the deployment status of multiple smart contracts - */ -export interface SmartContractsStatusResponse { - [k: string]: SmartContractFound | SmartContractNotFound; -} -export interface SmartContractFound { - found: true; - result: SmartContractStatus; -} -/** - * Deployment status of a smart contract - */ -export interface SmartContractStatus { - /** - * Smart contract deployment transaction status - */ - status: string; - /** - * Deployment transaction ID - */ - tx_id: string; - /** - * Smart contract ID - */ - contract_id: string; - /** - * Height of the transaction confirmation block - */ - block_height?: number; -} -export interface SmartContractNotFound { - found: false; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/stacking-pool/index.mdx b/content/docs/stacks/api/stacking-pool/index.mdx deleted file mode 100644 index 9dd34271f..000000000 --- a/content/docs/stacks/api/stacking-pool/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Stacking pool -index: true -toc: false -description: Retrieve the list of stacking pool members for a given delegator principal. ---- diff --git a/content/docs/stacks/api/stacking-pool/members.mdx b/content/docs/stacks/api/stacking-pool/members.mdx deleted file mode 100644 index 9b33cb578..000000000 --- a/content/docs/stacks/api/stacking-pool/members.mdx +++ /dev/null @@ -1,204 +0,0 @@ ---- -title: Get stacking pool members -description: Retrieves the list of stacking pool members for a given delegator principal. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Stacking pool members - -Retrieves the list of stacking pool members for a given delegator principal. -### Path Parameters - - - -Address principal of the stacking pool delegator - - -### Query Parameters - - - -If specified, only delegation events after the given block will be included - - - - - -whether or not to include Stackers from unconfirmed transactions - -Example: `true` - -Default: `false` - - - - - -number of items to return - -Example: `100` - -Default: `100` - -Maximum: `200` - - - - - -number of items to skip - -Example: `300` - -Default: `0` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/pox4/SP21YTSM60CAY6D011EZVEVNKXVW8FVZE198XEFFP/delegations?unanchored=false&limit=5" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/pox4/SP21YTSM60CAY6D011EZVEVNKXVW8FVZE198XEFFP/delegations?after_block=0&unanchored=true&limit=100&offset=300", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns stacking pool member details for a given pool (delegator) principal - - - - - -```json -{ - "limit": 200, - "offset": 0, - "total": 0, - "results": [ - { - "stacker": "string", - "pox_addr": "string", - "amount_ustx": "string", - "burn_block_unlock_height": 0, - "block_height": 0, - "tx_id": "string" - } - ] -} -``` - - - - - -```ts -/** - * GET request that returns stacking pool member details for a given pool (delegator) principal - */ -export interface PoolDelegationsResponse { - /** - * The number of Stackers to return - */ - limit: number; - /** - * The number to Stackers to skip (starting at `0`) - */ - offset: number; - /** - * The total number of Stackers - */ - total: number; - results: PoolDelegation[]; -} -export interface PoolDelegation { - /** - * The principal of the pool member that issued the delegation - */ - stacker: string; - /** - * The pox-addr value specified by the stacker in the delegation operation - */ - pox_addr?: string; - /** - * The amount of uSTX delegated by the stacker - */ - amount_ustx: string; - /** - * The optional burnchain block unlock height that the stacker may have specified - */ - burn_block_unlock_height?: number; - /** - * The block height at which the stacker delegation transaction was mined at - */ - block_height: number; - /** - * The tx_id of the stacker delegation operation - */ - tx_id: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/stacking-rewards/index.mdx b/content/docs/stacks/api/stacking-rewards/index.mdx deleted file mode 100644 index 072a558af..000000000 --- a/content/docs/stacks/api/stacking-rewards/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Stacking rewards -index: true -toc: false -description: Provides information on recent rewards, recipients, and total earned amounts. ---- diff --git a/content/docs/stacks/api/stacking-rewards/recent-burnchain-reward-recipient.mdx b/content/docs/stacks/api/stacking-rewards/recent-burnchain-reward-recipient.mdx deleted file mode 100644 index b8235e8ef..000000000 --- a/content/docs/stacks/api/stacking-rewards/recent-burnchain-reward-recipient.mdx +++ /dev/null @@ -1,185 +0,0 @@ ---- -title: Get recent burnchain reward for the given recipient -description: Retrieves a list of recent burnchain (e.g. Bitcoin) rewards for the given recipient with the associated amounts and block info. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get recent burnchain reward for the given recipient - -Retrieves a list of recent burnchain (e.g. Bitcoin) rewards for the given recipient with the associated amounts and block info -### Path Parameters - - - -Reward recipient address. Should either be in the native burnchain's format (e.g. B58 for Bitcoin), or if a STX principal address is provided it will be encoded as into the equivalent burnchain format - -Example: `"36hQtSEXBMevo5chpxhfAGiCTSC34QKgda"` - - -### Query Parameters - - - -max number of rewards to fetch - - - - - -index of first rewards to fetch - -Example: `42000` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of burnchain reward recipients and amounts | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/burnchain/rewards/36hQtSEXBMevo5chpxhfAGiCTSC34QKgda?limit=0&offset=42000" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/burnchain/rewards/36hQtSEXBMevo5chpxhfAGiCTSC34QKgda?limit=0&offset=42000", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns blocks - - - - - -```json -{ - "limit": 30, - "offset": 0, - "results": [ - { - "canonical": true, - "burn_block_hash": "string", - "burn_block_height": 0, - "burn_amount": "string", - "reward_recipient": "string", - "reward_amount": "string", - "reward_index": 0 - } - ] -} -``` - - - - - -```ts -/** - * GET request that returns blocks - */ -export interface BurnchainRewardListResponse { - /** - * The number of burnchain rewards to return - */ - limit: number; - /** - * The number to burnchain rewards to skip (starting at `0`) - */ - offset: number; - results: BurnchainReward[]; -} -/** - * Reward payment made on the burnchain - */ -export interface BurnchainReward { - /** - * Set to `true` if block corresponds to the canonical burchchain tip - */ - canonical: boolean; - /** - * The hash representing the burnchain block - */ - burn_block_hash: string; - /** - * Height of the burnchain block - */ - burn_block_height: number; - /** - * The total amount of burnchain tokens burned for this burnchain block, in the smallest unit (e.g. satoshis for Bitcoin) - */ - burn_amount: string; - /** - * The recipient address that received the burnchain rewards, in the format native to the burnchain (e.g. B58 encoded for Bitcoin) - */ - reward_recipient: string; - /** - * The amount of burnchain tokens rewarded to the recipient, in the smallest unit (e.g. satoshis for Bitcoin) - */ - reward_amount: string; - /** - * The index position of the reward entry, useful for ordering when there's more than one recipient per burnchain block - */ - reward_index: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/stacking-rewards/recent-burnchain-reward-recipients.mdx b/content/docs/stacks/api/stacking-rewards/recent-burnchain-reward-recipients.mdx deleted file mode 100644 index 764f6b51f..000000000 --- a/content/docs/stacks/api/stacking-rewards/recent-burnchain-reward-recipients.mdx +++ /dev/null @@ -1,180 +0,0 @@ ---- -title: Get recent burnchain reward recipients -description: Retrieves a list of recent burnchain (e.g. Bitcoin) reward recipients with the associated amounts and block info. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get recent burnchain reward recipients - -Retrieves a list of recent burnchain (e.g. Bitcoin) reward recipients with the associated amounts and block info -### Query Parameters - - - -max number of rewards to fetch - -Default: `96` - -Maximum: `250` - - - - - -index of first rewards to fetch - -Example: `42000` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of burnchain reward recipients and amounts | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/burnchain/rewards?limit=96&offset=42000" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/burnchain/rewards?limit=96&offset=42000", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns blocks - - - - - -```json -{ - "limit": 30, - "offset": 0, - "results": [ - { - "canonical": true, - "burn_block_hash": "string", - "burn_block_height": 0, - "burn_amount": "string", - "reward_recipient": "string", - "reward_amount": "string", - "reward_index": 0 - } - ] -} -``` - - - - - -```ts -/** - * GET request that returns blocks - */ -export interface BurnchainRewardListResponse { - /** - * The number of burnchain rewards to return - */ - limit: number; - /** - * The number to burnchain rewards to skip (starting at `0`) - */ - offset: number; - results: BurnchainReward[]; -} -/** - * Reward payment made on the burnchain - */ -export interface BurnchainReward { - /** - * Set to `true` if block corresponds to the canonical burchchain tip - */ - canonical: boolean; - /** - * The hash representing the burnchain block - */ - burn_block_hash: string; - /** - * Height of the burnchain block - */ - burn_block_height: number; - /** - * The total amount of burnchain tokens burned for this burnchain block, in the smallest unit (e.g. satoshis for Bitcoin) - */ - burn_amount: string; - /** - * The recipient address that received the burnchain rewards, in the format native to the burnchain (e.g. B58 encoded for Bitcoin) - */ - reward_recipient: string; - /** - * The amount of burnchain tokens rewarded to the recipient, in the smallest unit (e.g. satoshis for Bitcoin) - */ - reward_amount: string; - /** - * The index position of the reward entry, useful for ordering when there's more than one recipient per burnchain block - */ - reward_index: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/stacking-rewards/recent-reward-slot-holder-entries.mdx b/content/docs/stacks/api/stacking-rewards/recent-reward-slot-holder-entries.mdx deleted file mode 100644 index bbc009f8a..000000000 --- a/content/docs/stacks/api/stacking-rewards/recent-reward-slot-holder-entries.mdx +++ /dev/null @@ -1,180 +0,0 @@ ---- -title: Get recent reward slot holder entries -description: Retrieves a list of the Bitcoin addresses that would validly receive Proof-of-Transfer commitments for a given reward slot holder recipient address. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get recent reward slot holder entries for the given address - -Retrieves a list of the Bitcoin addresses that would validly receive Proof-of-Transfer commitments for a given reward slot holder recipient address. -### Path Parameters - - - -Reward slot holder recipient address. Should either be in the native burnchain's format (e.g. B58 for Bitcoin), or if a STX principal address is provided it will be encoded as into the equivalent burnchain format - -Example: `"36hQtSEXBMevo5chpxhfAGiCTSC34QKgda"` - - -### Query Parameters - - - -max number of items to fetch - - - - - -index of the first items to fetch - -Example: `42000` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of burnchain reward recipients and amounts | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/burnchain/reward_slot_holders/36hQtSEXBMevo5chpxhfAGiCTSC34QKgda?limit=0&offset=42000" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/burnchain/reward_slot_holders/36hQtSEXBMevo5chpxhfAGiCTSC34QKgda?limit=0&offset=42000", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns reward slot holders - - - - - -```json -{ - "limit": 30, - "offset": 0, - "total": 0, - "results": [ - { - "canonical": true, - "burn_block_hash": "string", - "burn_block_height": 0, - "address": "string", - "slot_index": 0 - } - ] -} -``` - - - - - -```ts -/** - * GET request that returns reward slot holders - */ -export interface BurnchainRewardSlotHolderListResponse { - /** - * The number of items to return - */ - limit: number; - /** - * The number of items to skip (starting at `0`) - */ - offset: number; - /** - * Total number of available items - */ - total: number; - results: BurnchainRewardSlotHolder[]; -} -/** - * Reward slot holder on the burnchain - */ -export interface BurnchainRewardSlotHolder { - /** - * Set to `true` if block corresponds to the canonical burchchain tip - */ - canonical: boolean; - /** - * The hash representing the burnchain block - */ - burn_block_hash: string; - /** - * Height of the burnchain block - */ - burn_block_height: number; - /** - * The recipient address that validly received PoX commitments, in the format native to the burnchain (e.g. B58 encoded for Bitcoin) - */ - address: string; - /** - * The index position of the reward entry, useful for ordering when there's more than one slot per burnchain block - */ - slot_index: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/stacking-rewards/recent-reward-slot-holders.mdx b/content/docs/stacks/api/stacking-rewards/recent-reward-slot-holders.mdx deleted file mode 100644 index 32fc8f5ac..000000000 --- a/content/docs/stacks/api/stacking-rewards/recent-reward-slot-holders.mdx +++ /dev/null @@ -1,175 +0,0 @@ ---- -title: Get recent reward slot holders -description: Retrieves a list of the Bitcoin addresses that would validly receive Proof-of-Transfer commitments. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get recent reward slot holders - -Retrieves a list of the Bitcoin addresses that would validly receive Proof-of-Transfer commitments. -### Query Parameters - - - -max number of items to fetch - -Default: `96` - -Maximum: `250` - - - - - -index of the first items to fetch - -Example: `42000` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of burnchain reward recipients and amounts | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/burnchain/reward_slot_holders?limit=96&offset=42000" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/burnchain/reward_slot_holders?limit=96&offset=42000", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns reward slot holders - - - - - -```json -{ - "limit": 30, - "offset": 0, - "total": 0, - "results": [ - { - "canonical": true, - "burn_block_hash": "string", - "burn_block_height": 0, - "address": "string", - "slot_index": 0 - } - ] -} -``` - - - - - -```ts -/** - * GET request that returns reward slot holders - */ -export interface BurnchainRewardSlotHolderListResponse { - /** - * The number of items to return - */ - limit: number; - /** - * The number of items to skip (starting at `0`) - */ - offset: number; - /** - * Total number of available items - */ - total: number; - results: BurnchainRewardSlotHolder[]; -} -/** - * Reward slot holder on the burnchain - */ -export interface BurnchainRewardSlotHolder { - /** - * Set to `true` if block corresponds to the canonical burchchain tip - */ - canonical: boolean; - /** - * The hash representing the burnchain block - */ - burn_block_hash: string; - /** - * Height of the burnchain block - */ - burn_block_height: number; - /** - * The recipient address that validly received PoX commitments, in the format native to the burnchain (e.g. B58 encoded for Bitcoin) - */ - address: string; - /** - * The index position of the reward entry, useful for ordering when there's more than one slot per burnchain block - */ - slot_index: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/stacking-rewards/total-burnchain-rewards-for-recipient.mdx b/content/docs/stacks/api/stacking-rewards/total-burnchain-rewards-for-recipient.mdx deleted file mode 100644 index 4295d5182..000000000 --- a/content/docs/stacks/api/stacking-rewards/total-burnchain-rewards-for-recipient.mdx +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: Get total burnchain rewards for the given recipient -description: Retrieves the total burnchain (e.g. Bitcoin) rewards for a given recipient address. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get total burnchain rewards for the given recipient - -Retrieves the total burnchain (e.g. Bitcoin) rewards for a given recipient `address` -### Path Parameters - - - -Reward recipient address. Should either be in the native burnchain's format (e.g. B58 for Bitcoin), or if a STX principal address is provided it will be encoded as into the equivalent burnchain format - -Example: `"36hQtSEXBMevo5chpxhfAGiCTSC34QKgda"` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of burnchain reward recipients and amounts | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/burnchain/rewards/36hQtSEXBMevo5chpxhfAGiCTSC34QKgda/total" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/burnchain/rewards/36hQtSEXBMevo5chpxhfAGiCTSC34QKgda/total", { - method: "GET" -}); -``` - - - - - - - - - -Total burnchain rewards made to a recipient - - - - - -```json -{ - "reward_recipient": "string", - "reward_amount": "string" -} -``` - - - - - -```ts -/** - * Total burnchain rewards made to a recipient - */ -export interface BurnchainRewardsTotal { - /** - * The recipient address that received the burnchain rewards, in the format native to the burnchain (e.g. B58 encoded for Bitcoin) - */ - reward_recipient: string; - /** - * The total amount of burnchain tokens rewarded to the recipient, in the smallest unit (e.g. satoshis for Bitcoin) - */ - reward_amount: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/tokens/holders.mdx b/content/docs/stacks/api/tokens/holders.mdx deleted file mode 100644 index 3ac6aa743..000000000 --- a/content/docs/stacks/api/tokens/holders.mdx +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Get fungible token holders -description: Retrieves the list of fungible token holders for a given token ID. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Fungible token holders - -Retrieves the list of fungible token holders for a given token ID. Specify `stx` for the `token` parameter to get the list of STX holders. - -### Path Parameters - - - -fungible token identifier - - - -| Status code | Description | -| :------ | :------ | -| `200` | Fungible token holders | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/tokens/ft/string/holders" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/tokens/ft/string/holders", { - method: "GET" -}); -``` - - - - - - - - - -List of fungible token holders - - - - - -```json -{ - "limit": 200, - "offset": 0, - "total": 0, - "total_supply": "string", - "results": [ - { - "address": "string", - "balance": "string" - } - ] -} -``` - - - - - -```ts -/** - * List of fungible token holders - */ -export interface FungibleTokenHolderList { - /** - * The number of holders to return - */ - limit: number; - /** - * The number to holders to skip (starting at `0`) - */ - offset: number; - /** - * The number of holders available - */ - total: number; - /** - * The total supply of the token (the sum of all balances) - */ - total_supply: string; - results: FtHolderEntry[]; -} -export interface FtHolderEntry { - address: string; - balance: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/tokens/index.mdx b/content/docs/stacks/api/tokens/index.mdx deleted file mode 100644 index 65eb71bfd..000000000 --- a/content/docs/stacks/api/tokens/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Tokens -index: true -toc: false -description: Read-only endpoints to obtain token details. ---- diff --git a/content/docs/stacks/api/transactions/address-transactions.mdx b/content/docs/stacks/api/transactions/address-transactions.mdx deleted file mode 100644 index 5933e33fa..000000000 --- a/content/docs/stacks/api/transactions/address-transactions.mdx +++ /dev/null @@ -1,740 +0,0 @@ ---- -title: Get address transactions -description: Retrieves transactions sent or received by a STX address or smart contract ID. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get address transactions - -Retrieves a paginated list of confirmed transactions sent or received by a STX address or Smart Contract ID, alongside the total amount of STX sent or received and the number of STX, FT and NFT transfers contained within each transaction. - -More information on Transaction types can be found [here](https://docs.stacks.co/understand-stacks/transactions#types). - -### Path Parameters - - - -STX address or Smart Contract ID - -Example: `"SP31DA6FTSJX2WGTZ69SFY11BH51NZMB0ZW97B5P0"` - - -### Query Parameters - - - -Number of transactions to fetch - -Example: `20` - - - - - -Index of first transaction to fetch - -Example: `10` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v2/addresses/SP31DA6FTSJX2WGTZ69SFY11BH51NZMB0ZW97B5P0/transactions?limit=20&offset=10" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/addresses/SP31DA6FTSJX2WGTZ69SFY11BH51NZMB0ZW97B5P0/transactions?limit=20&offset=10", { - method: "GET" -}); -``` - - - - - - - - - -GET Address Transactions - - - - - -```json -{ - "limit": 30, - "offset": 0, - "total": 0, - "results": [ - { - "tx": { - "tx_id": "string", - "nonce": 0, - "fee_rate": "string", - "sender_address": "string", - "sponsor_nonce": 0, - "sponsored": true, - "sponsor_address": "string", - "post_condition_mode": "allow", - "post_conditions": [ - { - "principal": { - "type_id": "principal_origin" - }, - "condition_code": "sent_equal_to", - "amount": "string", - "type": "stx" - } - ], - "anchor_mode": "on_chain_only", - "block_hash": "string", - "block_height": 0, - "block_time": 0, - "block_time_iso": "string", - "burn_block_height": 0, - "burn_block_time": 0, - "burn_block_time_iso": "string", - "parent_burn_block_time": 0, - "parent_burn_block_time_iso": "string", - "canonical": true, - "tx_index": 0, - "tx_status": "success", - "tx_result": { - "hex": "string", - "repr": "string" - }, - "event_count": 0, - "parent_block_hash": "string", - "is_unanchored": true, - "microblock_hash": "string", - "microblock_sequence": 0, - "microblock_canonical": true, - "execution_cost_read_count": 0, - "execution_cost_read_length": 0, - "execution_cost_runtime": 0, - "execution_cost_write_count": 0, - "execution_cost_write_length": 0, - "events": [ - { - "event_index": 0, - "event_type": "smart_contract_log", - "tx_id": "string", - "contract_log": { - "contract_id": "string", - "topic": "string", - "value": { - "hex": "string", - "repr": "string" - } - } - } - ], - "tx_type": "token_transfer", - "token_transfer": { - "recipient_address": "string", - "amount": "string", - "memo": "string" - } - }, - "stx_sent": "string", - "stx_received": "string", - "events": { - "stx": { - "transfer": 0, - "mint": 0, - "burn": 0 - }, - "ft": { - "transfer": 0, - "mint": 0, - "burn": 0 - }, - "nft": { - "transfer": 0, - "mint": 0, - "burn": 0 - } - } - } - ] -} -``` - - - - - -```ts -/** - * Describes all transaction types on Stacks 2.0 blockchain - */ -export type Transaction = - | TokenTransferTransaction - | SmartContractTransaction - | ContractCallTransaction - | PoisonMicroblockTransaction - | CoinbaseTransaction - | TenureChangeTransaction; -/** - * Describes representation of a Type-0 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-0-transferring-an-asset - */ -export type TokenTransferTransaction = AbstractTransaction & TokenTransferTransactionMetadata; -/** - * Anchored transaction metadata. All mined/anchored Stacks transactions have these properties. - */ -export type AbstractTransaction = BaseTransaction & { - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - tx_status: TransactionStatus; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - /** - * List of transaction events - */ - events: TransactionEvent[]; -}; -export type PostConditionMode = "allow" | "deny"; -/** - * Post-conditionscan limit the damage done to a user's assets - */ -export type PostCondition = PostConditionStx | PostConditionFungible | PostConditionNonFungible; -export type PostConditionStx = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - amount: string; - type: "stx"; -}; -export type PostConditionPrincipal = - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_origin"; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_standard"; - address: string; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_contract"; - address: string; - contract_name: string; - }; -/** - * A fungible condition code encodes a statement being made for either STX or a fungible token, with respect to the originating account. - */ -export type PostConditionFungibleConditionCode = - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; -export type PostConditionFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - type: "fungible"; - amount: string; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -export type PostConditionNonFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionNonFungibleConditionCode; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -/** - * A non-fungible condition code encodes a statement being made about a non-fungible token, with respect to whether or not the particular non-fungible token is owned by the account. - */ -export type PostConditionNonFungibleConditionCode = "sent" | "not_sent"; -/** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ -export type TransactionAnchorModeType = "on_chain_only" | "off_chain_only" | "any"; -/** - * Status of the transaction - */ -export type TransactionStatus = "success" | "abort_by_response" | "abort_by_post_condition"; -export type TransactionEvent = - | TransactionEventSmartContractLog - | TransactionEventStxLock - | TransactionEventStxAsset - | TransactionEventFungibleAsset - | TransactionEventNonFungibleAsset; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventSmartContractLog = AbstractTransactionEvent & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxLock = AbstractTransactionEvent & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxAsset = AbstractTransactionEvent & { - event_type: "stx_asset"; - tx_id: string; - asset: TransactionEventAsset; -}; -export type TransactionEventAssetType = "transfer" | "mint" | "burn"; -export type TransactionEventFungibleAsset = AbstractTransactionEvent & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type TransactionEventNonFungibleAsset = AbstractTransactionEvent & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Describes representation of a Type-1 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export type SmartContractTransaction = AbstractTransaction & SmartContractTransactionMetadata; -/** - * Describes representation of a Type 2 Stacks 2.0 transaction: Contract Call - */ -export type ContractCallTransaction = AbstractTransaction & ContractCallTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type PoisonMicroblockTransaction = AbstractTransaction & PoisonMicroblockTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type CoinbaseTransaction = AbstractTransaction & CoinbaseTransactionMetadata; -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export type TenureChangeTransaction = AbstractTransaction & TenureChangeTransactionMetadata; - -/** - * GET Address Transactions - */ -export interface AddressTransactionsV2ListResponse { - limit: number; - offset: number; - total: number; - results: AddressTransaction[]; -} -/** - * Address transaction with STX, FT and NFT transfer summaries - */ -export interface AddressTransaction { - tx: Transaction; - /** - * Total sent from the given address, including the tx fee, in micro-STX as an integer string. - */ - stx_sent: string; - /** - * Total received by the given address in micro-STX as an integer string. - */ - stx_received: string; - events?: { - stx: { - transfer: number; - mint: number; - burn: number; - }; - ft: { - transfer: number; - mint: number; - burn: number; - }; - nft: { - transfer: number; - mint: number; - burn: number; - }; - }; -} -/** - * Transaction properties that are available from a raw serialized transactions. These are available for transactions in the mempool as well as mined transactions. - */ -export interface BaseTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: PostConditionMode; - post_conditions: PostCondition[]; - anchor_mode: TransactionAnchorModeType; -} -export interface AbstractTransactionEvent { - event_index: number; -} -export interface TransactionEventAsset { - asset_event_type?: TransactionEventAssetType; - asset_id?: string; - sender?: string; - recipient?: string; - amount?: string; - value?: string; - memo?: string; -} -/** - * Metadata associated with token-transfer type transactions - */ -export interface TokenTransferTransactionMetadata { - tx_type: "token_transfer"; - token_transfer: { - recipient_address: string; - /** - * Transfer amount as Integer string (64-bit unsigned integer) - */ - amount: string; - /** - * Hex encoded arbitrary message, up to 34 bytes length (should try decoding to an ASCII string) - */ - memo: string; - }; -} -/** - * Metadata associated with a contract-deploy type transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export interface SmartContractTransactionMetadata { - tx_type: "smart_contract"; - smart_contract: { - /** - * The Clarity version of the contract, only specified for versioned contract transactions, otherwise null - */ - clarity_version?: number; - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Clarity code of the smart contract being deployed - */ - source_code: string; - }; -} -/** - * Metadata associated with a contract-call type transaction - */ -export interface ContractCallTransactionMetadata { - tx_type: "contract_call"; - contract_call: { - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Name of the Clarity function to be invoked - */ - function_name: string; - /** - * Function definition, including function name and type as well as parameter names and types - */ - function_signature: string; - /** - * List of arguments used to invoke the function - */ - function_args?: { - hex: string; - repr: string; - name: string; - type: string; - }[]; - }; -} -/** - * Metadata associated with a poison-microblock type transaction - */ -export interface PoisonMicroblockTransactionMetadata { - tx_type: "poison_microblock"; - poison_microblock: { - /** - * Hex encoded microblock header - */ - microblock_header_1: string; - /** - * Hex encoded microblock header - */ - microblock_header_2: string; - }; -} -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export interface CoinbaseTransactionMetadata { - tx_type: "coinbase"; - coinbase_payload: { - /** - * Hex encoded 32-byte scratch space for block leader's use - */ - data: string; - /** - * A principal that will receive the miner rewards for this coinbase transaction. Can be either a standard principal or contract principal. Only specified for `coinbase-to-alt-recipient` transaction types, otherwise null. - */ - alt_recipient?: string; - /** - * Hex encoded 80-byte VRF proof - */ - vrf_proof?: string; - }; -} -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export interface TenureChangeTransactionMetadata { - tx_type: "tenure_change"; - tenure_change_payload?: { - /** - * Consensus hash of this tenure. Corresponds to the sortition in which the miner of this block was chosen. - */ - tenure_consensus_hash: string; - /** - * Consensus hash of the previous tenure. Corresponds to the sortition of the previous winning block-commit. - */ - prev_tenure_consensus_hash: string; - /** - * Current consensus hash on the underlying burnchain. Corresponds to the last-seen sortition. - */ - burn_view_consensus_hash: string; - /** - * (Hex string) Stacks Block hash - */ - previous_tenure_end: string; - /** - * The number of blocks produced in the previous tenure. - */ - previous_tenure_blocks: number; - /** - * Cause of change in mining tenure. Depending on cause, tenure can be ended or extended. - */ - cause: "block_found" | "extended"; - /** - * (Hex string) The ECDSA public key hash of the current tenure. - */ - pubkey_hash: string; - }; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/transactions/details-for-transactions.mdx b/content/docs/stacks/api/transactions/details-for-transactions.mdx deleted file mode 100644 index 110f026c0..000000000 --- a/content/docs/stacks/api/transactions/details-for-transactions.mdx +++ /dev/null @@ -1,722 +0,0 @@ ---- -title: Get details for transactions -description: Retrieves details for a list of transactions. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get list of details for transactions - -Retrieves a list of transactions for a given list of transaction IDs - -If using TypeScript, import typings for this response from our types package: - -`import type { Transaction } from '@stacks/stacks-blockchain-api-types';` - -| Status code | Description | -| :------ | :------ | -| `200` | Returns list of transactions with their details for corresponding requested tx_ids. | -| `404` | Could not find any transaction by ID | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/tx/multiple" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/tx/multiple", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "property1": { - "found": true, - "result": { - "tx_id": "string", - "nonce": 0, - "fee_rate": "string", - "sender_address": "string", - "sponsor_nonce": 0, - "sponsored": true, - "sponsor_address": "string", - "post_condition_mode": "allow", - "post_conditions": [ - { - "principal": { - "type_id": "principal_origin" - }, - "condition_code": "sent_equal_to", - "amount": "string", - "type": "stx" - } - ], - "anchor_mode": "on_chain_only", - "tx_status": "pending", - "receipt_time": 0, - "receipt_time_iso": "string", - "tx_type": "token_transfer", - "token_transfer": { - "recipient_address": "string", - "amount": "string", - "memo": "string" - } - } - }, - "property2": { - "found": true, - "result": { - "tx_id": "string", - "nonce": 0, - "fee_rate": "string", - "sender_address": "string", - "sponsor_nonce": 0, - "sponsored": true, - "sponsor_address": "string", - "post_condition_mode": "allow", - "post_conditions": [ - { - "principal": { - "type_id": "principal_origin" - }, - "condition_code": "sent_equal_to", - "amount": "string", - "type": "stx" - } - ], - "anchor_mode": "on_chain_only", - "tx_status": "pending", - "receipt_time": 0, - "receipt_time_iso": "string", - "tx_type": "token_transfer", - "token_transfer": { - "recipient_address": "string", - "amount": "string", - "memo": "string" - } - } - } -} -``` - - - - - -```ts -/** - * Describes all transaction types on Stacks 2.0 blockchain - */ -export type MempoolTransaction = - | MempoolTokenTransferTransaction - | MempoolSmartContractTransaction - | MempoolContractCallTransaction - | MempoolPoisonMicroblockTransaction - | MempoolCoinbaseTransaction - | MempoolTenureChangeTransaction; -/** - * Describes representation of a Type-0 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-0-transferring-an-asset - */ -export type MempoolTokenTransferTransaction = AbstractMempoolTransaction & TokenTransferTransactionMetadata; -/** - * Abstract transaction. This schema makes up all properties common between all Stacks 2.0 transaction types - */ -export type AbstractMempoolTransaction = BaseTransaction & { - tx_status: MempoolTransactionStatus; - /** - * A unix timestamp (in seconds) indicating when the transaction broadcast was received by the node. - */ - receipt_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when the transaction broadcast was received by the node. - */ - receipt_time_iso: string; -}; -export type PostConditionMode = "allow" | "deny"; -/** - * Post-conditionscan limit the damage done to a user's assets - */ -export type PostCondition = PostConditionStx | PostConditionFungible | PostConditionNonFungible; -export type PostConditionStx = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - amount: string; - type: "stx"; -}; -export type PostConditionPrincipal = - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_origin"; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_standard"; - address: string; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_contract"; - address: string; - contract_name: string; - }; -/** - * A fungible condition code encodes a statement being made for either STX or a fungible token, with respect to the originating account. - */ -export type PostConditionFungibleConditionCode = - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; -export type PostConditionFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - type: "fungible"; - amount: string; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -export type PostConditionNonFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionNonFungibleConditionCode; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -/** - * A non-fungible condition code encodes a statement being made about a non-fungible token, with respect to whether or not the particular non-fungible token is owned by the account. - */ -export type PostConditionNonFungibleConditionCode = "sent" | "not_sent"; -/** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ -export type TransactionAnchorModeType = "on_chain_only" | "off_chain_only" | "any"; -/** - * Status of the transaction - */ -export type MempoolTransactionStatus = - | "pending" - | "dropped_replace_by_fee" - | "dropped_replace_across_fork" - | "dropped_too_expensive" - | "dropped_stale_garbage_collect" - | "dropped_problematic"; -/** - * Describes representation of a Type-1 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export type MempoolSmartContractTransaction = AbstractMempoolTransaction & SmartContractTransactionMetadata; -/** - * Describes representation of a Type 2 Stacks 2.0 transaction: Contract Call - */ -export type MempoolContractCallTransaction = AbstractMempoolTransaction & ContractCallTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type MempoolPoisonMicroblockTransaction = AbstractMempoolTransaction & PoisonMicroblockTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type MempoolCoinbaseTransaction = AbstractMempoolTransaction & CoinbaseTransactionMetadata; -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export type MempoolTenureChangeTransaction = AbstractMempoolTransaction & TenureChangeTransactionMetadata; -/** - * Describes all transaction types on Stacks 2.0 blockchain - */ -export type Transaction = - | TokenTransferTransaction - | SmartContractTransaction - | ContractCallTransaction - | PoisonMicroblockTransaction - | CoinbaseTransaction - | TenureChangeTransaction; -/** - * Describes representation of a Type-0 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-0-transferring-an-asset - */ -export type TokenTransferTransaction = AbstractTransaction & TokenTransferTransactionMetadata; -/** - * Anchored transaction metadata. All mined/anchored Stacks transactions have these properties. - */ -export type AbstractTransaction = BaseTransaction & { - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - tx_status: TransactionStatus; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - /** - * List of transaction events - */ - events: TransactionEvent[]; -}; -/** - * Status of the transaction - */ -export type TransactionStatus = "success" | "abort_by_response" | "abort_by_post_condition"; -export type TransactionEvent = - | TransactionEventSmartContractLog - | TransactionEventStxLock - | TransactionEventStxAsset - | TransactionEventFungibleAsset - | TransactionEventNonFungibleAsset; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventSmartContractLog = AbstractTransactionEvent & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxLock = AbstractTransactionEvent & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxAsset = AbstractTransactionEvent & { - event_type: "stx_asset"; - tx_id: string; - asset: TransactionEventAsset; -}; -export type TransactionEventAssetType = "transfer" | "mint" | "burn"; -export type TransactionEventFungibleAsset = AbstractTransactionEvent & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type TransactionEventNonFungibleAsset = AbstractTransactionEvent & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Describes representation of a Type-1 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export type SmartContractTransaction = AbstractTransaction & SmartContractTransactionMetadata; -/** - * Describes representation of a Type 2 Stacks 2.0 transaction: Contract Call - */ -export type ContractCallTransaction = AbstractTransaction & ContractCallTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type PoisonMicroblockTransaction = AbstractTransaction & PoisonMicroblockTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type CoinbaseTransaction = AbstractTransaction & CoinbaseTransactionMetadata; -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export type TenureChangeTransaction = AbstractTransaction & TenureChangeTransactionMetadata; - -export interface TransactionList { - [k: string]: TransactionFound | TransactionNotFound; -} -/** - * This object returns transaction for found true - */ -export interface TransactionFound { - found: true; - result: MempoolTransaction | Transaction; -} -/** - * Transaction properties that are available from a raw serialized transactions. These are available for transactions in the mempool as well as mined transactions. - */ -export interface BaseTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: PostConditionMode; - post_conditions: PostCondition[]; - anchor_mode: TransactionAnchorModeType; -} -/** - * Metadata associated with token-transfer type transactions - */ -export interface TokenTransferTransactionMetadata { - tx_type: "token_transfer"; - token_transfer: { - recipient_address: string; - /** - * Transfer amount as Integer string (64-bit unsigned integer) - */ - amount: string; - /** - * Hex encoded arbitrary message, up to 34 bytes length (should try decoding to an ASCII string) - */ - memo: string; - }; -} -/** - * Metadata associated with a contract-deploy type transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export interface SmartContractTransactionMetadata { - tx_type: "smart_contract"; - smart_contract: { - /** - * The Clarity version of the contract, only specified for versioned contract transactions, otherwise null - */ - clarity_version?: number; - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Clarity code of the smart contract being deployed - */ - source_code: string; - }; -} -/** - * Metadata associated with a contract-call type transaction - */ -export interface ContractCallTransactionMetadata { - tx_type: "contract_call"; - contract_call: { - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Name of the Clarity function to be invoked - */ - function_name: string; - /** - * Function definition, including function name and type as well as parameter names and types - */ - function_signature: string; - /** - * List of arguments used to invoke the function - */ - function_args?: { - hex: string; - repr: string; - name: string; - type: string; - }[]; - }; -} -/** - * Metadata associated with a poison-microblock type transaction - */ -export interface PoisonMicroblockTransactionMetadata { - tx_type: "poison_microblock"; - poison_microblock: { - /** - * Hex encoded microblock header - */ - microblock_header_1: string; - /** - * Hex encoded microblock header - */ - microblock_header_2: string; - }; -} -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export interface CoinbaseTransactionMetadata { - tx_type: "coinbase"; - coinbase_payload: { - /** - * Hex encoded 32-byte scratch space for block leader's use - */ - data: string; - /** - * A principal that will receive the miner rewards for this coinbase transaction. Can be either a standard principal or contract principal. Only specified for `coinbase-to-alt-recipient` transaction types, otherwise null. - */ - alt_recipient?: string; - /** - * Hex encoded 80-byte VRF proof - */ - vrf_proof?: string; - }; -} -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export interface TenureChangeTransactionMetadata { - tx_type: "tenure_change"; - tenure_change_payload?: { - /** - * Consensus hash of this tenure. Corresponds to the sortition in which the miner of this block was chosen. - */ - tenure_consensus_hash: string; - /** - * Consensus hash of the previous tenure. Corresponds to the sortition of the previous winning block-commit. - */ - prev_tenure_consensus_hash: string; - /** - * Current consensus hash on the underlying burnchain. Corresponds to the last-seen sortition. - */ - burn_view_consensus_hash: string; - /** - * (Hex string) Stacks Block hash - */ - previous_tenure_end: string; - /** - * The number of blocks produced in the previous tenure. - */ - previous_tenure_blocks: number; - /** - * Cause of change in mining tenure. Depending on cause, tenure can be ended or extended. - */ - cause: "block_found" | "extended"; - /** - * (Hex string) The ECDSA public key hash of the current tenure. - */ - pubkey_hash: string; - }; -} -export interface AbstractTransactionEvent { - event_index: number; -} -export interface TransactionEventAsset { - asset_event_type?: TransactionEventAssetType; - asset_id?: string; - sender?: string; - recipient?: string; - amount?: string; - value?: string; - memo?: string; -} -/** - * This object returns the id for not found transaction - */ -export interface TransactionNotFound { - found: false; - result: { - tx_id: string; - }; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/transactions/dropped-mempool-transactions.mdx b/content/docs/stacks/api/transactions/dropped-mempool-transactions.mdx deleted file mode 100644 index 34766c500..000000000 --- a/content/docs/stacks/api/transactions/dropped-mempool-transactions.mdx +++ /dev/null @@ -1,475 +0,0 @@ ---- -title: Get dropped mempool transactions -description: Retrieves all recently-broadcast transactions that have been dropped from the mempool. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get dropped mempool transactions - -Retrieves all recently-broadcast transactions that have been dropped from the mempool. - -Transactions are dropped from the mempool if: - * they were stale and awaiting garbage collection or, - * were expensive, or - * were replaced with a new fee - -### Query Parameters - - - -max number of mempool transactions to fetch - -Default: `96` - -Maximum: `200` - - - - - -index of first mempool transaction to fetch - -Example: `42000` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of dropped mempool transactions | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/tx/mempool/dropped?limit=96&offset=42000" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/tx/mempool/dropped?limit=96&offset=42000", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns transactions - - - - - -```json -{ - "limit": 0, - "offset": 0, - "total": 0, - "results": [ - { - "tx_id": "string", - "nonce": 0, - "fee_rate": "string", - "sender_address": "string", - "sponsor_nonce": 0, - "sponsored": true, - "sponsor_address": "string", - "post_condition_mode": "allow", - "post_conditions": [ - { - "principal": { - "type_id": "principal_origin" - }, - "condition_code": "sent_equal_to", - "amount": "string", - "type": "stx" - } - ], - "anchor_mode": "on_chain_only", - "tx_status": "pending", - "receipt_time": 0, - "receipt_time_iso": "string", - "tx_type": "token_transfer", - "token_transfer": { - "recipient_address": "string", - "amount": "string", - "memo": "string" - } - } - ] -} -``` - - - - - -```ts -/** - * Describes all transaction types on Stacks 2.0 blockchain - */ -export type MempoolTransaction = - | MempoolTokenTransferTransaction - | MempoolSmartContractTransaction - | MempoolContractCallTransaction - | MempoolPoisonMicroblockTransaction - | MempoolCoinbaseTransaction - | MempoolTenureChangeTransaction; -/** - * Describes representation of a Type-0 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-0-transferring-an-asset - */ -export type MempoolTokenTransferTransaction = AbstractMempoolTransaction & TokenTransferTransactionMetadata; -/** - * Abstract transaction. This schema makes up all properties common between all Stacks 2.0 transaction types - */ -export type AbstractMempoolTransaction = BaseTransaction & { - tx_status: MempoolTransactionStatus; - /** - * A unix timestamp (in seconds) indicating when the transaction broadcast was received by the node. - */ - receipt_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when the transaction broadcast was received by the node. - */ - receipt_time_iso: string; -}; -export type PostConditionMode = "allow" | "deny"; -/** - * Post-conditionscan limit the damage done to a user's assets - */ -export type PostCondition = PostConditionStx | PostConditionFungible | PostConditionNonFungible; -export type PostConditionStx = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - amount: string; - type: "stx"; -}; -export type PostConditionPrincipal = - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_origin"; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_standard"; - address: string; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_contract"; - address: string; - contract_name: string; - }; -/** - * A fungible condition code encodes a statement being made for either STX or a fungible token, with respect to the originating account. - */ -export type PostConditionFungibleConditionCode = - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; -export type PostConditionFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - type: "fungible"; - amount: string; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -export type PostConditionNonFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionNonFungibleConditionCode; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -/** - * A non-fungible condition code encodes a statement being made about a non-fungible token, with respect to whether or not the particular non-fungible token is owned by the account. - */ -export type PostConditionNonFungibleConditionCode = "sent" | "not_sent"; -/** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ -export type TransactionAnchorModeType = "on_chain_only" | "off_chain_only" | "any"; -/** - * Status of the transaction - */ -export type MempoolTransactionStatus = - | "pending" - | "dropped_replace_by_fee" - | "dropped_replace_across_fork" - | "dropped_too_expensive" - | "dropped_stale_garbage_collect" - | "dropped_problematic"; -/** - * Describes representation of a Type-1 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export type MempoolSmartContractTransaction = AbstractMempoolTransaction & SmartContractTransactionMetadata; -/** - * Describes representation of a Type 2 Stacks 2.0 transaction: Contract Call - */ -export type MempoolContractCallTransaction = AbstractMempoolTransaction & ContractCallTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type MempoolPoisonMicroblockTransaction = AbstractMempoolTransaction & PoisonMicroblockTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type MempoolCoinbaseTransaction = AbstractMempoolTransaction & CoinbaseTransactionMetadata; -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export type MempoolTenureChangeTransaction = AbstractMempoolTransaction & TenureChangeTransactionMetadata; - -/** - * GET request that returns transactions - */ -export interface MempoolTransactionListResponse { - limit: number; - offset: number; - total: number; - results: MempoolTransaction[]; -} -/** - * Transaction properties that are available from a raw serialized transactions. These are available for transactions in the mempool as well as mined transactions. - */ -export interface BaseTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: PostConditionMode; - post_conditions: PostCondition[]; - anchor_mode: TransactionAnchorModeType; -} -/** - * Metadata associated with token-transfer type transactions - */ -export interface TokenTransferTransactionMetadata { - tx_type: "token_transfer"; - token_transfer: { - recipient_address: string; - /** - * Transfer amount as Integer string (64-bit unsigned integer) - */ - amount: string; - /** - * Hex encoded arbitrary message, up to 34 bytes length (should try decoding to an ASCII string) - */ - memo: string; - }; -} -/** - * Metadata associated with a contract-deploy type transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export interface SmartContractTransactionMetadata { - tx_type: "smart_contract"; - smart_contract: { - /** - * The Clarity version of the contract, only specified for versioned contract transactions, otherwise null - */ - clarity_version?: number; - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Clarity code of the smart contract being deployed - */ - source_code: string; - }; -} -/** - * Metadata associated with a contract-call type transaction - */ -export interface ContractCallTransactionMetadata { - tx_type: "contract_call"; - contract_call: { - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Name of the Clarity function to be invoked - */ - function_name: string; - /** - * Function definition, including function name and type as well as parameter names and types - */ - function_signature: string; - /** - * List of arguments used to invoke the function - */ - function_args?: { - hex: string; - repr: string; - name: string; - type: string; - }[]; - }; -} -/** - * Metadata associated with a poison-microblock type transaction - */ -export interface PoisonMicroblockTransactionMetadata { - tx_type: "poison_microblock"; - poison_microblock: { - /** - * Hex encoded microblock header - */ - microblock_header_1: string; - /** - * Hex encoded microblock header - */ - microblock_header_2: string; - }; -} -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export interface CoinbaseTransactionMetadata { - tx_type: "coinbase"; - coinbase_payload: { - /** - * Hex encoded 32-byte scratch space for block leader's use - */ - data: string; - /** - * A principal that will receive the miner rewards for this coinbase transaction. Can be either a standard principal or contract principal. Only specified for `coinbase-to-alt-recipient` transaction types, otherwise null. - */ - alt_recipient?: string; - /** - * Hex encoded 80-byte VRF proof - */ - vrf_proof?: string; - }; -} -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export interface TenureChangeTransactionMetadata { - tx_type: "tenure_change"; - tenure_change_payload?: { - /** - * Consensus hash of this tenure. Corresponds to the sortition in which the miner of this block was chosen. - */ - tenure_consensus_hash: string; - /** - * Consensus hash of the previous tenure. Corresponds to the sortition of the previous winning block-commit. - */ - prev_tenure_consensus_hash: string; - /** - * Current consensus hash on the underlying burnchain. Corresponds to the last-seen sortition. - */ - burn_view_consensus_hash: string; - /** - * (Hex string) Stacks Block hash - */ - previous_tenure_end: string; - /** - * The number of blocks produced in the previous tenure. - */ - previous_tenure_blocks: number; - /** - * Cause of change in mining tenure. Depending on cause, tenure can be ended or extended. - */ - cause: "block_found" | "extended"; - /** - * (Hex string) The ECDSA public key hash of the current tenure. - */ - pubkey_hash: string; - }; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/transactions/events-for-an-address-transaction.mdx b/content/docs/stacks/api/transactions/events-for-an-address-transaction.mdx deleted file mode 100644 index 4d575981e..000000000 --- a/content/docs/stacks/api/transactions/events-for-an-address-transaction.mdx +++ /dev/null @@ -1,233 +0,0 @@ ---- -title: Get events for an address transaction -description: Retrieves events for a specific transaction. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get events for an address transaction - -Retrieves a paginated list of all STX, FT and NFT events concerning a STX address or Smart Contract ID within a specific transaction. - -### Path Parameters - - - -STX address or Smart Contract ID - -Example: `"SP31DA6FTSJX2WGTZ69SFY11BH51NZMB0ZW97B5P0"` - - - - - -Transaction ID - -Example: `"0x0a411719e3bfde95f9e227a2d7f8fac3d6c646b1e6cc186db0e2838a2c6cd9c0"` - - -### Query Parameters - - - -Number of events to fetch - -Example: `20` - - - - - -Index of first event to fetch - -Example: `10` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v2/addresses/SP31DA6FTSJX2WGTZ69SFY11BH51NZMB0ZW97B5P0/transactions/0x0a411719e3bfde95f9e227a2d7f8fac3d6c646b1e6cc186db0e2838a2c6cd9c0/events?limit=20&offset=10" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/addresses/SP31DA6FTSJX2WGTZ69SFY11BH51NZMB0ZW97B5P0/transactions/0x0a411719e3bfde95f9e227a2d7f8fac3d6c646b1e6cc186db0e2838a2c6cd9c0/events?limit=20&offset=10", { - method: "GET" -}); -``` - - - - - - - - - -GET Address Transaction Events - - - - - -```json -{ - "limit": 30, - "offset": 0, - "total": 0, - "results": [ - { - "type": "stx", - "event_index": 0, - "data": { - "type": "transfer", - "amount": "string", - "sender": "string", - "recipient": "string" - } - } - ] -} -``` - - - - - -```ts -/** - * Address Transaction Event - */ -export type AddressTransactionEvent = - | { - type: "stx"; - event_index: number; - data: { - type: "transfer" | "mint" | "burn"; - /** - * Amount transferred in micro-STX as an integer string. - */ - amount: string; - /** - * Principal that sent STX. This is unspecified if the STX were minted. - */ - sender?: string; - /** - * Principal that received STX. This is unspecified if the STX were burned. - */ - recipient?: string; - }; - } - | { - type: "ft"; - event_index: number; - data: { - type: "transfer" | "mint" | "burn"; - /** - * Fungible Token asset identifier. - */ - asset_identifier: string; - /** - * Amount transferred as an integer string. This balance does not factor in possible SIP-010 decimals. - */ - amount: string; - /** - * Principal that sent the asset. - */ - sender?: string; - /** - * Principal that received the asset. - */ - recipient?: string; - }; - } - | { - type: "nft"; - event_index: number; - data: { - type: "transfer" | "mint" | "burn"; - /** - * Non Fungible Token asset identifier. - */ - asset_identifier: string; - /** - * Non Fungible Token asset value. - */ - value: { - hex: string; - repr: string; - }; - /** - * Principal that sent the asset. - */ - sender?: string; - /** - * Principal that received the asset. - */ - recipient?: string; - }; - }; - -/** - * GET Address Transaction Events - */ -export interface AddressTransactionEventListResponse { - limit: number; - offset: number; - total: number; - results: AddressTransactionEvent[]; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/transactions/get-raw-transaction.mdx b/content/docs/stacks/api/transactions/get-raw-transaction.mdx deleted file mode 100644 index b37a25071..000000000 --- a/content/docs/stacks/api/transactions/get-raw-transaction.mdx +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Get raw transaction -description: Retrieves a hex encoded serialized transaction for a given ID. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get Raw Transaction - -Retrieves a hex encoded serialized transaction for a given ID - - -| Status code | Description | -| :------ | :------ | -| `200` | Hex encoded serialized transaction | -| `404` | Cannot find transaction for given ID | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/tx/%7Btx_id%7D/raw" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/tx/%7Btx_id%7D/raw", { - method: "GET" -}); -``` - - - - - - - - - -GET raw transaction - - - - - -```json -{ - "raw_tx": "string" -} -``` - - - - - -```ts -/** - * GET raw transaction - */ -export interface GetRawTransactionResult { - /** - * A hex encoded serialized transaction - */ - raw_tx: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/transactions/get-transaction.mdx b/content/docs/stacks/api/transactions/get-transaction.mdx deleted file mode 100644 index 8350835b0..000000000 --- a/content/docs/stacks/api/transactions/get-transaction.mdx +++ /dev/null @@ -1,656 +0,0 @@ ---- -title: Get transaction -description: Retrieves details for a specific transaction. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get transaction - -Retrieves transaction details for a given transaction ID - -`import type { Transaction } from '@stacks/stacks-blockchain-api-types';` - -### Path Parameters - - - -Transaction ID - -Example: `"0xe0cc8444f6303fabef13e1fea00fcddb3db6b9519ce808f3f812fafec42fae5b"` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Transaction | -| `404` | Cannot find transaction for given ID | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/tx/{tx_id}" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/tx/{tx_id}", { - method: "GET" -}); -``` - - - - - - - - - -Fetches transaction details for a given transaction ID - - - - - -```json -{ - "tx_id": "string", - "nonce": 0, - "fee_rate": "string", - "sender_address": "string", - "sponsor_nonce": 0, - "sponsored": true, - "sponsor_address": "string", - "post_condition_mode": "allow", - "post_conditions": [ - { - "principal": { - "type_id": "principal_origin" - }, - "condition_code": "sent_equal_to", - "amount": "string", - "type": "stx" - } - ], - "anchor_mode": "on_chain_only", - "block_hash": "string", - "block_height": 0, - "block_time": 0, - "block_time_iso": "string", - "burn_block_height": 0, - "burn_block_time": 0, - "burn_block_time_iso": "string", - "parent_burn_block_time": 0, - "parent_burn_block_time_iso": "string", - "canonical": true, - "tx_index": 0, - "tx_status": "success", - "tx_result": { - "hex": "string", - "repr": "string" - }, - "event_count": 0, - "parent_block_hash": "string", - "is_unanchored": true, - "microblock_hash": "string", - "microblock_sequence": 0, - "microblock_canonical": true, - "execution_cost_read_count": 0, - "execution_cost_read_length": 0, - "execution_cost_runtime": 0, - "execution_cost_write_count": 0, - "execution_cost_write_length": 0, - "events": [ - { - "event_index": 0, - "event_type": "smart_contract_log", - "tx_id": "string", - "contract_log": { - "contract_id": "string", - "topic": "string", - "value": { - "hex": "string", - "repr": "string" - } - } - } - ], - "tx_type": "token_transfer", - "token_transfer": { - "recipient_address": "string", - "amount": "string", - "memo": "string" - } -} -``` - - - - - -```ts -/** - * Describes all transaction types on Stacks 2.0 blockchain - */ -export type Transaction = - | TokenTransferTransaction - | SmartContractTransaction - | ContractCallTransaction - | PoisonMicroblockTransaction - | CoinbaseTransaction - | TenureChangeTransaction; -/** - * Describes representation of a Type-0 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-0-transferring-an-asset - */ -export type TokenTransferTransaction = AbstractTransaction & TokenTransferTransactionMetadata; -/** - * Anchored transaction metadata. All mined/anchored Stacks transactions have these properties. - */ -export type AbstractTransaction = BaseTransaction & { - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - tx_status: TransactionStatus; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - /** - * List of transaction events - */ - events: TransactionEvent[]; -}; -export type PostConditionMode = "allow" | "deny"; -/** - * Post-conditionscan limit the damage done to a user's assets - */ -export type PostCondition = PostConditionStx | PostConditionFungible | PostConditionNonFungible; -export type PostConditionStx = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - amount: string; - type: "stx"; -}; -export type PostConditionPrincipal = - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_origin"; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_standard"; - address: string; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_contract"; - address: string; - contract_name: string; - }; -/** - * A fungible condition code encodes a statement being made for either STX or a fungible token, with respect to the originating account. - */ -export type PostConditionFungibleConditionCode = - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; -export type PostConditionFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - type: "fungible"; - amount: string; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -export type PostConditionNonFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionNonFungibleConditionCode; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -/** - * A non-fungible condition code encodes a statement being made about a non-fungible token, with respect to whether or not the particular non-fungible token is owned by the account. - */ -export type PostConditionNonFungibleConditionCode = "sent" | "not_sent"; -/** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ -export type TransactionAnchorModeType = "on_chain_only" | "off_chain_only" | "any"; -/** - * Status of the transaction - */ -export type TransactionStatus = "success" | "abort_by_response" | "abort_by_post_condition"; -export type TransactionEvent = - | TransactionEventSmartContractLog - | TransactionEventStxLock - | TransactionEventStxAsset - | TransactionEventFungibleAsset - | TransactionEventNonFungibleAsset; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventSmartContractLog = AbstractTransactionEvent & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxLock = AbstractTransactionEvent & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxAsset = AbstractTransactionEvent & { - event_type: "stx_asset"; - tx_id: string; - asset: TransactionEventAsset; -}; -export type TransactionEventAssetType = "transfer" | "mint" | "burn"; -export type TransactionEventFungibleAsset = AbstractTransactionEvent & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type TransactionEventNonFungibleAsset = AbstractTransactionEvent & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Describes representation of a Type-1 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export type SmartContractTransaction = AbstractTransaction & SmartContractTransactionMetadata; -/** - * Describes representation of a Type 2 Stacks 2.0 transaction: Contract Call - */ -export type ContractCallTransaction = AbstractTransaction & ContractCallTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type PoisonMicroblockTransaction = AbstractTransaction & PoisonMicroblockTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type CoinbaseTransaction = AbstractTransaction & CoinbaseTransactionMetadata; -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export type TenureChangeTransaction = AbstractTransaction & TenureChangeTransactionMetadata; - -/** - * Transaction properties that are available from a raw serialized transactions. These are available for transactions in the mempool as well as mined transactions. - */ -export interface BaseTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: PostConditionMode; - post_conditions: PostCondition[]; - anchor_mode: TransactionAnchorModeType; -} -export interface AbstractTransactionEvent { - event_index: number; -} -export interface TransactionEventAsset { - asset_event_type?: TransactionEventAssetType; - asset_id?: string; - sender?: string; - recipient?: string; - amount?: string; - value?: string; - memo?: string; -} -/** - * Metadata associated with token-transfer type transactions - */ -export interface TokenTransferTransactionMetadata { - tx_type: "token_transfer"; - token_transfer: { - recipient_address: string; - /** - * Transfer amount as Integer string (64-bit unsigned integer) - */ - amount: string; - /** - * Hex encoded arbitrary message, up to 34 bytes length (should try decoding to an ASCII string) - */ - memo: string; - }; -} -/** - * Metadata associated with a contract-deploy type transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export interface SmartContractTransactionMetadata { - tx_type: "smart_contract"; - smart_contract: { - /** - * The Clarity version of the contract, only specified for versioned contract transactions, otherwise null - */ - clarity_version?: number; - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Clarity code of the smart contract being deployed - */ - source_code: string; - }; -} -/** - * Metadata associated with a contract-call type transaction - */ -export interface ContractCallTransactionMetadata { - tx_type: "contract_call"; - contract_call: { - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Name of the Clarity function to be invoked - */ - function_name: string; - /** - * Function definition, including function name and type as well as parameter names and types - */ - function_signature: string; - /** - * List of arguments used to invoke the function - */ - function_args?: { - hex: string; - repr: string; - name: string; - type: string; - }[]; - }; -} -/** - * Metadata associated with a poison-microblock type transaction - */ -export interface PoisonMicroblockTransactionMetadata { - tx_type: "poison_microblock"; - poison_microblock: { - /** - * Hex encoded microblock header - */ - microblock_header_1: string; - /** - * Hex encoded microblock header - */ - microblock_header_2: string; - }; -} -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export interface CoinbaseTransactionMetadata { - tx_type: "coinbase"; - coinbase_payload: { - /** - * Hex encoded 32-byte scratch space for block leader's use - */ - data: string; - /** - * A principal that will receive the miner rewards for this coinbase transaction. Can be either a standard principal or contract principal. Only specified for `coinbase-to-alt-recipient` transaction types, otherwise null. - */ - alt_recipient?: string; - /** - * Hex encoded 80-byte VRF proof - */ - vrf_proof?: string; - }; -} -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export interface TenureChangeTransactionMetadata { - tx_type: "tenure_change"; - tenure_change_payload?: { - /** - * Consensus hash of this tenure. Corresponds to the sortition in which the miner of this block was chosen. - */ - tenure_consensus_hash: string; - /** - * Consensus hash of the previous tenure. Corresponds to the sortition of the previous winning block-commit. - */ - prev_tenure_consensus_hash: string; - /** - * Current consensus hash on the underlying burnchain. Corresponds to the last-seen sortition. - */ - burn_view_consensus_hash: string; - /** - * (Hex string) Stacks Block hash - */ - previous_tenure_end: string; - /** - * The number of blocks produced in the previous tenure. - */ - previous_tenure_blocks: number; - /** - * Cause of change in mining tenure. Depending on cause, tenure can be ended or extended. - */ - cause: "block_found" | "extended"; - /** - * (Hex string) The ECDSA public key hash of the current tenure. - */ - pubkey_hash: string; - }; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/transactions/index.mdx b/content/docs/stacks/api/transactions/index.mdx deleted file mode 100644 index c6098a6e7..000000000 --- a/content/docs/stacks/api/transactions/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Transactions -index: true -toc: false -description: Manage, retrieve, and broadcast transaction data on the blockchain. ---- \ No newline at end of file diff --git a/content/docs/stacks/api/transactions/mempool-transactions.mdx b/content/docs/stacks/api/transactions/mempool-transactions.mdx deleted file mode 100644 index 197cc61cd..000000000 --- a/content/docs/stacks/api/transactions/mempool-transactions.mdx +++ /dev/null @@ -1,524 +0,0 @@ ---- -title: Get mempool transactions -description: Retrieves all transactions that have been recently broadcast to the mempool. These are pending transactions awaiting confirmation. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get mempool transactions - -Retrieves all transactions that have been recently broadcast to the mempool. These are pending transactions awaiting confirmation. - -If you need to monitor new transactions, we highly recommend subscribing to [WebSockets or Socket.io](https://github.com/hirosystems/stacks-blockchain-api/tree/master/client) for real-time updates. - -### Query Parameters - - - -Filter to only return transactions with this sender address. - -Example: `"SP1GPBP8NBRXDRJBFQBV7KMAZX1Z7W2RFWJEH0V10"` - - - - - -Filter to only return transactions with this recipient address (only applicable for STX transfer tx types). - - - - - -Filter to only return transactions with this address as the sender or recipient (recipient only applicable for STX transfer tx types). - - - - - -Option to sort results by transaction age, size, or fee rate. - -Example: `"fee"` - -Value in: `"age" | "size" | "fee"` - - - - - -Option to sort results in ascending or descending order. - -Example: `"asc"` - -Value in: `"asc" | "desc"` - - - - - -max number of mempool transactions to fetch - -Example: `20` - -Default: `20` - -Maximum: `50` - - - - - -index of first mempool transaction to fetch - -Example: `42000` - - - - - -Include transaction data from unanchored (i.e. unconfirmed) microblocks - -Example: `true` - -Default: `false` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of mempool transactions | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/tx/mempool?sender_address=SP1GPBP8NBRXDRJBFQBV7KMAZX1Z7W2RFWJEH0V10&recipient_address=string&address=string&order_by=fee&order=asc&limit=20&offset=42000&unanchored=true" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/tx/mempool?sender_address=SP1GPBP8NBRXDRJBFQBV7KMAZX1Z7W2RFWJEH0V10&recipient_address=string&address=string&order_by=fee&order=asc&limit=20&offset=42000&unanchored=true", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns transactions - - - - - -```json -{ - "limit": 0, - "offset": 0, - "total": 0, - "results": [ - { - "tx_id": "string", - "nonce": 0, - "fee_rate": "string", - "sender_address": "string", - "sponsor_nonce": 0, - "sponsored": true, - "sponsor_address": "string", - "post_condition_mode": "allow", - "post_conditions": [ - { - "principal": { - "type_id": "principal_origin" - }, - "condition_code": "sent_equal_to", - "amount": "string", - "type": "stx" - } - ], - "anchor_mode": "on_chain_only", - "tx_status": "pending", - "receipt_time": 0, - "receipt_time_iso": "string", - "tx_type": "token_transfer", - "token_transfer": { - "recipient_address": "string", - "amount": "string", - "memo": "string" - } - } - ] -} -``` - - - - - -```ts -/** - * Describes all transaction types on Stacks 2.0 blockchain - */ -export type MempoolTransaction = - | MempoolTokenTransferTransaction - | MempoolSmartContractTransaction - | MempoolContractCallTransaction - | MempoolPoisonMicroblockTransaction - | MempoolCoinbaseTransaction - | MempoolTenureChangeTransaction; -/** - * Describes representation of a Type-0 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-0-transferring-an-asset - */ -export type MempoolTokenTransferTransaction = AbstractMempoolTransaction & TokenTransferTransactionMetadata; -/** - * Abstract transaction. This schema makes up all properties common between all Stacks 2.0 transaction types - */ -export type AbstractMempoolTransaction = BaseTransaction & { - tx_status: MempoolTransactionStatus; - /** - * A unix timestamp (in seconds) indicating when the transaction broadcast was received by the node. - */ - receipt_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when the transaction broadcast was received by the node. - */ - receipt_time_iso: string; -}; -export type PostConditionMode = "allow" | "deny"; -/** - * Post-conditionscan limit the damage done to a user's assets - */ -export type PostCondition = PostConditionStx | PostConditionFungible | PostConditionNonFungible; -export type PostConditionStx = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - amount: string; - type: "stx"; -}; -export type PostConditionPrincipal = - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_origin"; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_standard"; - address: string; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_contract"; - address: string; - contract_name: string; - }; -/** - * A fungible condition code encodes a statement being made for either STX or a fungible token, with respect to the originating account. - */ -export type PostConditionFungibleConditionCode = - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; -export type PostConditionFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - type: "fungible"; - amount: string; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -export type PostConditionNonFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionNonFungibleConditionCode; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -/** - * A non-fungible condition code encodes a statement being made about a non-fungible token, with respect to whether or not the particular non-fungible token is owned by the account. - */ -export type PostConditionNonFungibleConditionCode = "sent" | "not_sent"; -/** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ -export type TransactionAnchorModeType = "on_chain_only" | "off_chain_only" | "any"; -/** - * Status of the transaction - */ -export type MempoolTransactionStatus = - | "pending" - | "dropped_replace_by_fee" - | "dropped_replace_across_fork" - | "dropped_too_expensive" - | "dropped_stale_garbage_collect" - | "dropped_problematic"; -/** - * Describes representation of a Type-1 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export type MempoolSmartContractTransaction = AbstractMempoolTransaction & SmartContractTransactionMetadata; -/** - * Describes representation of a Type 2 Stacks 2.0 transaction: Contract Call - */ -export type MempoolContractCallTransaction = AbstractMempoolTransaction & ContractCallTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type MempoolPoisonMicroblockTransaction = AbstractMempoolTransaction & PoisonMicroblockTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type MempoolCoinbaseTransaction = AbstractMempoolTransaction & CoinbaseTransactionMetadata; -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export type MempoolTenureChangeTransaction = AbstractMempoolTransaction & TenureChangeTransactionMetadata; - -/** - * GET request that returns transactions - */ -export interface MempoolTransactionListResponse { - limit: number; - offset: number; - total: number; - results: MempoolTransaction[]; -} -/** - * Transaction properties that are available from a raw serialized transactions. These are available for transactions in the mempool as well as mined transactions. - */ -export interface BaseTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: PostConditionMode; - post_conditions: PostCondition[]; - anchor_mode: TransactionAnchorModeType; -} -/** - * Metadata associated with token-transfer type transactions - */ -export interface TokenTransferTransactionMetadata { - tx_type: "token_transfer"; - token_transfer: { - recipient_address: string; - /** - * Transfer amount as Integer string (64-bit unsigned integer) - */ - amount: string; - /** - * Hex encoded arbitrary message, up to 34 bytes length (should try decoding to an ASCII string) - */ - memo: string; - }; -} -/** - * Metadata associated with a contract-deploy type transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export interface SmartContractTransactionMetadata { - tx_type: "smart_contract"; - smart_contract: { - /** - * The Clarity version of the contract, only specified for versioned contract transactions, otherwise null - */ - clarity_version?: number; - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Clarity code of the smart contract being deployed - */ - source_code: string; - }; -} -/** - * Metadata associated with a contract-call type transaction - */ -export interface ContractCallTransactionMetadata { - tx_type: "contract_call"; - contract_call: { - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Name of the Clarity function to be invoked - */ - function_name: string; - /** - * Function definition, including function name and type as well as parameter names and types - */ - function_signature: string; - /** - * List of arguments used to invoke the function - */ - function_args?: { - hex: string; - repr: string; - name: string; - type: string; - }[]; - }; -} -/** - * Metadata associated with a poison-microblock type transaction - */ -export interface PoisonMicroblockTransactionMetadata { - tx_type: "poison_microblock"; - poison_microblock: { - /** - * Hex encoded microblock header - */ - microblock_header_1: string; - /** - * Hex encoded microblock header - */ - microblock_header_2: string; - }; -} -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export interface CoinbaseTransactionMetadata { - tx_type: "coinbase"; - coinbase_payload: { - /** - * Hex encoded 32-byte scratch space for block leader's use - */ - data: string; - /** - * A principal that will receive the miner rewards for this coinbase transaction. Can be either a standard principal or contract principal. Only specified for `coinbase-to-alt-recipient` transaction types, otherwise null. - */ - alt_recipient?: string; - /** - * Hex encoded 80-byte VRF proof - */ - vrf_proof?: string; - }; -} -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export interface TenureChangeTransactionMetadata { - tx_type: "tenure_change"; - tenure_change_payload?: { - /** - * Consensus hash of this tenure. Corresponds to the sortition in which the miner of this block was chosen. - */ - tenure_consensus_hash: string; - /** - * Consensus hash of the previous tenure. Corresponds to the sortition of the previous winning block-commit. - */ - prev_tenure_consensus_hash: string; - /** - * Current consensus hash on the underlying burnchain. Corresponds to the last-seen sortition. - */ - burn_view_consensus_hash: string; - /** - * (Hex string) Stacks Block hash - */ - previous_tenure_end: string; - /** - * The number of blocks produced in the previous tenure. - */ - previous_tenure_blocks: number; - /** - * Cause of change in mining tenure. Depending on cause, tenure can be ended or extended. - */ - cause: "block_found" | "extended"; - /** - * (Hex string) The ECDSA public key hash of the current tenure. - */ - pubkey_hash: string; - }; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/transactions/recent-transactions.mdx b/content/docs/stacks/api/transactions/recent-transactions.mdx deleted file mode 100644 index 5a1e71223..000000000 --- a/content/docs/stacks/api/transactions/recent-transactions.mdx +++ /dev/null @@ -1,788 +0,0 @@ ---- -title: Get recent transactions -description: Retrieves all recently mined transactions. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get recent transactions - -Retrieves all recently mined transactions - -If using TypeScript, import typings for this response from our types package: - -`import type { TransactionResults } from '@stacks/stacks-blockchain-api-types';` - -### Query Parameters - - - -max number of transactions to fetch - -Example: `100` - -Default: `96` - -Maximum: `200` - - - - - -index of first transaction to fetch - -Example: `42000` - - - -"} required={false} deprecated={false}> - -Filter by transaction type - -Example: `"coinbase"` - - - - - -Option to filter results by sender address - - - - - -Option to filter results by recipient address - - - - - -Option to sort results by block height, timestamp, or fee - -Example: `"burn_block_time"` - -Default: `"block_height"` - -Value in: `"block_height" | "burn_block_time" | "fee"` - - - - - -Filter by transactions after this timestamp (unix timestamp in seconds) - -Example: `1704067200` - - - - - -Filter by transactions before this timestamp (unix timestamp in seconds) - -Example: `1706745599` - - - - - -Filter by contract call transactions involving this contract ID - -Example: `"SP000000000000000000002Q6VF78.pox-4"` - - - - - -Filter by contract call transactions involving this function name - -Example: `"delegate-stx"` - - - - - -Filter by transactions with this nonce - -Example: `123` - - - - - -Option to sort results in ascending or descending order - -Example: `"desc"` - -Default: `"desc"` - -Value in: `"asc" | "desc"` - - - - - -Include transaction data from unanchored (i.e. unconfirmed) microblocks - -Example: `true` - -Default: `false` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of transactions | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/tx?limit=100&offset=42000&type=coinbase&from_address=string&to_address=string&sort_by=burn_block_time&start_time=1704067200&end_time=1706745599&contract_id=SP000000000000000000002Q6VF78.pox-4&function_name=delegate-stx&nonce=123&order=desc&unanchored=true" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/tx?limit=100&offset=42000&type=coinbase&from_address=string&to_address=string&sort_by=burn_block_time&start_time=1704067200&end_time=1706745599&contract_id=SP000000000000000000002Q6VF78.pox-4&function_name=delegate-stx&nonce=123&order=desc&unanchored=true", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns transactions - - - - - -```json -{ - "limit": 200, - "offset": 0, - "total": 0, - "results": [ - { - "tx_id": "string", - "nonce": 0, - "fee_rate": "string", - "sender_address": "string", - "sponsor_nonce": 0, - "sponsored": true, - "sponsor_address": "string", - "post_condition_mode": "allow", - "post_conditions": [ - { - "principal": { - "type_id": "principal_origin" - }, - "condition_code": "sent_equal_to", - "amount": "string", - "type": "stx" - } - ], - "anchor_mode": "on_chain_only", - "block_hash": "string", - "block_height": 0, - "block_time": 0, - "block_time_iso": "string", - "burn_block_height": 0, - "burn_block_time": 0, - "burn_block_time_iso": "string", - "parent_burn_block_time": 0, - "parent_burn_block_time_iso": "string", - "canonical": true, - "tx_index": 0, - "tx_status": "success", - "tx_result": { - "hex": "string", - "repr": "string" - }, - "event_count": 0, - "parent_block_hash": "string", - "is_unanchored": true, - "microblock_hash": "string", - "microblock_sequence": 0, - "microblock_canonical": true, - "execution_cost_read_count": 0, - "execution_cost_read_length": 0, - "execution_cost_runtime": 0, - "execution_cost_write_count": 0, - "execution_cost_write_length": 0, - "events": [ - { - "event_index": 0, - "event_type": "smart_contract_log", - "tx_id": "string", - "contract_log": { - "contract_id": "string", - "topic": "string", - "value": { - "hex": "string", - "repr": "string" - } - } - } - ], - "tx_type": "token_transfer", - "token_transfer": { - "recipient_address": "string", - "amount": "string", - "memo": "string" - } - } - ] -} -``` - - - - - -```ts -/** - * Describes all transaction types on Stacks 2.0 blockchain - */ -export type Transaction = - | TokenTransferTransaction - | SmartContractTransaction - | ContractCallTransaction - | PoisonMicroblockTransaction - | CoinbaseTransaction - | TenureChangeTransaction; -/** - * Describes representation of a Type-0 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-0-transferring-an-asset - */ -export type TokenTransferTransaction = AbstractTransaction & TokenTransferTransactionMetadata; -/** - * Anchored transaction metadata. All mined/anchored Stacks transactions have these properties. - */ -export type AbstractTransaction = BaseTransaction & { - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - tx_status: TransactionStatus; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - /** - * List of transaction events - */ - events: TransactionEvent[]; -}; -export type PostConditionMode = "allow" | "deny"; -/** - * Post-conditionscan limit the damage done to a user's assets - */ -export type PostCondition = PostConditionStx | PostConditionFungible | PostConditionNonFungible; -export type PostConditionStx = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - amount: string; - type: "stx"; -}; -export type PostConditionPrincipal = - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_origin"; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_standard"; - address: string; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_contract"; - address: string; - contract_name: string; - }; -/** - * A fungible condition code encodes a statement being made for either STX or a fungible token, with respect to the originating account. - */ -export type PostConditionFungibleConditionCode = - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; -export type PostConditionFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - type: "fungible"; - amount: string; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -export type PostConditionNonFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionNonFungibleConditionCode; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -/** - * A non-fungible condition code encodes a statement being made about a non-fungible token, with respect to whether or not the particular non-fungible token is owned by the account. - */ -export type PostConditionNonFungibleConditionCode = "sent" | "not_sent"; -/** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ -export type TransactionAnchorModeType = "on_chain_only" | "off_chain_only" | "any"; -/** - * Status of the transaction - */ -export type TransactionStatus = "success" | "abort_by_response" | "abort_by_post_condition"; -export type TransactionEvent = - | TransactionEventSmartContractLog - | TransactionEventStxLock - | TransactionEventStxAsset - | TransactionEventFungibleAsset - | TransactionEventNonFungibleAsset; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventSmartContractLog = AbstractTransactionEvent & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxLock = AbstractTransactionEvent & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxAsset = AbstractTransactionEvent & { - event_type: "stx_asset"; - tx_id: string; - asset: TransactionEventAsset; -}; -export type TransactionEventAssetType = "transfer" | "mint" | "burn"; -export type TransactionEventFungibleAsset = AbstractTransactionEvent & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type TransactionEventNonFungibleAsset = AbstractTransactionEvent & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Describes representation of a Type-1 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export type SmartContractTransaction = AbstractTransaction & SmartContractTransactionMetadata; -/** - * Describes representation of a Type 2 Stacks 2.0 transaction: Contract Call - */ -export type ContractCallTransaction = AbstractTransaction & ContractCallTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type PoisonMicroblockTransaction = AbstractTransaction & PoisonMicroblockTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type CoinbaseTransaction = AbstractTransaction & CoinbaseTransactionMetadata; -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export type TenureChangeTransaction = AbstractTransaction & TenureChangeTransactionMetadata; - -/** - * GET request that returns transactions - */ -export interface TransactionResults { - /** - * The number of transactions to return - */ - limit: number; - /** - * The number to transactions to skip (starting at `0`) - */ - offset: number; - /** - * The number of transactions available - */ - total: number; - results: Transaction[]; -} -/** - * Transaction properties that are available from a raw serialized transactions. These are available for transactions in the mempool as well as mined transactions. - */ -export interface BaseTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: PostConditionMode; - post_conditions: PostCondition[]; - anchor_mode: TransactionAnchorModeType; -} -export interface AbstractTransactionEvent { - event_index: number; -} -export interface TransactionEventAsset { - asset_event_type?: TransactionEventAssetType; - asset_id?: string; - sender?: string; - recipient?: string; - amount?: string; - value?: string; - memo?: string; -} -/** - * Metadata associated with token-transfer type transactions - */ -export interface TokenTransferTransactionMetadata { - tx_type: "token_transfer"; - token_transfer: { - recipient_address: string; - /** - * Transfer amount as Integer string (64-bit unsigned integer) - */ - amount: string; - /** - * Hex encoded arbitrary message, up to 34 bytes length (should try decoding to an ASCII string) - */ - memo: string; - }; -} -/** - * Metadata associated with a contract-deploy type transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export interface SmartContractTransactionMetadata { - tx_type: "smart_contract"; - smart_contract: { - /** - * The Clarity version of the contract, only specified for versioned contract transactions, otherwise null - */ - clarity_version?: number; - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Clarity code of the smart contract being deployed - */ - source_code: string; - }; -} -/** - * Metadata associated with a contract-call type transaction - */ -export interface ContractCallTransactionMetadata { - tx_type: "contract_call"; - contract_call: { - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Name of the Clarity function to be invoked - */ - function_name: string; - /** - * Function definition, including function name and type as well as parameter names and types - */ - function_signature: string; - /** - * List of arguments used to invoke the function - */ - function_args?: { - hex: string; - repr: string; - name: string; - type: string; - }[]; - }; -} -/** - * Metadata associated with a poison-microblock type transaction - */ -export interface PoisonMicroblockTransactionMetadata { - tx_type: "poison_microblock"; - poison_microblock: { - /** - * Hex encoded microblock header - */ - microblock_header_1: string; - /** - * Hex encoded microblock header - */ - microblock_header_2: string; - }; -} -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export interface CoinbaseTransactionMetadata { - tx_type: "coinbase"; - coinbase_payload: { - /** - * Hex encoded 32-byte scratch space for block leader's use - */ - data: string; - /** - * A principal that will receive the miner rewards for this coinbase transaction. Can be either a standard principal or contract principal. Only specified for `coinbase-to-alt-recipient` transaction types, otherwise null. - */ - alt_recipient?: string; - /** - * Hex encoded 80-byte VRF proof - */ - vrf_proof?: string; - }; -} -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export interface TenureChangeTransactionMetadata { - tx_type: "tenure_change"; - tenure_change_payload?: { - /** - * Consensus hash of this tenure. Corresponds to the sortition in which the miner of this block was chosen. - */ - tenure_consensus_hash: string; - /** - * Consensus hash of the previous tenure. Corresponds to the sortition of the previous winning block-commit. - */ - prev_tenure_consensus_hash: string; - /** - * Current consensus hash on the underlying burnchain. Corresponds to the last-seen sortition. - */ - burn_view_consensus_hash: string; - /** - * (Hex string) Stacks Block hash - */ - previous_tenure_end: string; - /** - * The number of blocks produced in the previous tenure. - */ - previous_tenure_blocks: number; - /** - * Cause of change in mining tenure. Depending on cause, tenure can be ended or extended. - */ - cause: "block_found" | "extended"; - /** - * (Hex string) The ECDSA public key hash of the current tenure. - */ - pubkey_hash: string; - }; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/transactions/statistics-for-mempool-transactions.mdx b/content/docs/stacks/api/transactions/statistics-for-mempool-transactions.mdx deleted file mode 100644 index c22306e75..000000000 --- a/content/docs/stacks/api/transactions/statistics-for-mempool-transactions.mdx +++ /dev/null @@ -1,289 +0,0 @@ ---- -title: Get statistics for mempool transactions -description: Retrieves statistics for transactions in the mempool, such as counts, ages, and fees. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get statistics for mempool transactions - -Queries for transactions counts, age (by block height), fees (simple average), and size. -All results broken down by transaction type and percentiles (p25, p50, p75, p95). - - -| Status code | Description | -| :------ | :------ | -| `200` | Statistics for mempool transactions | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/tx/mempool/stats" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/tx/mempool/stats", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns stats on mempool transactions - - - - - -```json -{ - "tx_type_counts": { - "token_transfer": 0, - "smart_contract": 0, - "contract_call": 0, - "poison_microblock": 0 - }, - "tx_simple_fee_averages": { - "token_transfer": { - "p25": 0, - "p50": 0, - "p75": 0, - "p95": 0 - }, - "smart_contract": { - "p25": 0, - "p50": 0, - "p75": 0, - "p95": 0 - }, - "contract_call": { - "p25": 0, - "p50": 0, - "p75": 0, - "p95": 0 - }, - "poison_microblock": { - "p25": 0, - "p50": 0, - "p75": 0, - "p95": 0 - } - }, - "tx_ages": { - "token_transfer": { - "p25": 0, - "p50": 0, - "p75": 0, - "p95": 0 - }, - "smart_contract": { - "p25": 0, - "p50": 0, - "p75": 0, - "p95": 0 - }, - "contract_call": { - "p25": 0, - "p50": 0, - "p75": 0, - "p95": 0 - }, - "poison_microblock": { - "p25": 0, - "p50": 0, - "p75": 0, - "p95": 0 - } - }, - "tx_byte_sizes": { - "token_transfer": { - "p25": 0, - "p50": 0, - "p75": 0, - "p95": 0 - }, - "smart_contract": { - "p25": 0, - "p50": 0, - "p75": 0, - "p95": 0 - }, - "contract_call": { - "p25": 0, - "p50": 0, - "p75": 0, - "p95": 0 - }, - "poison_microblock": { - "p25": 0, - "p50": 0, - "p75": 0, - "p95": 0 - } - } -} -``` - - - - - -```ts -/** - * GET request that returns stats on mempool transactions - */ -export interface MempoolTransactionStatsResponse { - /** - * Number of tranasction in the mempool, broken down by transaction type. - */ - tx_type_counts: { - token_transfer: number; - smart_contract: number; - contract_call: number; - poison_microblock: number; - }; - /** - * The simple mean (average) transaction fee, broken down by transaction type. Note that this does not factor in actual execution costs. The average fee is not a reliable metric for calculating a fee for a new transaction. - */ - tx_simple_fee_averages: { - token_transfer: { - p25: number; - p50: number; - p75: number; - p95: number; - }; - smart_contract: { - p25: number; - p50: number; - p75: number; - p95: number; - }; - contract_call: { - p25: number; - p50: number; - p75: number; - p95: number; - }; - poison_microblock: { - p25: number; - p50: number; - p75: number; - p95: number; - }; - }; - /** - * The average time (in blocks) that transactions have lived in the mempool. The start block height is simply the current chain-tip of when the attached Stacks node receives the transaction. This timing can be different across Stacks nodes / API instances due to propagation timing differences in the p2p network. - */ - tx_ages: { - token_transfer: { - p25: number; - p50: number; - p75: number; - p95: number; - }; - smart_contract: { - p25: number; - p50: number; - p75: number; - p95: number; - }; - contract_call: { - p25: number; - p50: number; - p75: number; - p95: number; - }; - poison_microblock: { - p25: number; - p50: number; - p75: number; - p95: number; - }; - }; - /** - * The average byte size of transactions in the mempool, broken down by transaction type. - */ - tx_byte_sizes: { - token_transfer: { - p25: number; - p50: number; - p75: number; - p95: number; - }; - smart_contract: { - p25: number; - p50: number; - p75: number; - p95: number; - }; - contract_call: { - p25: number; - p50: number; - p75: number; - p95: number; - }; - poison_microblock: { - p25: number; - p50: number; - p75: number; - p95: number; - }; - }; -} -``` - - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/transactions/transaction-events.mdx b/content/docs/stacks/api/transactions/transaction-events.mdx deleted file mode 100644 index 16c09d990..000000000 --- a/content/docs/stacks/api/transactions/transaction-events.mdx +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: Get transaction events -description: Retrieves events for a specific transaction. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Transaction Events - -Retrieves the list of events filtered by principal (STX address or Smart Contract ID), transaction id or event types. The list of event types is ('smart_contract_log', 'stx_lock', 'stx_asset', 'fungible_token_asset', 'non_fungible_token_asset'). -### Query Parameters - - - -Hash of transaction - - - - - -Stacks address or a Contract identifier - -Example: `"ST1HB64MAJ1MBV4CQ80GF01DZS4T1DSMX20ADCRA4"` - - - - - -number of items to return - -Example: `100` - - - - - -number of items to skip - -Example: `42000` - - - -"} required={false} deprecated={false}> - -Filter the events on event type - -Example: `"stx_lock"` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/tx/events?tx_id=string&address=ST1HB64MAJ1MBV4CQ80GF01DZS4T1DSMX20ADCRA4&limit=100&offset=42000&type=stx_lock" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/tx/events?tx_id=string&address=ST1HB64MAJ1MBV4CQ80GF01DZS4T1DSMX20ADCRA4&limit=100&offset=42000&type=stx_lock", { - method: "GET" -}); -``` - - - - - - - - - -GET event for the given transaction - - - - - -```json -{ - "limit": 0, - "offset": 0, - "results": [ - { - "event_index": 0, - "event_type": "smart_contract_log", - "tx_id": "string", - "contract_log": { - "contract_id": "string", - "topic": "string", - "value": { - "hex": "string", - "repr": "string" - } - } - } - ] -} -``` - - - - - -```ts -export type TransactionEvent = - | TransactionEventSmartContractLog - | TransactionEventStxLock - | TransactionEventStxAsset - | TransactionEventFungibleAsset - | TransactionEventNonFungibleAsset; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventSmartContractLog = AbstractTransactionEvent & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxLock = AbstractTransactionEvent & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxAsset = AbstractTransactionEvent & { - event_type: "stx_asset"; - tx_id: string; - asset: TransactionEventAsset; -}; -export type TransactionEventAssetType = "transfer" | "mint" | "burn"; -export type TransactionEventFungibleAsset = AbstractTransactionEvent & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type TransactionEventNonFungibleAsset = AbstractTransactionEvent & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; - -/** - * GET event for the given transaction - */ -export interface TransactionEventsResponse { - limit: number; - offset: number; - results: TransactionEvent[]; -} -export interface AbstractTransactionEvent { - event_index: number; -} -export interface TransactionEventAsset { - asset_event_type?: TransactionEventAssetType; - asset_id?: string; - sender?: string; - recipient?: string; - amount?: string; - value?: string; - memo?: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/transactions/transactions-by-block.mdx b/content/docs/stacks/api/transactions/transactions-by-block.mdx deleted file mode 100644 index a97518193..000000000 --- a/content/docs/stacks/api/transactions/transactions-by-block.mdx +++ /dev/null @@ -1,676 +0,0 @@ ---- -title: Get transactions by block -description: Retrieves transactions confirmed in a single block. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get transactions by block - -Retrieves transactions confirmed in a single block - -### Path Parameters - - - -filter by block height, hash, index block hash or the constant `latest` to filter for the most recent block - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of transactions | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v2/blocks/42000/transactions" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v2/blocks/42000/transactions", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns transactions - - - - - -```json -{ - "limit": 200, - "offset": 0, - "total": 0, - "results": [ - { - "tx_id": "string", - "nonce": 0, - "fee_rate": "string", - "sender_address": "string", - "sponsor_nonce": 0, - "sponsored": true, - "sponsor_address": "string", - "post_condition_mode": "allow", - "post_conditions": [ - { - "principal": { - "type_id": "principal_origin" - }, - "condition_code": "sent_equal_to", - "amount": "string", - "type": "stx" - } - ], - "anchor_mode": "on_chain_only", - "block_hash": "string", - "block_height": 0, - "block_time": 0, - "block_time_iso": "string", - "burn_block_height": 0, - "burn_block_time": 0, - "burn_block_time_iso": "string", - "parent_burn_block_time": 0, - "parent_burn_block_time_iso": "string", - "canonical": true, - "tx_index": 0, - "tx_status": "success", - "tx_result": { - "hex": "string", - "repr": "string" - }, - "event_count": 0, - "parent_block_hash": "string", - "is_unanchored": true, - "microblock_hash": "string", - "microblock_sequence": 0, - "microblock_canonical": true, - "execution_cost_read_count": 0, - "execution_cost_read_length": 0, - "execution_cost_runtime": 0, - "execution_cost_write_count": 0, - "execution_cost_write_length": 0, - "events": [ - { - "event_index": 0, - "event_type": "smart_contract_log", - "tx_id": "string", - "contract_log": { - "contract_id": "string", - "topic": "string", - "value": { - "hex": "string", - "repr": "string" - } - } - } - ], - "tx_type": "token_transfer", - "token_transfer": { - "recipient_address": "string", - "amount": "string", - "memo": "string" - } - } - ] -} -``` - - - - - -```ts -/** - * Describes all transaction types on Stacks 2.0 blockchain - */ -export type Transaction = - | TokenTransferTransaction - | SmartContractTransaction - | ContractCallTransaction - | PoisonMicroblockTransaction - | CoinbaseTransaction - | TenureChangeTransaction; -/** - * Describes representation of a Type-0 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-0-transferring-an-asset - */ -export type TokenTransferTransaction = AbstractTransaction & TokenTransferTransactionMetadata; -/** - * Anchored transaction metadata. All mined/anchored Stacks transactions have these properties. - */ -export type AbstractTransaction = BaseTransaction & { - /** - * Hash of the blocked this transactions was associated with - */ - block_hash: string; - /** - * Height of the block this transactions was associated with - */ - block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined. - */ - block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) indicating when this block was mined. - */ - block_time_iso: string; - /** - * Height of the anchor burn block. - */ - burn_block_height: number; - /** - * Unix timestamp (in seconds) indicating when this block was mined - */ - burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this block was mined. - */ - burn_block_time_iso: string; - /** - * Unix timestamp (in seconds) indicating when this parent block was mined - */ - parent_burn_block_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when this parent block was mined. - */ - parent_burn_block_time_iso: string; - /** - * Set to `true` if block corresponds to the canonical chain tip - */ - canonical: boolean; - /** - * Index of the transaction, indicating the order. Starts at `0` and increases with each transaction - */ - tx_index: number; - tx_status: TransactionStatus; - /** - * Result of the transaction. For contract calls, this will show the value returned by the call. For other transaction types, this will return a boolean indicating the success of the transaction. - */ - tx_result: { - /** - * Hex string representing the value fo the transaction result - */ - hex: string; - /** - * Readable string of the transaction result - */ - repr: string; - }; - /** - * Number of transaction events - */ - event_count: number; - /** - * Hash of the previous block. - */ - parent_block_hash: string; - /** - * True if the transaction is included in a microblock that has not been confirmed by an anchor block. - */ - is_unanchored: boolean; - /** - * The microblock hash that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be an empty string. - */ - microblock_hash: string; - /** - * The microblock sequence number that this transaction was streamed in. If the transaction was batched in an anchor block (not included within a microblock) then this value will be 2147483647 (0x7fffffff, the max int32 value), this value preserves logical transaction ordering on (block_height, microblock_sequence, tx_index). - */ - microblock_sequence: number; - /** - * Set to `true` if microblock is anchored in the canonical chain tip, `false` if the transaction was orphaned in a micro-fork. - */ - microblock_canonical: boolean; - /** - * Execution cost read count. - */ - execution_cost_read_count: number; - /** - * Execution cost read length. - */ - execution_cost_read_length: number; - /** - * Execution cost runtime. - */ - execution_cost_runtime: number; - /** - * Execution cost write count. - */ - execution_cost_write_count: number; - /** - * Execution cost write length. - */ - execution_cost_write_length: number; - /** - * List of transaction events - */ - events: TransactionEvent[]; -}; -export type PostConditionMode = "allow" | "deny"; -/** - * Post-conditionscan limit the damage done to a user's assets - */ -export type PostCondition = PostConditionStx | PostConditionFungible | PostConditionNonFungible; -export type PostConditionStx = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - amount: string; - type: "stx"; -}; -export type PostConditionPrincipal = - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_origin"; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_standard"; - address: string; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_contract"; - address: string; - contract_name: string; - }; -/** - * A fungible condition code encodes a statement being made for either STX or a fungible token, with respect to the originating account. - */ -export type PostConditionFungibleConditionCode = - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; -export type PostConditionFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - type: "fungible"; - amount: string; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -export type PostConditionNonFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionNonFungibleConditionCode; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -/** - * A non-fungible condition code encodes a statement being made about a non-fungible token, with respect to whether or not the particular non-fungible token is owned by the account. - */ -export type PostConditionNonFungibleConditionCode = "sent" | "not_sent"; -/** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ -export type TransactionAnchorModeType = "on_chain_only" | "off_chain_only" | "any"; -/** - * Status of the transaction - */ -export type TransactionStatus = "success" | "abort_by_response" | "abort_by_post_condition"; -export type TransactionEvent = - | TransactionEventSmartContractLog - | TransactionEventStxLock - | TransactionEventStxAsset - | TransactionEventFungibleAsset - | TransactionEventNonFungibleAsset; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventSmartContractLog = AbstractTransactionEvent & { - event_type: "smart_contract_log"; - tx_id: string; - contract_log: { - contract_id: string; - topic: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxLock = AbstractTransactionEvent & { - event_type: "stx_lock"; - tx_id: string; - stx_lock_event: { - locked_amount: string; - unlock_height: number; - locked_address: string; - }; -}; -/** - * Only present in `smart_contract` and `contract_call` tx types. - */ -export type TransactionEventStxAsset = AbstractTransactionEvent & { - event_type: "stx_asset"; - tx_id: string; - asset: TransactionEventAsset; -}; -export type TransactionEventAssetType = "transfer" | "mint" | "burn"; -export type TransactionEventFungibleAsset = AbstractTransactionEvent & { - event_type: "fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - amount: string; - }; -}; -export type TransactionEventNonFungibleAsset = AbstractTransactionEvent & { - event_type: "non_fungible_token_asset"; - tx_id: string; - asset: { - asset_event_type: string; - asset_id: string; - sender: string; - recipient: string; - value: { - hex: string; - repr: string; - }; - }; -}; -/** - * Describes representation of a Type-1 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export type SmartContractTransaction = AbstractTransaction & SmartContractTransactionMetadata; -/** - * Describes representation of a Type 2 Stacks 2.0 transaction: Contract Call - */ -export type ContractCallTransaction = AbstractTransaction & ContractCallTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type PoisonMicroblockTransaction = AbstractTransaction & PoisonMicroblockTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type CoinbaseTransaction = AbstractTransaction & CoinbaseTransactionMetadata; -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export type TenureChangeTransaction = AbstractTransaction & TenureChangeTransactionMetadata; - -/** - * GET request that returns transactions - */ -export interface TransactionResults { - /** - * The number of transactions to return - */ - limit: number; - /** - * The number to transactions to skip (starting at `0`) - */ - offset: number; - /** - * The number of transactions available - */ - total: number; - results: Transaction[]; -} -/** - * Transaction properties that are available from a raw serialized transactions. These are available for transactions in the mempool as well as mined transactions. - */ -export interface BaseTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: PostConditionMode; - post_conditions: PostCondition[]; - anchor_mode: TransactionAnchorModeType; -} -export interface AbstractTransactionEvent { - event_index: number; -} -export interface TransactionEventAsset { - asset_event_type?: TransactionEventAssetType; - asset_id?: string; - sender?: string; - recipient?: string; - amount?: string; - value?: string; - memo?: string; -} -/** - * Metadata associated with token-transfer type transactions - */ -export interface TokenTransferTransactionMetadata { - tx_type: "token_transfer"; - token_transfer: { - recipient_address: string; - /** - * Transfer amount as Integer string (64-bit unsigned integer) - */ - amount: string; - /** - * Hex encoded arbitrary message, up to 34 bytes length (should try decoding to an ASCII string) - */ - memo: string; - }; -} -/** - * Metadata associated with a contract-deploy type transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export interface SmartContractTransactionMetadata { - tx_type: "smart_contract"; - smart_contract: { - /** - * The Clarity version of the contract, only specified for versioned contract transactions, otherwise null - */ - clarity_version?: number; - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Clarity code of the smart contract being deployed - */ - source_code: string; - }; -} -/** - * Metadata associated with a contract-call type transaction - */ -export interface ContractCallTransactionMetadata { - tx_type: "contract_call"; - contract_call: { - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Name of the Clarity function to be invoked - */ - function_name: string; - /** - * Function definition, including function name and type as well as parameter names and types - */ - function_signature: string; - /** - * List of arguments used to invoke the function - */ - function_args?: { - hex: string; - repr: string; - name: string; - type: string; - }[]; - }; -} -/** - * Metadata associated with a poison-microblock type transaction - */ -export interface PoisonMicroblockTransactionMetadata { - tx_type: "poison_microblock"; - poison_microblock: { - /** - * Hex encoded microblock header - */ - microblock_header_1: string; - /** - * Hex encoded microblock header - */ - microblock_header_2: string; - }; -} -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export interface CoinbaseTransactionMetadata { - tx_type: "coinbase"; - coinbase_payload: { - /** - * Hex encoded 32-byte scratch space for block leader's use - */ - data: string; - /** - * A principal that will receive the miner rewards for this coinbase transaction. Can be either a standard principal or contract principal. Only specified for `coinbase-to-alt-recipient` transaction types, otherwise null. - */ - alt_recipient?: string; - /** - * Hex encoded 80-byte VRF proof - */ - vrf_proof?: string; - }; -} -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export interface TenureChangeTransactionMetadata { - tx_type: "tenure_change"; - tenure_change_payload?: { - /** - * Consensus hash of this tenure. Corresponds to the sortition in which the miner of this block was chosen. - */ - tenure_consensus_hash: string; - /** - * Consensus hash of the previous tenure. Corresponds to the sortition of the previous winning block-commit. - */ - prev_tenure_consensus_hash: string; - /** - * Current consensus hash on the underlying burnchain. Corresponds to the last-seen sortition. - */ - burn_view_consensus_hash: string; - /** - * (Hex string) Stacks Block hash - */ - previous_tenure_end: string; - /** - * The number of blocks produced in the previous tenure. - */ - previous_tenure_blocks: number; - /** - * Cause of change in mining tenure. Depending on cause, tenure can be ended or extended. - */ - cause: "block_found" | "extended"; - /** - * (Hex string) The ECDSA public key hash of the current tenure. - */ - pubkey_hash: string; - }; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/transactions/transactions-for-address.mdx b/content/docs/stacks/api/transactions/transactions-for-address.mdx deleted file mode 100644 index c394b180f..000000000 --- a/content/docs/stacks/api/transactions/transactions-for-address.mdx +++ /dev/null @@ -1,486 +0,0 @@ ---- -title: Get transactions for address -description: Retrieves transactions for a specific address. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Transactions for address - -Retrieves all transactions for a given address that are currently in mempool -### Path Parameters - - - -Transactions for the address - -Example: `"SP197DVH8KTJGX4STM61QN0WJV8Y9QJWXV83ZGNR9"` - - -### Query Parameters - - - -max number of transactions to fetch - -Example: `90` - - - - - -index of first transaction to fetch - -Example: `42000` - - - - - -Include transaction data from unanchored (i.e. unconfirmed) microblocks - -Example: `true` - -Default: `false` - - - -| Status code | Description | -| :------ | :------ | -| `200` | List of Transactions | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/extended/v1/address/SP197DVH8KTJGX4STM61QN0WJV8Y9QJWXV83ZGNR9/mempool?limit=90&offset=42000&unanchored=true" -``` - - - - - -```js -fetch("https://api.hiro.so/extended/v1/address/SP197DVH8KTJGX4STM61QN0WJV8Y9QJWXV83ZGNR9/mempool?limit=90&offset=42000&unanchored=true", { - method: "GET" -}); -``` - - - - - - - - - -GET request that returns transactions - - - - - -```json -{ - "limit": 0, - "offset": 0, - "total": 0, - "results": [ - { - "tx_id": "string", - "nonce": 0, - "fee_rate": "string", - "sender_address": "string", - "sponsor_nonce": 0, - "sponsored": true, - "sponsor_address": "string", - "post_condition_mode": "allow", - "post_conditions": [ - { - "principal": { - "type_id": "principal_origin" - }, - "condition_code": "sent_equal_to", - "amount": "string", - "type": "stx" - } - ], - "anchor_mode": "on_chain_only", - "tx_status": "pending", - "receipt_time": 0, - "receipt_time_iso": "string", - "tx_type": "token_transfer", - "token_transfer": { - "recipient_address": "string", - "amount": "string", - "memo": "string" - } - } - ] -} -``` - - - - - -```ts -/** - * Describes all transaction types on Stacks 2.0 blockchain - */ -export type MempoolTransaction = - | MempoolTokenTransferTransaction - | MempoolSmartContractTransaction - | MempoolContractCallTransaction - | MempoolPoisonMicroblockTransaction - | MempoolCoinbaseTransaction - | MempoolTenureChangeTransaction; -/** - * Describes representation of a Type-0 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-0-transferring-an-asset - */ -export type MempoolTokenTransferTransaction = AbstractMempoolTransaction & TokenTransferTransactionMetadata; -/** - * Abstract transaction. This schema makes up all properties common between all Stacks 2.0 transaction types - */ -export type AbstractMempoolTransaction = BaseTransaction & { - tx_status: MempoolTransactionStatus; - /** - * A unix timestamp (in seconds) indicating when the transaction broadcast was received by the node. - */ - receipt_time: number; - /** - * An ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) timestamp indicating when the transaction broadcast was received by the node. - */ - receipt_time_iso: string; -}; -export type PostConditionMode = "allow" | "deny"; -/** - * Post-conditionscan limit the damage done to a user's assets - */ -export type PostCondition = PostConditionStx | PostConditionFungible | PostConditionNonFungible; -export type PostConditionStx = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - amount: string; - type: "stx"; -}; -export type PostConditionPrincipal = - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_origin"; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_standard"; - address: string; - } - | { - /** - * String literal of type `PostConditionPrincipalType` - */ - type_id: "principal_contract"; - address: string; - contract_name: string; - }; -/** - * A fungible condition code encodes a statement being made for either STX or a fungible token, with respect to the originating account. - */ -export type PostConditionFungibleConditionCode = - | "sent_equal_to" - | "sent_greater_than" - | "sent_greater_than_or_equal_to" - | "sent_less_than" - | "sent_less_than_or_equal_to"; -export type PostConditionFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionFungibleConditionCode; - type: "fungible"; - amount: string; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -export type PostConditionNonFungible = { - principal: PostConditionPrincipal; -} & { - condition_code: PostConditionNonFungibleConditionCode; - type: "non_fungible"; - asset_value: { - hex: string; - repr: string; - }; - asset: { - asset_name: string; - contract_address: string; - contract_name: string; - }; -}; -/** - * A non-fungible condition code encodes a statement being made about a non-fungible token, with respect to whether or not the particular non-fungible token is owned by the account. - */ -export type PostConditionNonFungibleConditionCode = "sent" | "not_sent"; -/** - * `on_chain_only`: the transaction MUST be included in an anchored block, `off_chain_only`: the transaction MUST be included in a microblock, `any`: the leader can choose where to include the transaction. - */ -export type TransactionAnchorModeType = "on_chain_only" | "off_chain_only" | "any"; -/** - * Status of the transaction - */ -export type MempoolTransactionStatus = - | "pending" - | "dropped_replace_by_fee" - | "dropped_replace_across_fork" - | "dropped_too_expensive" - | "dropped_stale_garbage_collect" - | "dropped_problematic"; -/** - * Describes representation of a Type-1 Stacks 2.0 transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export type MempoolSmartContractTransaction = AbstractMempoolTransaction & SmartContractTransactionMetadata; -/** - * Describes representation of a Type 2 Stacks 2.0 transaction: Contract Call - */ -export type MempoolContractCallTransaction = AbstractMempoolTransaction & ContractCallTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type MempoolPoisonMicroblockTransaction = AbstractMempoolTransaction & PoisonMicroblockTransactionMetadata; -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export type MempoolCoinbaseTransaction = AbstractMempoolTransaction & CoinbaseTransactionMetadata; -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export type MempoolTenureChangeTransaction = AbstractMempoolTransaction & TenureChangeTransactionMetadata; - -/** - * GET request that returns transactions - */ -export interface MempoolTransactionListResponse { - limit: number; - offset: number; - total: number; - results: MempoolTransaction[]; -} -/** - * Transaction properties that are available from a raw serialized transactions. These are available for transactions in the mempool as well as mined transactions. - */ -export interface BaseTransaction { - /** - * Transaction ID - */ - tx_id: string; - /** - * Used for ordering the transactions originating from and paying from an account. The nonce ensures that a transaction is processed at most once. The nonce counts the number of times an account's owner(s) have authorized a transaction. The first transaction from an account will have a nonce value equal to 0, the second will have a nonce value equal to 1, and so on. - */ - nonce: number; - /** - * Transaction fee as Integer string (64-bit unsigned integer). - */ - fee_rate: string; - /** - * Address of the transaction initiator - */ - sender_address: string; - sponsor_nonce?: number; - /** - * Denotes whether the originating account is the same as the paying account - */ - sponsored: boolean; - sponsor_address?: string; - post_condition_mode: PostConditionMode; - post_conditions: PostCondition[]; - anchor_mode: TransactionAnchorModeType; -} -/** - * Metadata associated with token-transfer type transactions - */ -export interface TokenTransferTransactionMetadata { - tx_type: "token_transfer"; - token_transfer: { - recipient_address: string; - /** - * Transfer amount as Integer string (64-bit unsigned integer) - */ - amount: string; - /** - * Hex encoded arbitrary message, up to 34 bytes length (should try decoding to an ASCII string) - */ - memo: string; - }; -} -/** - * Metadata associated with a contract-deploy type transaction. https://github.com/blockstack/stacks-blockchain/blob/master/sip/sip-005-blocks-and-transactions.md#type-1-instantiating-a-smart-contract - */ -export interface SmartContractTransactionMetadata { - tx_type: "smart_contract"; - smart_contract: { - /** - * The Clarity version of the contract, only specified for versioned contract transactions, otherwise null - */ - clarity_version?: number; - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Clarity code of the smart contract being deployed - */ - source_code: string; - }; -} -/** - * Metadata associated with a contract-call type transaction - */ -export interface ContractCallTransactionMetadata { - tx_type: "contract_call"; - contract_call: { - /** - * Contract identifier formatted as `.` - */ - contract_id: string; - /** - * Name of the Clarity function to be invoked - */ - function_name: string; - /** - * Function definition, including function name and type as well as parameter names and types - */ - function_signature: string; - /** - * List of arguments used to invoke the function - */ - function_args?: { - hex: string; - repr: string; - name: string; - type: string; - }[]; - }; -} -/** - * Metadata associated with a poison-microblock type transaction - */ -export interface PoisonMicroblockTransactionMetadata { - tx_type: "poison_microblock"; - poison_microblock: { - /** - * Hex encoded microblock header - */ - microblock_header_1: string; - /** - * Hex encoded microblock header - */ - microblock_header_2: string; - }; -} -/** - * Describes representation of a Type 3 Stacks 2.0 transaction: Poison Microblock - */ -export interface CoinbaseTransactionMetadata { - tx_type: "coinbase"; - coinbase_payload: { - /** - * Hex encoded 32-byte scratch space for block leader's use - */ - data: string; - /** - * A principal that will receive the miner rewards for this coinbase transaction. Can be either a standard principal or contract principal. Only specified for `coinbase-to-alt-recipient` transaction types, otherwise null. - */ - alt_recipient?: string; - /** - * Hex encoded 80-byte VRF proof - */ - vrf_proof?: string; - }; -} -/** - * Describes representation of a Type 7 Stacks transaction: Tenure Change - */ -export interface TenureChangeTransactionMetadata { - tx_type: "tenure_change"; - tenure_change_payload?: { - /** - * Consensus hash of this tenure. Corresponds to the sortition in which the miner of this block was chosen. - */ - tenure_consensus_hash: string; - /** - * Consensus hash of the previous tenure. Corresponds to the sortition of the previous winning block-commit. - */ - prev_tenure_consensus_hash: string; - /** - * Current consensus hash on the underlying burnchain. Corresponds to the last-seen sortition. - */ - burn_view_consensus_hash: string; - /** - * (Hex string) Stacks Block hash - */ - previous_tenure_end: string; - /** - * The number of blocks produced in the previous tenure. - */ - previous_tenure_blocks: number; - /** - * Cause of change in mining tenure. Depending on cause, tenure can be ended or extended. - */ - cause: "block_found" | "extended"; - /** - * (Hex string) The ECDSA public key hash of the current tenure. - */ - pubkey_hash: string; - }; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/api/txs.mdx b/content/docs/stacks/api/txs.mdx deleted file mode 100644 index 8c61e7a3c..000000000 --- a/content/docs/stacks/api/txs.mdx +++ /dev/null @@ -1,596 +0,0 @@ ---- -title: Transactions -description: Learn about transactions on the Stacks blockchain. ---- - -Transactions are the fundamental unit of execution in the Stacks blockchain. Each transaction is originated from a [Stacks account](https://docs.stacks.co/stacks-101/accounts), and is retained in the Stacks blockchain. This guide helps you understand Stacks transactions. - -### Lifecycle - -Transactions go through phases before being finally confirmed and propagated on the Stacks network. - -- **Generate**: Transactions are assembled according to the encoding specification. -- **Validate and sign**: Transactions are validated to confirm they are well-formed. Required signatures are filled in. -- **Broadcast**: Transactions are sent to a node. -- **Register**: A miner receives transactions, verifies, and adds them to the ["mempool"](https://academy.binance.com/en/glossary/mempool), a holding area for all the pending transactions. -- **Process**: Miners review the mempool and select transactions to be included in the next block. Depending on the transaction type, different actions can happen during this step. For example, post-conditions could be verified for a token transfer, tokens defined in a smart contract could be minted, or an attempt to call an existing smart contract method could be made. -- **Confirm**: Miners successfully mine blocks, with each block containing a set of transactions. The transactions inside each new block are successfully propagated to the network. - - -A transaction can have one of three states once it is registered: `pending`, `success`, or `failed`. - - -### Types - -Stacks supports a set of different transaction types: - -| **Type** | **Value** | **Description** | -| :----------------- | :------------------- | :--------------- | -| Coinbase | _json`"coinbase"`_ | The first transaction in a new block. | -| Token transfer | _json`"token_transfer"`_ | Asset transfer from a sender to a recipient. | -| Contract deploy | _json`"smart_contract"`_ | Contract instantiation. | -| Contract call | _json`"contract_call"`_ | Contract call for a public, non read-only function. | - -A sample of each transaction type can be found in the [Stacks Blockchain API response definition for transactions](https://docs.hiro.so/api#operation/get_transaction_by_id). - - -Read-only contract call calls do **not** require transactions. Read more about it in the [network guide](https://docs.stacks.co/stacks-101/network#read-only-function-calls). - - -### Anchor mode - - -Microblocks are being deprecated with the Nakamoto upgrade. - - -Transactions can be mined either in an anchor block or in a [microblock](https://docs.stacks.co/stacks-101/mining#microblocks). If microblocks -are selected, the transaction can be confirmed with a lower latency than the anchor block time. - -The anchor mode enum has three options: - -- `OnChainOnly` The transaction must be included in an anchored block. -- `OffChainOnly`: The transaction must be included in a microblock. -- `Any`: The leader can choose where to include the transaction. - -Here is an example where the transaction must be included in a microblock: - -```js -import { AnchorMode, makeSTXTokenTransfer } from '@stacks/transactions'; -import { StacksTestnet, StacksMainnet } from '@stacks/network'; - -const BigNum = require('bn.js'); - -const txOptions = { - recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159', - amount: new BigNum(12345), - senderKey: 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01', - network: new StacksTestnet(), // for mainnet, use `StacksMainnet()` - anchorMode: AnchorMode.OffChainOnly, // must be included in a microblock -}; - -const transaction = await makeSTXTokenTransfer(txOptions); -``` - -### Post-conditions - -Transaction post-conditions are a feature meant to limit the damage malicious smart contract developers and smart contract bugs can do in terms of destroying (or taking) a user's assets. Post-conditions are executed whenever a contract is deployed or a public method of an existing contract is executed. Whenever a post-condition fails, the transaction is forced to abort. - -Post-conditions are meant to be added by the user (or by the user's wallet software) at the moment they sign a transaction. For example, a user may append a post-condition saying that upon successful execution, their account's Stacks (STX) balance should have decreased by no more than 1 STX. If this is not the case, then the transaction would abort, and the account would only pay the transaction fee of processing it. - - -Read more about post-conditions [here](/stacks/stacks.js/concepts/post-conditions). - - -### Attributes - -Each transaction includes a field that describes zero or more post-conditions that must all be true when the transaction finishes running. The post-condition describes only properties of the owner of the asset before the transaction happened. For a transfer transaction, the post-condition is about the sender, for a burn transaction, the post-condition is about the previous owner. - -A post-condition includes the following information: - -| **Attribute** | **Sample** | **Description** | -| ------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------ | -| Principal | `SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE` | Original owner of the asset, can be a Stacks address or a smart contract | -| Asset id | `STX` | Asset to apply conditions to (could be STX, fungible, or non-fungible tokens) | -| Comparator | `>=` | Compare operation to be applied (could define "how much" or "whether or not the asset is owned") | -| Literal | `1000000` | Use a number or true/false value to check if the asset meets the condition | - -### Evaluation modes - -The Stacks blockchain supports an `allow` or `deny` mode for evaluating post-conditions: - -- **Allow**: Other asset transfers not covered by post-conditions are permitted. -- **Deny**: No other asset transfers are permitted besides those named in post-conditions. - -### Authorization - -Transactions can be authorized in two ways: _standard_ and _sponsored_. Authorization determines whether or not the originating account is also the paying account. In a transaction with a standard authorization, the origin and paying accounts are the same. In a transaction with a sponsored authorization, the origin and paying accounts are distinct, and both accounts must sign the transaction for it to be valid (first the origin, then the spender). - -**Sponsored transactions** enable developers and/or infrastructure operators to pay for users to call into their smart contracts, even if users do not have the Stacks (STX) to do so. - -In a sponsored transaction, the user first signs the transaction with their origin account and with the intent of it being sponsored (that is, the user must explicitly allow a sponsor to sign), and then the sponsor signs the transaction with their paying account to pay for the user's transaction fee. - -### Encoding - -A transaction includes the following information. Multiple-byte fields are encoded as big-endian. - -| **Type** | **Description** | -| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Version number | Network version: `0x80` for testnet, `0x0` for mainnet | -| Chain ID | Chain instance ID: `0x80000000` for testnet, `0x00000001` for mainnet | -| Authorization | Type of authorization: (`0x04` for standard, `0x05` for sponsored) and [spending conditions](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-authorization) | -| Post-conditions | List of post-conditions, each including a [type ID and variable-length condition body](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-post-conditions-1) | -| Payload | Transaction type and variable-length [payload](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-payloads-1) | - -### Construction - -The easiest way to construct well-formed transactions is by [using the Stacks.js Transactions library](/stacks/stacks.js/packages/transactions). With that library, you can construct the following transaction types: - -- Stacks token transfer -- Smart contract deploy -- Smart contract function call - -When constructing transactions, it is required to set the network the transaction is intended for. This can be either mainnet or testnet. - - -Transactions can be constructed and serialized offline. However, it is required to know the nonce and estimated fees ahead of time. Once internet access is available, the transaction can be broadcast to the network. Keep in mind that the nonce and fee might change during offline activity, making the transaction invalid. - - -### Stacks token transfer - -```js -import { makeSTXTokenTransfer } from '@stacks/transactions'; -import { StacksTestnet, StacksMainnet } from '@stacks/network'; - -const BigNum = require('bn.js'); - -const txOptions = { - recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159', - amount: new BigNum(12345), - senderKey: 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01', - network: new StacksTestnet(), // for mainnet, use `StacksMainnet()` - memo: 'test memo', - nonce: new BigNum(0), // set a nonce manually if you don't want builder to fetch from a Stacks node - fee: new BigNum(200), // set a tx fee if you don't want the builder to estimate -}; - -const transaction = await makeSTXTokenTransfer(txOptions); -``` - - -Read more about [nonces](https://docs.stacks.co/stacks-101/network#nonces) in the network guide. - - -#### Smart contract deployment - -```js -import { makeContractDeploy } from '@stacks/transactions'; -import { StacksTestnet, StacksMainnet } from '@stacks/network'; -const BigNum = require('bn.js'); - -const txOptions = { - contractName: 'contract_name', - codeBody: fs.readFileSync('/path/to/contract.clar').toString(), - senderKey: 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01', - network: new StacksTestnet(), // for mainnet, use `StacksMainnet()` -}; - -const transaction = await makeContractDeploy(txOptions); -``` - -#### Smart contract function call - -```js -import { makeContractCall, BufferCV } from '@stacks/transactions'; -import { StacksTestnet, StacksMainnet } from '@stacks/network'; - -const BigNum = require('bn.js'); - -const txOptions = { - contractAddress: 'SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X', - contractName: 'contract_name', - functionName: 'contract_function', - functionArgs: [bufferCVFromString('foo')], - senderKey: 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01', - // attempt to fetch this contract's interface and validate the provided functionArgs - validateWithAbi: true, - network: new StacksTestnet(), // for mainnet, use `StacksMainnet()` -}; - -const transaction = await makeContractCall(txOptions); -``` - -### Clarity value types - -Building transactions that call functions in deployed Clarity contracts requires you to construct valid Clarity values to pass to the function as arguments. The [Clarity type system](https://github.com/stacksgov/sips/blob/main/sips/sip-002/sip-002-smart-contract-language.md#clarity-type-system) contains the following types: - -| Type | Declaration | Description | -| ---------------- | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Tuple | `(tuple (key-name-0 key-type-0) ...)` | Typed tuple with named fields | -| List | `(list max-len entry-type)` | List of maximum length `max-len`, with entries of type entry-type | -| Response | `(response ok-type err-type)` | Object used by public functions to commit their changes or abort. May be returned or used by other functions as well, however, only public functions have the commit/abort behavior | -| Optional | `(optional some-type)` | Option type for objects that can either be (some value) or none | -| Buffer | `(buff max-len)` | Byte buffer with maximum length `max-len` | -| Principal | `principal` | Object representing a principal (whether a contract principal or standard principal) | -| Boolean | `bool` | Boolean value ('true or 'false) | -| Signed Integer | `int` | Signed 128-bit integer | -| Unsigned Integer | `uint` | Unsigned 128-bit integer | -| ASCII String | `(define-data-var my-str (string-ascii 11) "hello world")` | String value encoded in ASCII | -| UTF-8 String | `(define-data-var my-str (string-utf8 7) u"hello \u{1234}")` | String value encoded in UTF-8 | - -The [Stacks.js Transactions library](/stacks/stacks.js/packages/transactions) contains TypeScript types and classes that map to the Clarity types, in order to make it easy to construct well-typed Clarity values in JavaScript. These types all extend the abstract class `ClarityValue`. - -Here are samples for Clarity value constructions using this library: - -```js -// construct boolean Clarity values -const t = trueCV(); -const f = falseCV(); - -// construct optional Clarity values -const nothing = noneCV(); -const something = someCV(t); - -// construct a buffer Clarity value from an existing buffer -const buffer = Buffer.from('foo'); -const bufCV = bufferCV(buffer); - -// construct signed and unsigned integer Clarity values -const i = intCV(-10); -const u = uintCV(10); - -// construct principal Clarity values -const address = 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B'; -const contractName = 'contract-name'; -const spCV = standardPrincipalCV(address); -const cpCV = contractPrincipalCV(address, contractName); - -// construct response Clarity values -const errCV = responseErrorCV(trueCV()); -const okCV = responseOkCV(falseCV()); - -// construct tuple Clarity values -const tupCV = tupleCV({ - a: intCV(1), - b: trueCV(), - c: falseCV(), -}); - -// construct list Clarity values -const l = listCV([trueCV(), falseCV()]); -``` - -If you develop in TypeScript, the type checker can help prevent you from creating wrongly-typed Clarity values. For example, the following code won't compile since lists are homogeneous in Clarity (meaning they can only contain values of a single type). It is important to include the type variable `BooleanCV` in this example; otherwise the TypeScript type checker won't know which type the list is of and won't enforce homogeneity. - -```js -const l = listCV < BooleanCV > [trueCV(), intCV(1)]; -``` - -#### Setting post-conditions - -The Stacks.js Transactions library supports the construction of post-conditions. - -Here is an example of a post-condition that ensures an account's balance will only decrease by no more than 1 STX: - -```js -const account = 'SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE'; -const comparator = FungibleConditionCode.GreaterEqual; -// assuming the Stacks (STX) balance before the transaction is 12346 -const amount = new BigNum(12345); - -const standardSTXPostCondition = makeStandardSTXPostCondition( - account, - comparator, - amount -); - -const txOptions = { - ..., // other transaction options - postConditions: [standardSTXPostCondition] -} - -const transaction = await makeContractCall(txOptions); -``` - -### Serialization - -A well-formed transaction construct is encoded in [Recursive Length Prefix ("RLP")](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp). RLP encoding results in a variable-sized byte array. - -In order to broadcast transactions to and between nodes on the network, RLP data is represented in hexadecimal string (also called the **raw format**). - - -To support an API-friendly and human-readable representation, the Stacks Blockchain API converts transactions into a JSON format. - - -[The Stacks.js Transactions library](/stacks/stacks.js/packages/transactions) supports serialization of transactions. - -#### Raw format - -Broadcasting transactions directly to the Stacks Blockchain API or Node RPC API requires the transaction to be serialized and in hexadecimal representation. - -```js -// to see the raw serialized tx -const serializedTx = transaction.serialize().toString('hex'); - -console.log(serializedTx); -``` - -The preceding method returns the following string: - -```terminal -$ 8080000000040015c31b8c1c11c515e244b75806bac48d1399c77500000000000000000000000000000000000127e88a68dce8689fc94ff4c186bf8966f8d544c5129ff84d95a2459b5e8e7c39430388f6c8f85cce8c9ce5e6ec1e157116ca4a67d65ab53768b25d5fb5831939030200000000000516df0ba3e79792be7be5e50a370289accfc8c9e03200000000000f424068656c6c6f20776f726c640000000000000000000000000000000000000000000000 -``` - -Transaction IDs are generated by hashing the raw transaction with [sha512/256](https://eprint.iacr.org/2010/548.pdf) - -#### JSON format - -When called the Stacks Blockchain API or Node RPC API, transactions returned will be serialized in a JSON format. Here is a token transfer transaction: - -```js -{ - "tx_id": "0x77cb1bf0804f09ad24b4c494a6c00d5b10bb0afbb94a0d646fa9640eff338e37", - "nonce": 5893, - "fee_rate": "180", - "sender_address": "STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6", - "sponsored": false, - "post_condition_mode": "deny", - "post_conditions": [], - "anchor_mode": "any", - "block_hash": "0xf1e54a3acd04232f1362c09d5096b095363158348303396ea5fc5092e1d8788f", - "parent_block_hash": "0x3de356eb5afa5d7b781f6a925d31d69d218b772ec995930b4e15d92bd15443f9", - "block_height": 13984, - "burn_block_time": 1622678407, - "burn_block_time_iso": "2021-06-03T00:00:07.000Z", - "canonical": true, - "tx_index": 2, - "tx_status": "success", - "tx_result": { - "hex": "0x0703", - "repr": "(ok true)" - }, - "microblock_hash": "", - "microblock_sequence": 2147483647, - "microblock_canonical": true, - "event_count": 1, - "events": [], - "tx_type": "token_transfer", - "token_transfer": { - "recipient_address": "STZ4C5RT4WH4JGRQA5E0ZF5PPSQCVY1WRB6E2CGW", - "amount": "500000000", - "memo": "0x46617563657400000000000000000000000000000000000000000000000000000000" - } -} -``` - -#### Deserializing - -Serialized, raw transactions can be deserialized without access to the internet using [the Stacks.js Transactions library](/stacks/stacks.js/packages/transactions): - -```js -import { BufferReader, deserializeTransaction } from '@stacks/transactions'; - -// receive raw transaction -const serializedTx = '808000000...'; - -const bufferReader = new BufferReader(Buffer.from(serializedTx)); -const deserializedTx = deserializeTransaction(bufferReader); - -// print memo -console.log(deserializedTx.payload.memo.content); -``` - -### Signature and verification - -Every transaction contains verifiable signatures that certify its authenticity. These signatures are generated by signing the transaction hash with the origin's private key. The Elliptic Curve Digital Signature Algorithm (ECDSA) is used for signing, with the curve set to secp256k1. The internal structure that encapsulates the signature is the spending condition. Spending conditions include several parameters, such as the public key hash, nonce, fee rate and the recoverable ECDSA signature. - -When constructing a transaction using Stacks.js, you can supply the private key and signing will be completed automatically. If you would like to sign the transaction manually, use the `TransactionSigner` class. - -Below are the steps taken to generate the signature internal to the transaction library. - -#### Signing steps - -1. Generate a transaction hash for signing. This is the SHA512/256 digest of the serialized transaction before a signature is added. -2. Append the authorization type, fee amount and nonce to the transaction hash to create the signature hash. -3. Generate the SHA512/256 hash of the resulting string from the previous step. -4. Sign the hash using ECDSA and the origin private key. -5. Add the resulting recoverable ECDSA signature to the transaction spending condition. - -#### Single signature transactions - -As the name implies, a single signature transaction contains 1 signature from the origin account that authorizes a token spend or smart contract deploy/execution. - -#### Multi-signature transactions - -For multi-sig accounts, multiple keys must sign the transaction for it to be valid. - -#### Sponsored transactions - -A sponsored transaction is one where a second signer sets and pays the transaction fees. The origin must sign the transaction first before the sponsor signs. - -### Broadcast - -With a serialized transaction in the [raw format](#raw-format), it can be broadcast to the network using the [`POST /v2/transactions`](/stacks/api/transactions/broadcast-transaction) endpoint: - -```terminal -$ curl --location --request POST 'https://api.testnet.hiro.so/v2/transactions' \ ---header 'Content-Type: application/octet-stream' \ ---data-raw '' -``` - -The API will respond with a `HTTP 200 - OK` if the transaction was successfully added to the mempool. - -There is no explicit time constraint between the construction of a valid signed transaction and when it can be broadcast. There are, however, some constraints to be aware of. The following reasons can deem a transaction invalid after some period: - -- **Token transfer**: Nonce changed in-between construction and broadcast -- **Contract call or deploy**: Block height is evaluated (with [`at-block`](https://docs.stacks.co/clarity/functions#at-block)) and changed in-between construction and broadcast - -### Mempool - -Once a transaction has been successfully broadcast to the network, the transaction is added to the mempool of the node -that received the broadcast. From the [Bitcoin wiki][]: "a node's memory pool contains all 0-confirmation transactions -across the entire network that that particular node knows about." - -So, the set of transactions in the mempool might be -different for each node in the network. For example, when you query the mempool endpoints on -`api.mainnet.hiro.so`, the response reflects the set of unconfirmed transactions known to the nodes that -service that API. - -Miners can employ different heuristics and strategies for deciding which transactions to admit into the mempool and -which transactions to include from the mempool when mining a block. Some transactions may be rejected outright (for -example, if there are insufficient funds at an address) while others might be accepted into the mempool, but not mined -into a block indefinitely (for example, if the transaction fees are too low). - -Transactions that are admitted in the mempool but not yet -mined are said to be "pending." The current implementation of [stacks-blockchain](https://github.com/stacks-network/stacks-core) discards pending mempool -transactions after [256 blocks][]. - -#### Best practices - -- **Nonce**: It's crucial that transactions use the correct nonce. Using an incorrect nonce makes it less likely that - the transaction is mined in a timely manner. To determine the correct nonce, query the [`accounts`][] endpoint of - the node you intend to broadcast your transaction to. The value of the `nonce` field in the response is the next nonce - that the node expects to consume for that account. Nonce starts at `0`, so the first transaction from an account should - be set to `nonce=0`. -- **Transaction chaining**: Even when using the correct nonce, transactions might arrive at a node out-of-order. For - instance, a transaction with `nonce=1` may arrive in the mempool before a `nonce=0` transaction. Stacks nodes admit - such out-of-order transactions in the mempool, but only up to a limit ([25 in the current implementation][]). So, you - should limit any chain of unconfirmed transactions from a single account to less than 25. Making this limit higher has - downsides, discussed in [this issue](https://github.com/blockstack/stacks-blockchain/issues/2384). If you need to send - more than 25 transactions per block, consider using multiple accounts or a smart-contract based approach. See - [this tool](https://www.npmjs.com/package/@stacks/send-many-stx-cli), for example, that allows up to 200 token - transfers in a single transaction. - -### Querying - -Transactions on the Stacks network can be queried using the Stacks Blockchain API. The API exposes two interfaces, a RESTful JSON API and a WebSockets API. - - -The API can be easily consumed using a generated [JS client library](https://hirosystems.github.io/stacks-blockchain-api/client/index.html). The generator uses an OpenAPI specification and supports other languages and frameworks. - - -#### Get recent transactions - -Recent transactions can be obtained through the [`GET /extended/v1/tx`](/stacks/api/transactions/recent-transactions) endpoint: - -```terminal -$ curl 'https://api.testnet.hiro.so/extended/v1/tx' -``` - -Sample response: - -```js -{ - "limit": 10, - "offset": 0, - "total": 101922, - "results": [ - { - "tx_id": "0x5e9f3933e358df6a73fec0d47ce3e1062c20812c129f5294e6f37a8d27c051d9", - "tx_status": "success", - "tx_type": "coinbase", - "fee_rate": "0", - "sender_address": "ST3WCQ6S0DFT7YHF53M8JPKGDS1N1GSSR91677XF1", - "sponsored": false, - "post_condition_mode": "deny", - "block_hash": "0x58412b50266debd0c35b1a20348ad9c0f17e5525fb155a97033256c83c9e2491", - "block_height": 3231, - "burn_block_time": 1594230455, - "canonical": true, - "tx_index": 0, - "coinbase_payload": { - "data": "0x0000000000000000000000000000000000000000000000000000000000000000" - } - } - ] -} -``` - -#### Get mempool transactions - -Mempool (registered, but not processed) transactions can be obtained using the [`GET /extended/v1/tx/mempool`](/stacks/api/transactions/mempool-transactions) endpoint: - -```terminal -$ curl 'https://api.testnet.hiro.so/extended/v1/tx/mempool' -``` - -Sample response: - -```js -{ - "limit": 96, - "offset": 0, - "total": 5, - "results": [ - { - "tx_id": "0xb31df5a363dad31723324cb5e0eefa04d491519fd30827a521cbc830114aa50c", - "tx_status": "pending", - "tx_type": "token_transfer", - "receipt_time": 1598288370, - "receipt_time_iso": "2020-08-24T16:59:30.000Z", - "fee_rate": "180", - "sender_address": "STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6", - "sponsored": false, - "post_condition_mode": "deny", - "token_transfer": { - "recipient_address": "ST1GY25DM8RZV4X15X07THRZ2C5NMWPGQWKFGV87F", - "amount": "500000", - "memo": "0x46617563657400000000000000000000000000000000000000000000000000000000" - } - } - ] -} -``` - -The `memo` field is represented as a hexadecimal string of a byte buffer - -##### Filter by type - -Recent transactions can be filtered by [transaction type](#types) using the `type` query parameter: - -```terminal -$ curl 'https://api.testnet.hiro.so/extended/v1/tx/?type=contract_call' -``` - -#### Get transaction by ID - -A specific transaction can be obtained using the [`GET /extended/v1/tx/`](/stacks/api/transactions/get-transaction) endpoint: - -```terminal -$ curl 'https://api.testnet.hiro.so/extended/v1/tx/' -``` - -Sample response: - -```js -{ - "limit": 96, - "offset": 0, - "total": 5, - "results": [ - { - "tx_id": "0xb31df5a363dad31723324cb5e0eefa04d491519fd30827a521cbc830114aa50c", - "tx_status": "pending", - "tx_type": "token_transfer", - "receipt_time": 1598288370, - "receipt_time_iso": "2020-08-24T16:59:30.000Z", - "fee_rate": "180", - "sender_address": "STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6", - "sponsored": false, - "post_condition_mode": "deny", - "token_transfer": { - "recipient_address": "ST1GY25DM8RZV4X15X07THRZ2C5NMWPGQWKFGV87F", - "amount": "500000", - "memo": "0x46617563657400000000000000000000000000000000000000000000000000000000" - } - } - ] -} -``` - -### Garbage collection - -Broadcast transactions stay in the mempool for 256 blocks (~42 hours). If a transaction is not confirmed within that time, it is removed from the mempool. - -Most transactions stay in the mempool due to nonce issues. If you see a transaction pending for an unusual time, review the nonce of the account and the transaction. - -If a transaction is removed from the mempool, the transaction was not processed, and no changes were made to the blockchain state. diff --git a/content/docs/stacks/api/usage.mdx b/content/docs/stacks/api/usage.mdx deleted file mode 100644 index 968df1a11..000000000 --- a/content/docs/stacks/api/usage.mdx +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: Usage -description: Understand general concepts, response codes, and authentication strategies. ---- - -### Base URL - -The Stacks API is built on REST principles, enforcing HTTPS for all requests to ensure data security, integrity, and privacy. The base URL for all API requests is: - -```plaintext -https://api.mainnet.hiro.so -``` - -### Making requests - -To make a request to the Stacks API, you can paste the `curl` command below in your terminal. - -```terminal -$ curl -L 'https://api.hiro.so/extended' \ --H 'Accept: application/json' -``` - -### Authentication - -If you are using an `api-key`, you will need to replace `$HIRO_API_KEY` with your secret API key. - -```terminal -$ curl -L 'https://api.hiro.so/extended' \ - -H 'Accept: application/json' \ - -H 'X-API-Key: $HIRO_API_KEY' -``` - -### Response codes - -The Stacks API uses standard HTTP response codes to indicate the success or failure of an API request: - -- **`200`**: Successful request -- **`400`**: Check that the parameters were correct -- **`401`**: Missing API key -- **`403`**: Invalid API key -- **`404`**: Resource not found -- **`429`**: Rate limit exceeded -- **`5xx`**: Server errors - -### Rate limits - -| API key | Rate limit | -|:--------|:----------------------------------| -| No | 50 requests per minute (RPM) per client IP, for unauthenticated traffic | -| Yes | 500 requests per minute (RPM) regardless of origin IP, with an authenticated API key | - - - For more information on rate limiting, you can check out the [rate limiting documentation](/stacks/rate-limiting). - diff --git a/content/docs/stacks/archive/guides/stacks-api.mdx b/content/docs/stacks/archive/guides/stacks-api.mdx deleted file mode 100644 index 1c1dffc71..000000000 --- a/content/docs/stacks/archive/guides/stacks-api.mdx +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Use the Stacks Blockchain API archive -description: Discover how to use the Hiro Archive to spin up a Stacks Blockchain API. ---- - -## Prerequisites - -Since the Stacks Blockchain API depends on a Stacks blockchain node being at the same block height, you will need to first [restore a Stacks blockchain node using the Hiro Archive](/stacks/archive/guides/stacks-blockchain) before restoring the Stacks Blockchain API. Otherwise, you may encounter errors when running the API. - -In order for the Stacks blockchain and Stacks Blockchain API archives to be compatible, they must meet the following criteria: - -- Both archives correspond to the same Stacks network (mainnet/testnet). -- The API archive version must be compatible with the Stacks blockchain archive version (See [API release notes](https://github.com/hirosystems/stacks-blockchain-api/releases) for guidance). -- Both archives were created on the same date. - -## Restoration methods - -There are two ways to restore a Stacks Blockchain API using the Hiro Archive. The archive file you'll need to download will depend on your method of restoration. There is no scenario where you would need both restoration methods. - -**Restore via Postgres database dump (Recommended)** - -This is the quickest and most direct method, and it is suitable for most scenarios. It consists of a backup of the API's Postgres database taken using `pg_dump`. We generally recommend starting with this method before attempting the method below if this one does not work for any reason. - -**Restore via tab-separated-values (TSV) file** - -This method is several times slower than restoring from a Postgres dump. The API TSV file contains the raw unprocessed events from a Stacks blockchain node. The API can ingest this file to process events into a Postgres database. -Restoring from a TSV file can be useful when a Postgres database archive for a particular API version is not available or when it cannot be used for any reason. - -## Where to download archives - -Depending on the restoration method used above, the Stacks Blockchain API archives for each network can be found at the following locations: - -- Postgres database dump - - mainnet: https://archive.hiro.so/mainnet/stacks-blockchain-api-pg/ - - testnet: https://archive.hiro.so/testnet/stacks-blockchain-api-pg/ -- TSV file - - mainnet: https://archive.hiro.so/mainnet/stacks-blockchain-api/ - - testnet: https://archive.hiro.so/testnet/stacks-blockchain-api/ - -The file name patterns are as follows: - -- Postgres database dump - - archive: `stacks-blockchain-api-pg---.dump` - - shasum: `stacks-blockchain-api-pg---.sha256` -- TSV file - - archive: `-stacks-blockchain-api--.gz` - - shasum: `-stacks-blockchain-api--.sha256` - -There is a continually updated archive and shasum which always points to the most recent upload: - -- Postgres database dump - - archive: `stacks-blockchain-api-pg--latest.dump` - - shasum: `stacks-blockchain-api-pg--latest.sha256` -- TSV file - - archive: `-stacks-blockchain-api-latest.gz` - - shasum: `-stacks-blockchain-api-latest.sha256` - -or the most recent upload for a particular version: - -- Postgres database dump - - archive: `stacks-blockchain-api-pg---latest.dump` - - shasum: `stacks-blockchain-api-pg---latest.sha256` -- TSV file - - archive: `-stacks-blockchain-api--latest.gz` - - shasum: `-stacks-blockchain-api--latest.sha256` - -## Restoring the Stacks Blockchain API using the Hiro Archive - -**If restoring via Postgres dump** - -1. Download the archive and shasum for the appropriate network and restoration method. -1. [Verify the archive](/stacks/archive/guides/verify-archive-data) with the shasum. -1. Import the archive file into a running Postgres database (may take up to an hour depending on database specs and tuning): - ```terminal - $ export PGPASSWORD= - $ pg_restore --username postgres --verbose --jobs 4 --dbname stacks_blockchain_api /path/to/archive/file - ``` -1. Launch the Stacks Blockchain API service. -1. Verify the dataset is being used by comparing your nodes [local block height](http://localhost:3999/extended/v1/status) with [Hiro's](https://api.hiro.so/extended/v1/status). If the block height matches or is close to Hiro's block height, the restoration was successful. - 1. It may take a few minutes for the local node to respond on this endpoint. - 1. Your block height may be up to a few hundred blocks away from Hiro's depending on the age of the archive. It should catch up relatively quickly. - -**If restoring via TSV file** - -1. Download the archive and shasum for the appropriate network and restoration method. -1. [Verify the archive](/stacks/archive/guides/verify-archive-data) with the shasum. -1. Extract the archive into the desired directory: - ```terminal - $ gzip -d --stdout > /path/to/extracted/file - ``` -1. [Follow these directions](https://github.com/hirosystems/stacks-blockchain-api#export-and-import) to process and import the events in the TSV file into your Postgres database. -1. Launch the Stacks Blockchain API service. -1. Verify the dataset is being used by comparing your nodes [local block height](http://localhost:3999/extended/v1/status) with [Hiro's](https://api.hiro.so/extended/v1/status). If the block height matches or is close to Hiro's block height, the restoration was successful. - 1. It may take a few minutes for the local node to respond on this endpoint. - 1. Your block height may be up to a few hundred blocks away from Hiro's depending on the age of the archive. It should catch up relatively quickly. diff --git a/content/docs/stacks/archive/index.mdx b/content/docs/stacks/archive/index.mdx deleted file mode 100644 index c936cb161..000000000 --- a/content/docs/stacks/archive/index.mdx +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Overview -description: The Hiro Archive is a series of data snapshots for services in the Stacks ecosystem. ---- - -import { Button } from "@/components/ui/button" -import { SecondaryCard } from "@/components/card" - -The Hiro Archive enables you to quickly bootstrap supported services with pre-loaded data, which otherwise could take you days or weeks to acquire when syncing from genesis. This is a public service Hiro offers as a free benefit to the Stacks community. - - - -## Supported services - -We record and archive mainnet and testnet snapshots for the following services every night: - - - - - - - diff --git a/content/docs/stacks/archive/meta.json b/content/docs/stacks/archive/meta.json deleted file mode 100644 index 6d3a7128d..000000000 --- a/content/docs/stacks/archive/meta.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "title": "Hiro Archive", - "root": true, - "pages": [ - "---Hiro Archive---", - "index", - "---Guides---", - "guides/verify-archive-data", - "guides/stacks-blockchain", - "guides/stacks-api", - "guides/token-metadata-api" - ] -} diff --git a/content/docs/stacks/chainhook/concepts/predicate-design.mdx b/content/docs/stacks/chainhook/concepts/predicate-design.mdx deleted file mode 100644 index 305c29243..000000000 --- a/content/docs/stacks/chainhook/concepts/predicate-design.mdx +++ /dev/null @@ -1,343 +0,0 @@ ---- -title: Predicate design -description: Predicates are the building blocks of Chainhook. ---- - -The core design of Chainhook revolves around the concept of predicates. Each individual chainhook has a customizable predicate that specifies what Bitcoin or Stacks blockchain data you are scanning for. - - - Commands outlined here will require that you have [installed Chainhook directly](/stacks/chainhook/installation) first. - - -## Predicate design -Below is the general strucure of the `predicate` JSON with its primary elements. These elements and their values are required. - -- Chainhook will evaluate the predicate against the specfied blockchain specified in `chain`. -- The `uuid` will be returned in the Chainhook payload, providing a record of the predicate that triggers it. -- Identify your predicate for your app using `name` and `version`. - -```json - { - "chain": "stacks", - "uuid": "1", - "name": "STX_Transfer_Predicate", - "version": 1, - "networks": { - // Other configurations - } - } - ``` - - - You can use the following command to verify your predicate: - ``` - chainhook predicate check your-predicate-file.json --mainnet - ``` - - -## Networks - -The `networks` element contains an object who's key determines the blockchain network you want Chainhook to scan. -- This object's value will contain the `if_this` and then `then_that` specifications. -- Multple networks can be specified in the `networks` element. - -```json - "networks": { - "mainnet": { - // if_this and then_that specifications - // Other configurations - }, - "testnet": { - // if_this and then_that specifications - // Other configurations - }, - } -``` - - - For additional information, check out the [Bitcoin scopes](/stacks/chainhook/references/scopes/bitcoin) and [Stacks scopes](/stacks/chainhook/references/scopes/stacks) references pages. - - -## if_this specification - -The `predicate` identifies what data you want Chainhook to scan for using the `scope` define within the `if_this` specification. Additional arguments specific to the `scope` will also be passed here. - -```json - { - "if_this": { - "scope": "contract_call", - "contract_identifier": "STJ81C2WPQHFB6XTG518JKPABWM639R2X37VFKJV.simple-vote-v0", - "method": "cast-vote" - } - } -``` - -## then_that specification - -Chainhook delivers the payload when it is triggered by your `predicate` using the `then_that` specification. There are 2 options available: - -1. `file_append` -2. `http_post` - -When choosing to use file_append, specify the path where Chainhook will post the payload data. - -```json -{ - "then_that": { - "file_append": { - "path": "/tmp/events.json" - } - } -} -``` - -When using `http_post`, specify the endpoint's `url` and `authorization_header`. - -```json -{ - "then_that": { - "http_post": { - "url": "https://webhook.site/abc123456-789e-0fgh-1ijk-23lmno456789", - "authorization_header": "12345" - } - } -} -``` - - - Chainhook requires `https` to post to your endpoint. You can use a service like [LocalTunnel](https://github.com/localtunnel/localtunnel) to test locally or a site like [WebhookSite](https://webhook.site). - - -## Blockchain specific configurations - - - - - ```json - { - "chain": "bitcoin", - "uuid": "1", - "name": "Wrap BTC", - "version": 1, - "networks": { - "testnet": { - "if_this": { - "scope": "ordinals_protocol", - "operation": "inscription_feed" - }, - "then_that": { - "http_post": { - "url": "http://localhost:3000/api/v1/ordinals", - "authorization_header": "Bearer cn389ncoiwuencr" - } - }, - "start_block": 10200 - // Additional configurations - }, - "mainnet": { - "if_this": { - "scope": "ordinals_protocol", - "operation": "inscription_feed" - }, - "then_that": { - "http_post": { - "url": "http://my-protocol.xyz/api/v1/ordinals", - "authorization_header": "Bearer cn389ncoiwuencr" - } - }, - "start_block": 90232 - // Additional configurations - } - } - } - ``` - - - - The following additional configurations can be used to improve the performance of Chainhook by preventing a full scan of the blockchain. - - Ignore any block before the given block: - - ```json - "start_block": 101 - ``` - - Ignore any block after the given block: - - ```json - "end_block": 201 - ``` - - Stop evaluating a chainhook after a given number of occurrences are found: - - ```json - "expire_after_occurrence": 1 - ``` - - Don't include proofs: - - ```json - "include_proof": false - ``` - - Don't include proofs: - - ```json - "include_proof": false - ``` - - Don't include Bitcoin transaction inputs in the payload: - - ```json - "include_inputs": false - ``` - - Don't include Bitcoin transaction outputs in the payload: - - ```json - "include_outputs": false - ``` - - Don't include Bitcoin transaction outputs in the payload: - - ```json - "include_outputs": false - ``` - - Don't include Bitcoin transaction witnesses in the payload: - - ```json - "include_witness": false - ``` - - Don't include Bitcoin transaction witnesses in the payload: - - ```json - "include_witness": false - ``` - - - - - The following command allows you to generate a predicate template for the Bitcoin blockchain. - ``` - chainhook predicates new your-bitcoin-predicate.json --bitcoin - ``` - - - - - - - ```json - { - "chain": "stacks", - "uuid": "1", - "name": "Contract-Call-Chainhook", - "version": 1, - "networks": { - "testnet": { - "if_this": { - "scope": "contract_call", - "contract_identifier": "STJ81C2WPQHFB6XTG518JKPABWM639R2X37VFKJV.simple-vote-v0", - "method": "cast-vote" - }, - "then_that": { - "file_append": { - "path": "/tmp/events.json" - } - }, - "start_block": 21443 - // Additional configurations - }, - "mainnet": { - "if_this": { - "scope": "contract_call", - "contract_identifier": "STJ81C2WPQHFB6XTG518JKPABWM639R2X37VFKJV.simple-vote-v0", - "method": "cast-vote" - }, - "then_that": { - "http_post": { - "url": "http://my-protocol.xyz/api/v1/ordinals", - "authorization_header": "Bearer cn389ncoiwuencr" - } - }, - "start_block": 142221 - // Additional configurations - } - } - } - ``` - - - - Thse additional configurations can be used to improve the performance of Chainhook by preventing a full scan of the blockchain: - - Ignore any block before the given block: - - ```json - "start_block": 101 - ``` - - Ignore any block after the given block: - - ```json - "end_block": 201 - ``` - - Stop evaluating chainhook after a given number of occurrences found: - - ```json - "expire_after_occurrence": 1 - ``` - - Include decoded Clarity values in the payload: - - ```json - "decode_clarity_values": true - ``` - - Include the contract ABI for transactions that deploy contracts: - - ```json - "include_contract_abi": true - ``` - - - - - The following command allows you to generate a predicate template for the Stacks blockchain. - ``` - chainhook predicates new your-stacks-predicate.json --stacks - ``` - - - - - - -## Next steps - - - - - - - - diff --git a/content/docs/stacks/chainhook/guides/chainhook-as-a-service-with-stacks-node.mdx b/content/docs/stacks/chainhook/guides/chainhook-as-a-service-with-stacks-node.mdx deleted file mode 100644 index 09c273918..000000000 --- a/content/docs/stacks/chainhook/guides/chainhook-as-a-service-with-stacks-node.mdx +++ /dev/null @@ -1,303 +0,0 @@ ---- -title: Run Chainhook as a service with a Stacks node -description: Learn how to run Chainhook as a service with a Stacks node to evaluate Stacks blocks against your predicates. ---- - -You can run Chainhook as a service to evaluate Stacks blocks against your predicates. You can also dynamically register new predicates by enabling the predicates registration API. - -In this guide, you will learn how to: - -1. [Configure your Stacks node to work with Chainhook](#configure-your-stacks-node). -2. [Configure Chainhook](#configure-chainhook). -3. [Create a predicate to evaluate your events](#create-a-predicate). -4. [Initiate a Chainhook service to watch for matching transactions](#initiate-chainhook-as-a-service). -5. [Dynamically register your predicates with Chainhook](#dynamically-register-predicates). - -{/* Check out a full example [here](https://github.com/hiro-so/stacks-connect-example). */} - ---- - -## Configure Your Stacks Node - -If you followed along with the previous guide on syncing a Stacks node, you should generate a `Stacks.toml` file within your Stacks node repository. Below is a sample `Stacks.toml` file: - -```toml title="Stacks.toml" -[node] -working_dir = "/stacks-blockchain" -rpc_bind = "0.0.0.0:20443" # Make a note of this port to use in the `Chainhook.toml` -p2p_bind = "0.0.0.0:20444" -bootstrap_node = "02da7a464ac770ae8337a343670778b93410f2f3fef6bea98dd1c3e9224459d36b@seed-0.mainnet.stacks.co:20444,02afeae522aab5f8c99a00ddf75fbcb4a641e052dd48836408d9cf437344b63516@seed-1.mainnet.stacks.co:20444,03652212ea76be0ed4cd83a25c06e57819993029a7b9999f7d63c36340b34a4e62@seed-2.mainnet.stacks.co:20444" - -[burnchain] -chain = "bitcoin" -mode = "mainnet" -peer_host = "localhost" -username = "bitcoind_username" # Must match the rpcuser in the bitcoin.conf -password = "bitcoind_password" # Must match the rpcpassword in the bitcoin.conf -rpc_port = 8332 # Must match the rpcport in the bitcoin.conf -peer_port = 8333 - -[[events_observer]] -endpoint = "localhost:20455" -retry_count = 255 -events_keys = ["*"] -``` - -Ensure that the `username`, `password`, and `rpc_port` values in the `Stacks.toml` file match the values in the `bitcoin.conf` file. Also, note the `rpc_bind` port to use in the `Chainhook.toml` configuration in the next section. - - -## Configure Chainhook - -In this section, you will configure Chainhook to communicate with the network. Run the following command in your terminal to generate the `Chainhook.toml` file: - -```terminal -$ chainhook config generate --mainnet -``` - -Several network parameters in the generated Chainhook.toml configuration file need to match those in the bitcoin.conf file created earlier in the Setting up a Bitcoin Node section. Update the following parameters accordingly: - -1. Update `bitcoind_rpc_username` with the username set for `rpcuser` in `bitcoin.conf`. -2. Update `bitcoind_rpc_password` with the password set for `rpcpassword` in `bitcoin.conf`. -3. Update `bitcoind_rpc_url` with the same host and port used for `rpcport` in `bitcoin.conf`. -4. Ensure `stacks_node_rpc_url` matches the `rpc_bind` in the `Stacks.toml` file. - -The generated `Chainhook.toml` file should look like this: - -```toml title="Chainhook.toml" -[storage] -working_dir = "cache" - -# The http API allows you to register / deregister predicates dynamically. -# This is disabled by default. - -# [http_api] -# http_port = 20456 -# database_uri = "redis://localhost:6379/" - -[network] -mode = "mainnet" -bitcoind_rpc_url = "http://localhost:8332" -bitcoind_rpc_username = "devnet" -bitcoind_rpc_password = "devnet" -# Bitcoin block events can be received by Chainhook -# either through a Bitcoin node's ZeroMQ interface, -# or through the Stacks node. The Stacks node is -# used by default: -stacks_node_rpc_url = "http://localhost:20443" -stacks_events_ingestion_port = 20455 -# but zmq can be used instead: -# bitcoind_zmq_url = "tcp://0.0.0.0:18543" - -[limits] -max_number_of_bitcoin_predicates = 100 -max_number_of_concurrent_bitcoin_scans = 100 -max_number_of_stacks_predicates = 10 -max_number_of_concurrent_stacks_scans = 10 -max_number_of_processing_threads = 16 -max_number_of_networking_threads = 16 -max_caching_memory_size_mb = 32000 - -[[event_source]] -tsv_file_url = "https://archive.hiro.so/mainnet/stacks-blockchain-api/mainnet-stacks-blockchain-api-latest" -``` - -Ensure the following configurations are matched to allow Chainhook to communicate with both Stacks and Bitcoin: - -| bitcoin.conf | Stacks.toml | Chainhook.toml | -|--------------------|-------------|-----------------------------| -| rpcuser | username | bitcoind_rpc_username | -| rpcpassword | password | bitcoind_rpc_password | -| rpcport | rpc_port | bitcoind_rpc_url | -| zmqpubhashblock | | bitcoind_zmq_url | -| | rpc_bind | stacks_node_rpc_url | -| | endpoint | stacks_events_ingestion_port | - - -The `bitcoind_zmq_url` is optional when running Chainhook as a service using Stacks because Stacks will pull the blocks from Stacks and the Bitcoin chain. - - -## Create a predicate - -Now that the Stacks and Chainhook configurations are done, you can scan your blocks by defining your predicates. - -### Appending events to a file - -The following command will generate a sample JSON file `print-event.json`. - -```terminal -$ chainhook predicates new print-event.json --stacks -``` - -Once the boilerplate predicate code has been generated, update the `print-event.json` file with the following content: - -```json title="print-event.json" -{ - "chain": "stacks", - "uuid": "6ad27176-2b83-4381-b51c-50baede11e3f", - "name": "Hello world", - "version": 1, - "networks": { - "testnet": { - "start_block": 34239, - "end_block": 50000, - "if_this": { - "scope": "print_event", - "contract_identifier": "ST1SVA0SST0EDT4MFYGWGP6GNSXMMQJDVP1G8QTTC.arkadiko-freddie-v1-1", - "contains": "vault" - }, - "then_that": { - "file_append": { - "path": "arkadiko.txt" - } - } - }, - "mainnet": { - "start_block": 34239, - "end_block": 50000, - "if_this": { - "scope": "print_event", - "contract_identifier": "SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.arkadiko-freddie-v1-1", - "contains": "vault" - }, - "then_that": { - "file_append": { - "path": "arkadiko.txt" - } - } - } - } -} -``` - -Now, use the following command to scan the blocks based on the predicates defined in the `print-event.json` file: - -```terminal -$ chainhook predicates scan print-event.json --mainnet -``` - -The output of the above command will be a file `arkadiko.txt` generated based on the predicate definition. - -### Sending events to an API endpoint - -```terminal -$ chainhook predicates new print-event-post.json --stacks -``` - -This will generate a sample JSON file `print-event-post.json`. Update the generated `print-event-post.json` file with the following content: - -```json title="print-event-post.json" -{ - "chain": "stacks", - "uuid": "e5fa09b2-ec3e-4b6a-9a4a-0ebb454f6e19", - "name": "Hello world", - "version": 1, - "networks": { - "testnet": { - "if_this": { - "scope": "print_event", - "contract_identifier": "ST1SVA0SST0EDT4MFYGWGP6GNSXMMQJDVP1G8QTTC.arkadiko-freddie-v1-1", - "contains": "vault" - }, - "then_that": { - "http_post": { - "url": "http://localhost:3000/events", - "authorization_header": "Bearer cn389ncoiwuencr" - } - }, - "start_block": 10200, - "expire_after_occurrence": 5 - }, - "mainnet": { - "if_this": { - "scope": "print_event", - "contract_identifier": "SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.arkadiko-freddie-v1-1", - "contains": "vault" - }, - "then_that": { - "http_post": { - "url": "http://localhost:3000/events", - "authorization_header": "Bearer cn389ncoiwuencr" - } - }, - "start_block": 10200, - "expire_after_occurrence": 5 - } - } -} -``` - - -The `start_block` is a required field to use the `http_post` then_that predicate. - - -Now, use the following command to scan the blocks based on the predicates defined in the `print-event-post.json` file: - -```terminal -$ chainhook predicates scan print-event-post.json --mainnet -``` - -The above command posts events to the URL `http://localhost:3000/events` mentioned in the `Chainhook.toml` file. - -## Initiate Chainhook as a service - -```terminal -$ chainhook service start --predicate-path=print-event.json --config-path=Chainhook.toml -``` - -This command registers the predicate and starts the Chainhook service. - -## Dynamically register predicates - -You can also dynamically register new predicates with your Chainhook service. - - This section requires that you have Redis running locally. To install, refer to the [Redis documentation](https://redis.io/docs/getting-started/). - -First, ensure that the following lines in the `Chainhook.toml` file are uncommented to enable the predicate registration server: - -```toml title="Chainhook.toml" -[http_api] -http_port = 20456 -database_uri = "redis://localhost:6379/" -``` - -```terminal -$ chainhook service start --predicate-path=print-event.json --config-path=Chainhook.toml -``` - -Start the Chainhook service with the following command: - -```terminal -$ chainhook service start --config-path=Chainhook.toml -``` - -To dynamically register a new predicate, send a POST request to the running predicate registration server at `localhost:20456/v1/chainhooks`. - -Use the following `curl` command template as an example: - -```terminal -$ curl -X POST \ - -H "Content-Type: application/json" \ - -d @predicate.json \ - http://localhost:20456/v1/chainhooks - -{"result":"","status":200} -``` - -You can also run the Chainhook service by passing multiple predicates: `chainhook service start --predicate-path=predicate_1.json --predicate-path=predicate_2.json --config-path=Chainhook.toml` - ---- - -## Next steps - - - - - \ No newline at end of file diff --git a/content/docs/stacks/chainhook/guides/chainhook-as-a-service.mdx b/content/docs/stacks/chainhook/guides/chainhook-as-a-service.mdx deleted file mode 100644 index 7af882a29..000000000 --- a/content/docs/stacks/chainhook/guides/chainhook-as-a-service.mdx +++ /dev/null @@ -1,254 +0,0 @@ ---- -title: Run Chainhook as a service -description: Learn how to run Chainhook as a service to evaluate your "if this, then that" predicates against the Bitcoin and Stacks blockchains. ---- - -In order to build out a more robust and secure web app, you can run Chainhook as a service to stream your events continously to a server you designate. - -In this guide, you will learn how to: - -1. [Configure an existing Bitcoin node to work with Chainhook](#configure-an-existing-bitcoin-node-to-work-with-chainhook). -2. [Generate a Chainhook predicate to target specific transactions](#generate-a-chainhook-predicate-to-target-specific-transactions). -3. [Scan the Bitcoin blockchain for transactions that match your predicate](#scan-the-bitcoin-blockchain-for-transactions-that-match-your-predicate). -4. [Initiate a Chainhook service to watch for matching transactions](#initiate-a-chainhook-service-to-watch-for-matching-transactions). -5. [Dynamically register your predicate with Chainhook](#dynamically-register-your-predicate-with-chainhook). - ---- - -## Configure Chainhook - -In this section, you will configure Chainhook to match the network configurations with the bitcoin config file. First, [install the latest version of Chainhook](/stacks/chainhook/installation). - -Next, you will generate a `Chainhook.toml` file to connect Chainhook with your bitcoind node. Navigate to the directory where you want to generate the `Chainhook.toml` file and use the following command in your terminal: - -```terminal -$ chainhook config generate --mainnet -``` - -Several network parameters in the generated `Chainhook.toml` configuration file need to match those in the `bitcoin.conf` file created earlier in the [setting up a Bitcoin node](/guides/sync-a-bitcoin-node) section. Update the following parameters accordingly: - -1. Update `bitcoind_rpc_username` with the username set for `rpcuser` in `bitcoin.conf`. -2. Update `bitcoind_rpc_password` with the password set for `rpcpassword` in `bitcoin.conf`. -3. Update `bitcoind_rpc_url` with the same host and port used for `rpcport` in `bitcoin.conf`. - -Additionally, if you want to receive events from the configured Bitcoin node, substitute `stacks_node_rpc_url` with `bitcoind_zmq_url`, as follows: - -```toml -[storage] -working_dir = "cache" - -# The http API allows you to register / deregister predicates dynamically. -# This is disabled by default. - -# [http_api] -# http_port = 20456 -# database_uri = "redis://localhost:6379/" - -[network] -mode = "mainnet" -bitcoind_rpc_url = "http://localhost:8332" -bitcoind_rpc_username = "devnet" -bitcoind_rpc_password = "devnet" -# Bitcoin block events can be received by Chainhook -# either through a Bitcoin node's ZeroMQ interface, -# or through the Stacks node. The Stacks node is -# used by default: -# stacks_node_rpc_url = "http://localhost:20443" -# but zmq can be used instead: -bitcoind_zmq_url = "tcp://0.0.0.0:18543" - -[limits] -max_number_of_bitcoin_predicates = 100 -max_number_of_concurrent_bitcoin_scans = 100 -max_number_of_stacks_predicates = 10 -max_number_of_concurrent_stacks_scans = 10 -max_number_of_processing_threads = 16 -max_number_of_networking_threads = 16 -max_caching_memory_size_mb = 32000 - -[[event_source]] -tsv_file_url = "https://archive.hiro.so/mainnet/stacks-blockchain-api/mainnet-stacks-blockchain-api-latest" -``` - -Here is a table of the relevant parameters this guide changes in our configuration files. - -| bitcoin.conf | Chainhook.toml | -| :--------------- | :--------------------- | -| rpcuser | bitcoind_rpc_username | -| rpcpassword | bitcoind_rpc_password | -| rpcport | bitcoind_rpc_url | -| zmqpubhashblock | bitcoind_zmq_url | - -## Scan the blockchain based on predicates - -Now that your `bitcoind` and Chainhook configurations are complete, you can define the Chainhook [Bitcoin predicate scope](/stacks/chainhook/references/scopes/bitcoin) you would like to scan for. - -These predicates are where you specify the `if_this / then_that` pattern to trigger Chainhook to deliver a result (either a file appendation or an HTTP POST request). - -## Appending events to a file - -To generate a sample JSON file with predicates, execute the following command in your terminal: - -```terminal -$ chainhook predicates new stacking-pool.json --bitcoin -``` - -Replace the contents of the `stacking-pool.json` file with the following: - -```json -{ - "chain": "bitcoin", - "uuid": "1", - "name": "Stacking Pool", - "version": 1, - "networks": { - "mainnet": { - "start_block": 801500, - "end_block": 802000, - "if_this": { - "scope": "outputs", - "p2wpkh": { - "equals": "bc1qs0kkdpsrzh3ngqgth7mkavlwlzr7lms2zv3wxe" - } - }, - "then_that": { - "file_append": { - "path": "bitcoin-transactions.txt" - } - } - } - } -} -``` - -This example demonstrates scanning a portion of the Bitcoin blockchain to capture specific outputs from a Bitcoin address associated with a Stacking pool, in this case [Friedgar Pool](https://pool.friedger.de/). Notice the `then_that` predicate specifying a `file_append`. - - -You can get blockchain height and current block by referring to the [Stacks Explorer](https://explorer.hiro.so/blocks?chain=mainnet). - - -Now, use the following command to scan the blocks based on the predicates defined in the `stacking-pool.json` file. - -```terminal -$ chainhook predicates scan stacking-pool.json --config-path=./Chainhook.toml -``` - -The output of the above command will be a text file `bitcoin-transactions.txt` generated based on the predicate definition. - -## Sending events to an API endpoint - -Now you will generate another sample predicate, but this time you will send the payload to an API endpoint: - -```terminal -$ chainhook predicates new stacking-pool-api.json --bitcoin -``` - -Replace the contents of the `stacking-pool-api.json` file with the following: - -```json -{ - "chain": "bitcoin", - "uuid": "2", - "name": "Stacking Pool (API)", - "version": 1, - "networks": { - "mainnet": { - "start_block": 801500, - "if_this": { - "scope": "outputs", - "p2wpkh": { - "equals": "bc1qs0kkdpsrzh3ngqgth7mkavlwlzr7lms2zv3wxe" - } - }, - "then_that": { - "http_post": { - "url": "http://localhost:3000/events", - "authorization_header": "12345" - } - } - } - } -} -``` - - -The `start_block` is a required field when using the `http_post` `then_that` predicate. - - -Once you are finished setting up your endpoint, use the following command to scan the blocks based on the predicates defined in the `stacking-pool-api.json` file. - -```terminal -$ chainhook predicates scan stacking-pool-api.json --config-path=./Chainhook.toml -``` - -The above command posts events to the URL `http://localhost:3000/events`, mentioned in the JSON file. - -## Initiate Chainhook service - -In the examples above, your Chainhook scanned historical blockchain data against predicates and delivered results. In this next section, you will learn how to set up a Chainhook that acts as an ongoing observer and event-streaming service. - -You can start a Chainhook service with an existing predicate. You can also dynamically register new predicates by making an API call to your chainhook. In both of these instances, your predicates will be delivering their results to a server set up to receive results. - -Initiate the chainhook service by passing the predicate path to the command as shown below: - -```terminal -$ chainhook service start --predicate-path=stacking-pool-api.json --config-path=Chainhook.toml -``` - -The above command registers the predicate based on the predicate definition in the `stacking-pool-api.json` file. - -## Dynamically register predicates - -You can also dynamically register new predicates with your Chainhook service. This means you can start a long-running process that exposes HTTP endpoints to register, deregister, and report on new predicates. - - -This section requires that you have Redis running locally. To install, refer to the [Redis documentation](https://redis.io/docs/getting-started/). - - -First, ensure that the following lines of code are uncommented in the `Chainhook.toml` file to enable the predicate registration server: - -```toml -[http_api] -http_port = 20456 -database_uri = "redis://localhost:6379/" -``` - -If you have an instance of Redis running locally, you can now start the Chainhook service by running the following command: - -```terminal -$ chainhook service start --config-path=Chainhook.toml -``` - -To dynamically register a new predicate, send a POST request to the running predicate registration server at `localhost:20456/v1/chainhooks`. - -Use the following `curl` command template as an example: - -```terminal -$ curl -X POST \ - -H "Content-Type: application/json" \ - -d @predicate.json \ - http://localhost:20456/v1/chainhooks - -{"result":"","status":200} -``` - - -You can also run chainhook service by passing multiple predicates, ie `chainhook service start --predicate-path=predicate_1.json --predicate-path=predicate_2.json --config-path=Chainhook.toml` - - ---- - -## Next steps - - - - - \ No newline at end of file diff --git a/content/docs/stacks/chainhook/guides/observing-contract-calls.mdx b/content/docs/stacks/chainhook/guides/observing-contract-calls.mdx deleted file mode 100644 index 53974a9b5..000000000 --- a/content/docs/stacks/chainhook/guides/observing-contract-calls.mdx +++ /dev/null @@ -1,382 +0,0 @@ ---- -title: Observing contract calls with Chainhook -description: Learn how to use Chainhook to observe a function call for a voting contract. ---- - -import { Step, Steps } from "fumadocs-ui/components/steps"; -import { - Tooltip, - TooltipContent, - TooltipProvider, - TooltipTrigger, -} from "@/components/ui/tooltip"; - -The _json`contract_call`_ predicate scope is designed to target direct function calls within a smart contract. When triggered, Chainhook will return a payload with transaction data detailing the on-chain events contained in these functions. - -In this guide, you will learn how to: - -1. [Build a predicate to target the `cast-vote` function](#creating-the-predicate). -2. [Scan the Stacks blockchain using your predicate](#running-the-predicate). -3. [Use a Clarity function to return specific contract data](#return-contract-data-with-the-clarity-function). -4. [Find data related to the contract call within the Chainhook payload](#chainhook-payload). - - - To follow this guide, make sure you have installed Chainhook [directly](/stacks/chainhook/installation). - - - - - -## Create the predicate - -The `predicate` is your main interface for querying the Chainhook data indexer. Chainhook uses this predicate to select the appropriate blockchain, network, and scope for monitoring transactions. - -For the Stacks blockchain, run the following command to generate a `predicate` template: - -```terminal -$ chainhook predicates new contract-call-chainhook.json --stacks -``` - - - Alternatively, [Hiro Platform](https://platform.hiro.so/) has an excellent UI to help you to create a `predicate` using a form builder or upload a json file containing your `predicate`. - - -There are 3 main components to your `predicate` that you need to address: - -1. Targeting the appropriate blockchain and network -2. Defining the scope and targeting the function you want to observe -3. Defining the payload destination - -To begin, you need to configure the `predicate` to target the voting contract: - -- Specify `testnet` in the network object. -- Set the `start_block` property to 21443This value represents the block height that our voting contract was deployed at.. - -```json contract-call-chainhook.json -{ - "chain": "stacks", - "uuid": "1", - "name": "Contract-Call-Chainhook", - "version": 1, - "networks": { - "testnet": { - "start_block": 21443, - "decode_clarity_values": true, - "expire_after_occurrence": 1, - // ... - } - } -} -``` - -Next, define the scope of the `predicate` within the `if_this` specification. - -The `contract_call` scope allows Chainhook to observe blockchain data when the specified function is directly called from its contract. - -```json contract-call-chainhook.json -{ - "if_this": { - "scope": "contract_call", - "contract_identifier": "STJ81C2WPQHFB6XTG518JKPABWM639R2X37VFKJV.simple-vote-v0", - "method": "cast-vote" - } -} -``` - - - The function defined in the `method` property of your `predicate` must be directly called in order for Chainhook to observe events. Calling the function from another contract or from within a different function on the same contract will not generate a `payload`. Below is an example of a `cast-vote` function that would not trigger an event. - ```clarity - (define-public (call-cast-vote) - (cast-vote) - ) - ``` - - -Finally, define how Chainhook delivers the payload when it is triggered by your `predicate` using the `then_that` specification. - -Using `file_append`, specify the path where Chainhook will post the payload data. - -```json contract-call-chainhook.json -{ - "then_that": { - "file_append": { - "path": "/tmp/events.json" - } - } -} -``` - - - - ```json - { - "chain": "stacks", - "uuid": "1", - "name": "Contract-Call-Chainhook", - "version": 1, - "networks": { - "testnet": { - "start_block": 21443, - "decode_clarity_values": true, - "expire_after_occurrence": 1, - "if_this": { - "scope": "contract_call", - "contract_identifier": "STJ81C2WPQHFB6XTG518JKPABWM639R2X37VFKJV.simple-vote-v0", - "method": "cast-vote" - }, - "then_that": { - "file_append": { - "path": "/tmp/events.json" - } - } - } - } - } - ``` - - - - - - For more details on optional configurations, other predicate elements and scopes, check out the [Predicate Design](/stacks/chainhook/concepts/predicate-design) and [Stacks scopes](/stacks/chainhook/references/scopes/stacks) pages. - - - - - - -## Scan the predicate - -With your `predicate` set up, you can now scan for blocks that match the `contract_call` scope and analyze the returned payload. - -Chainhook will track events where this function is directly invoked and deliver detailed transaction data at the block level, based on your configuration. - -To scan the Stacks blockchain using your predicate, run the following command, replacing `/path/to/contract-call-chainhook.json` with the actual path to your `contract-call-chainhook.json` file: - -```terminal -$ chainhook predicates scan /path/to/contract-call-chainhook.json --testnet -``` - - - If you are using Platform, creating your Chainhook will automatically begin the scan for you. - - - - - -## Return contract data with the Clarity function - -The _clarity`cast-vote`_ function records a vote by storing the address that calls it. It also logs relevant data using the _clarity`print`_ function, which can be useful for when you want to track additional on-chain events that are not part of the built-in Clarity functions. - -When you examine the `payload`, this is the data you will look for. - -```clarity simple-vote-v0.clar -(define-public (cast-vote) - (begin - ;; Check if the voter has already voted. - (asserts! (is-none (map-get? UserVotes tx-sender)) (err ERR_ALREADY_VOTED)) - - ;; Update the map that the vote has been cast. Print vote related data. - (map-set UserVotes tx-sender { hasVoted: true }) - (var-set VoteCount (+ (var-get VoteCount) u1)) - (print - { - notification: "cast-vote", - payload: { - status: "Has voted set to true", - voter: tx-sender, - totalVotes: (get-total-votes) - } - } - ) - (ok "Vote cast successfully") - ) -) -``` - - - This contract has been deployed to the Stacks [testnet network](https://explorer.hiro.so/txid/0x312a3c559af0f75381a9eb4540912c310d74682ed3036207ec890ad8cd1aebe6?chain=testnet) under the name `STJ81C2WPQHFB6XTG518JKPABWM639R2X37VFKJV.simple-vote-v0`. - - - - - -## Dive deeper into the Chainhook payload - -When triggered by your predicate, the `payload` returned by Chainhook is a standarized, block level observation in json format. - -Within the `apply` arrays element, the `block_identifer` object gives us the `index` for the observed block height. - -```json contract-call-payload.json -"block_identifier": { - "hash": "0x4d88015a6df9ec4f6df875941d87337ce64f8d51608563f80b6e27adeb327e4d", - "index": 21544 -} -``` - - - The hash returned in the `block_identifer` object is not that block hash you - would see in [Stacks Explorer](https://explorer.hiro.so/?chain=testnet), but - `index_block_hash` returned from the Stacks API's [get - block](/stacks/api/blocks/get-block) endpoint. You can use the `apply` array's - metadata object to get the `stacks_block_hash`. - - -We can retrieve the `stacks_block_hash` by navigating to the `apply` arrays object `metadata` element. This hash will match the block hash display in the Stacks Explorer. - -```json contract-call-payload.json -"apply": [ - { - "metadata": { - "stacks_block_hash": "0x4ad36f77ff76042f3b7355006556375970b0f99d1232b14a3b4a2eadda4a806a" - } - } -] -``` - -There is also a `timestamp` value returned in the `apply` array. This UNIX time stamp represents the initiation of the Stacks block. - -```json contract-call-payload.json -"timestamp": 1722208524 -``` - - - The timestamp returned in this object is not the finalized block time you - would see in the [Stacks Explorer](https://explorer.hiro.so/?chain=testnet), but - `block_time` returned from the Stacks API's [get - block](/stacks/api/blocks/get-block) endpoint. - - -### Transaction object - -Because Chainhook is triggered on the block level, we will receive a single response that contains data specific to each `transaction` that matches your predicate's `contract_call` scope. - -To find this data, we start with the `apply` array element of the `payload` object. The single object that makes up the `apply` array contains a child element, the `transactions` array. Every `transaction` will be represents by a single object within this array. This `transaction` object contains its own children elements which can be seen in the example below. - -```json -{ - "apply": [ - { - "transactions": [ - { - "transaction_identifier": { ... }, - "metdata": { ... }, - "operations": [], - } - ], - } - ], - "rollback": [ ... ], - "chainhook": { ... } -} -``` - -Once the `transaction` object is returned, we can begin examining the important data elements this object contains. The first element, `transaction_identifier`, includes a hash value that uniquely identifies your transaction. - -```json contract-call-payload.json -"transaction_identifier": { - "hash": "0x98195af8f888d2f9ca3462c41c1691e7798ea6d9e5e3afe42955c0921f981f2c" -} -``` - -Next, focus on the `metadata` object within your `contract_call` data. It's crucial to determine the success state of your transaction. Chainhook captures and reports on transactions regardless of their outcome. - -Utilize the `success` object to assess transaction success and extract the `sender` of the transaction and the `result` returned by the contract. - -```json contract-call-payload.json -"metadata": { - "success": true, - "sender": "STJ81C2WPQHFB6XTG518JKPABWM639R2X37VFKJV", - "result": "(ok \"Vote cast successfully\")" -} -``` - -Moving forward, examine the `kind` object and its components within your `contract_call`. The data object contains crucial information: - -- `contract_identifier` specifies the contract your function resides in -- `method` identifies the function called -- `args` lists the arguments passed when invoking this function - -In this case, the `cast-vote` function accepts no arguments, resulting in an empty `args` array. - -```json contract-call-payload.json -{ - "metadata": - "kind": { - "data": { - "args": [], - "contract_identifier": "STJ81C2WPQHFB6XTG518JKPABWM639R2X37VFKJV.simple-vote-v0", - "method": "cast-vote" - } - } -} -``` - -In the `metadata` object's `receipt`, the `events` array holds the key data for your `contract_call`. - -Since the `cast-vote` function uses a `print` statement, the events array will contain `topic` and `value` keys representing the data output. - -```json contract-call-payload.json -{ - "metadata": - "receipt": { - "contract_calls_stack": [], - "events": [ - { - "data": { - "contract_identifier": "STJ81C2WPQHFB6XTG518JKPABWM639R2X37VFKJV.simple-vote-v0", - "topic": "print", - "value": { - "notification": "cast-vote", - "payload": { - "status": "Has voted set to true", - "totalVotes": 1, - "voter": "STJ81C2WPQHFB6XTG518JKPABWM639R2X37VFKJV" - } - } - }, - "position": { - "index": 0 - }, - "type": "SmartContractEvent" - } - ], - "mutated_assets_radius": [], - "mutated_contracts_radius": [ - "STJ81C2WPQHFB6XTG518JKPABWM639R2X37VFKJV.simple-vote-v0" - ] - } -} -``` - - - You can view the full [contract-call-payload.json](/contract-call-payload.json) here. - - - - - ---- - -Now that you've located the relevant data in the payload, you can start to extract the relevant information into your API. - -The following is an example of how you might store your information in a database table: - -| Block Height | Timestamp | Transaction Identifier | Success | Sender | Result | Args | Contract Identifier | Function | Value | -| ------------ | ---------- | ------------------------------------------------------------------ | ------- | ---------------------------------------- | ----------------------------- | ---- | ------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 21544 | 1722208524 | 0x98195af8f888d2f9ca3462c41c1691e7798ea6d9e5e3afe42955c0921f981f2c | True | STJ81C2WPQHFB6XTG518JKPABWM639R2X37VFKJV | (ok "Vote cast successfully") | [] | STJ81C2WPQHFB6XTG518JKPABWM639R2X37VFKJV.simple-vote-v0 | cast-vote | \{"notification": "cast-vote", "payload": \{"status": "Has voted set to true", "totalVotes": 1, "voter": "STJ81C2WPQHFB6XTG518JKPABWM639R2X37VFKJV"\}\} | - -## Next steps - - - - - diff --git a/content/docs/stacks/chainhook/guides/register-chainhooks-on-devnet.mdx b/content/docs/stacks/chainhook/guides/register-chainhooks-on-devnet.mdx deleted file mode 100644 index 073f37802..000000000 --- a/content/docs/stacks/chainhook/guides/register-chainhooks-on-devnet.mdx +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Register Chainhooks on devnet -description: Learn how to register chainhooks on devnet. ---- - -import { File, Folder, Files } from 'fumadocs-ui/components/files'; - -Follow these steps to register your Chainhooks on devnet using Clarinet: - - - This feature requires Clarinet version 2.1.0 or higher. To upgrade or install, refer to our [installation](/stacks/clarinet/installation) page for Clarinet. - - -## Create your Chainhook predicates - -First, within your Clarinet project, you'll need to create your Chainhook predicate files. - -These should be situated in the root of your project directory. The files can either be separate or stored within a specific folder, e.g., `/chainhooks` in your project root directory: - - - - - - - - - - - - - - - - - - - - -For examples on how to define your predicates, refer to the [scopes](/stacks/chainhook/references/scopes/stacks) reference page. - -## Start devnet - -To start devnet, run the _`clarinet devnet start`_ command from the root of your project directory. Running this command will begin a local Chainhook service in the background that automatically registers your Chainhook files within the project directory against the network. - -## Confirm registration - -Once your devnet starts, the Chainhook service initiates the registration process. You'll know that the registration of your Chainhooks was successful by checking the confirmation message in your terminal: - -```terminal -$ clarinet devnet start -# ... -INFO Feb 5 15:20:07.233382 2 chainhooks registered -``` - -If you do not see this message at the top of your _`clarinet devnet start`_ logs, verify that you are using `clarinet` version 2.1.0 or higher. - -## Working with chainhooks - -With these steps completed, your chainhooks are ready to trigger whenever local contract actions occur. You can monitor your network activity locally, through the _`clarinet devnet start` terminal, to confirm chainhooks execution as you further develop and test your smart contracts. When an action occurs, you should see something like this: - -```terminal -$ clarinet devnet start -# ... -INFO Feb 5 15:21:07.233382 1 hooks triggered -``` - -At this point, you can verify the payload for that action depending on whether you are expecting an _json`http_post`_ or _json`file_append`_ result from your _json`then_that`_ configuration. diff --git a/content/docs/stacks/chainhook/index.mdx b/content/docs/stacks/chainhook/index.mdx deleted file mode 100644 index 1f3051b20..000000000 --- a/content/docs/stacks/chainhook/index.mdx +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: Overview -description: Chainhook enables you to target events on the Bitcoin and Stacks blockchain important to your use case in order to trigger actions based on those events. ---- - -import { SecondaryCard } from '@/components/card'; - -Chainhook is a reorg-aware indexer that serves reliable blockchain data—you don’t have to waste time reindexing your database every time there's a fork. Chainhook also lets you index only the data you need, which means you can build lighter databases, get faster query results, and deliver a better experience to your users. - -To get started, check out our [installation guide](/stacks/chainhook/installation). - -## Create event streams - - - - - - - -## Setting up Chainhook predicates - - - - - - -## Related tools - -- **[Bitcoin Indexer](/bitcoin/indexer)**: Simplify your testing with the Clarinet JS SDK. -- **[Hiro Platform](/stacks/platform)**: A developer platform for building, deploying and scaling Bitcoin apps. - -
- - -Reach out to us on the #chainhook channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET. - \ No newline at end of file diff --git a/content/docs/stacks/chainhook/installation.mdx b/content/docs/stacks/chainhook/installation.mdx deleted file mode 100644 index df6870beb..000000000 --- a/content/docs/stacks/chainhook/installation.mdx +++ /dev/null @@ -1,40 +0,0 @@ ---- -title: Installation -description: Chainhook is a CLI tool that allows you to create event streams for your Stacks and Bitcoin nodes. -toc: false ---- - - - - ```terminal - $ brew install chainhook - ``` - - - - ```terminal - $ sudo snap install chainhook - ``` - - - - ```terminal - $ winget install HiroSystems.Chainhook - ``` - - - - Clone the [Chainhook Repo](https://github.com/hirosystems/chainhook): - - ```terminal - $ git clone https://github.com/hirosystems/chainhook.git - ``` - - Navigate to the root directory and run `cargo chainhook-install`: - - ```terminal - $ cd chainhook && cargo chainhook-install - ``` - - - \ No newline at end of file diff --git a/content/docs/stacks/chainhook/meta.json b/content/docs/stacks/chainhook/meta.json deleted file mode 100644 index 1a0ce2b79..000000000 --- a/content/docs/stacks/chainhook/meta.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "title": "Chainhook", - "root": true, - "pages": [ - "---Chainhook---", - "index", - "installation", - "quickstart", - "---Concepts---", - "concepts/predicate-design", - "---Guides---", - "guides/register-chainhooks-on-devnet", - "guides/chainhook-as-a-service", - "guides/chainhook-as-a-service-with-stacks-node", - "guides/observing-contract-calls", - "---Reference---", - "references/scopes/bitcoin", - "references/scopes/stacks" - ] -} \ No newline at end of file diff --git a/content/docs/stacks/chainhook/quickstart.mdx b/content/docs/stacks/chainhook/quickstart.mdx deleted file mode 100644 index 14d943164..000000000 --- a/content/docs/stacks/chainhook/quickstart.mdx +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Quickstart -description: Learn how to scan the Stacks blockchain for STX transactions. ---- - -import { Accordion, Accordions } from "fumadocs-ui/components/accordion" -import { Steps, Step } from 'fumadocs-ui/components/steps'; - -In this quickstart guide, you will set up `Chainhook` to generate and scan predicates on the Stacks blockchain. You will learn how to generate predicates and run basic commands using the CLI to scan and inspect blockchain events. - -Check out the [run Chainhook as a service](/stacks/chainhook/guides/chainhook-as-a-service) for a more advanced use case. - - - - ## Generate a predicate file - - To generate a predicate file, use the `predicates new` command. This command generates a template that you can use to help set up your own predicate. - - ```terminal - $ chainhook predicates new stx-transfer.json --stacks - ``` - - - The `--stacks` flag is required and allows you to specify the network to scan. Other options include `--bitcoin`. - - - - ## Track the latest stx_event for a given address - - The generated file contains helpful boilerplate configuration, but you still need to make some edits to tell it to track specific Stacks-related transactions. - - To do this, update your `if_this` construct in your `stx-transfer.json` file. - - ```json title="stx-transfer.json" - { - "if_this": { - "scope": "stx_event", - "actions": ["transfer"] - } - } - ``` - - - - ```json - { - "chain": "stacks", - "uuid": "87ac9bff-1052-4d02-9c79-3768a6f08a09", - "name": "STX Transfer", - "version": 1, - "networks": { - "mainnet": { - "start_block": 154670, - "if_this": { - "scope": "stx_event", - "contract_identifier": "SPM113AY78VCMJJ0SDFJ4XJXFHHQ6R9KB3710X7D", - "actions": ["transfer"] - }, - "then_that": { - "file_append": { - "path": "stx-transfers.txt" - } - } - } - } - } - ``` - - - - - Other available `actions` include `mint`, `burn`, and `lock`. For more information on these actions, check out the [predicates](/stacks/chainhook/concepts/stacks-predicates) section. - - - - ## Scanning for events - - With your updated predicate file, you can now use the `predicate scan` command to scan for `stx_event` transactions. - - ```terminal - $ chainhook predicates scan /path/to/stx-transfer.json --mainnet - ``` - - - When running `scan` for the first time, a chainstate archive will be downloaded. The subsequent scans will use the cached chainstate if already present, speeding up iterations and the overall feedback loop. For more information on the Hiro Archive, click [here](/stacks/archive). - - - - ---- - -## Next steps - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/chainhook/references/scopes/bitcoin.mdx b/content/docs/stacks/chainhook/references/scopes/bitcoin.mdx deleted file mode 100644 index 3130e23cf..000000000 --- a/content/docs/stacks/chainhook/references/scopes/bitcoin.mdx +++ /dev/null @@ -1,383 +0,0 @@ ---- -title: Bitcoin Scopes -description: Reference guide for available scopes for Bitcoin. -toc: false ---- - -import { Root, API, APIExample } from '@/components/layout'; -import { Property } from 'fumadocs-openapi/ui' - -import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; -import { Badge } from '@/components/ui/badge'; -import { - Tooltip, - TooltipContent, - TooltipProvider, - TooltipTrigger, -} from "@/components/ui/tooltip"; - -import { InlineCode } from '@/components/inline-code'; - -Bitcoin scopes are parameters you use to define the `if this` specification logic of your Chainhook on the Bitcoin blockchain. In other words, scopes specify what on-chain events you are looking to monitor and track. For more information on Chainhook design, please view [predicate design](/stacks/chainhook/concepts/predicate-design). - - - - - -
- -

`txid`

- -The `txid` scope allows you to query transactions based on their transaction ID. This is particularly useful for tracking specific transactions or auditing transaction histories. - -## Parameters - - - -The `equals` property is a 32 byte hex encoded type used to specify the exact transaction ID to match. - - - -
- - - - - - - By transaction ID - - - - - ```json - { - "if_this": { - "scope": "txid", - "equals": "0xfaaac1833dc4883e7ec28f61e35b41f896c395f8d288b1a177155de2abd6052f" - } - } - ``` - - - - - -
- - - -
- -

`outputs`

- -The `outputs` scope allows you to query blocks based on the payload returned by the specified operation. - -## Parameters - - - -The `operation` property is used to identify the Bitcoin operation that will trigger Chainhook as it observes Bitcoin transactions. The available operations are `op_return`, `p2pkh`, `p2sh`,`p2wpkh` and `p2wsh`. - - - -
- - - - - - - Using op_return - - - Using p2pkh - - - Using p2sh - - - Using p2wpkh - - - Using p2wsh - - - Using descriptor - - - - - ```json - { - "if_this": { - "scope": "outputs", - "op_return": { - "equals": "0xbtc21000042stx016" - } - } - } - ``` - - - - The `equals` property specifies the exact characters of the string or 32 byte encoded hex to match. - - - The `starts_with` property specifies the starting characters of the string or 32 byte encoded hex to match. - - - The `ends_with` property specifies the ending characters of the string or 32 byte encoded hex to match. - - - - - The `op_return` operation allows for `equals`, `starts_with` and `ends_with` for matching against the desired input. - - - - - ```json - { - "if_this": { - "scope": "outputs", - "p2kph": { - "equals": "0xbtc21000042stx016" - } - } - } - ``` - - - - The `equals` property specifies the exact characters of the string or 32 byte encoded hex to match. - - - - - `p2pkh`(Pay-to-Public-Key-Hash) is a Bitcoin transaction output script type that allows users to send funds to a recipient's hashed public key, providing security and privacy by concealing the actual public key. - - - - - ```json - { - "if_this": { - "scope": "outputs", - "p2sh": { - "equals": "0xbtc21000042stx016" - } - } - } - ``` - - - - The `equals` property specifies the exact characters of the string or 32 byte encoded hex to match. - - - - - `p2sh`(Pay-to-Script-Hash) is a Bitcoin transaction output script type that enables users to send funds to a script instead of a public key, allowing for more complex transaction conditions and multi-signature addresses. - - - - - ```json - { - "if_this": { - "scope": "outputs", - "p2wpkh": { - "equals": "0xbtc21000042stx016" - } - } - } - ``` - - - - The `equals` property specifies the exact characters of the string to match. - - - - - `p2wpkh`(Pay-to-Witness-Public-Key-Hash) is a Bitcoin transaction output script type used in Segregated Witness (SegWit) that allows for more efficient and secure transactions by separating the witness data from the transaction data and storing it in a separate block. - - - - - ```json - { - "if_this": { - "scope": "outputs", - "p2wsh": { - "equals": "0xbtc21000042stx016" - } - } - } - ``` - - - - The `equals` property specifies the exact characters of the string to match. - - - - - `p2wsh` (Pay-to-Witness-Script-Hash) is a Bitcoin transaction output script type used in Segregated Witness (SegWit) that enables users to send funds to a hashed script, allowing for more complex transaction conditions and greater scalability by separating the script from the transaction data. - - - - - ```json - { - "if_this": { - "scope": "outputs", - "descriptor": { - "expression": "wpkh(tprv8ZgxMBicQKsPePxn6j3TjvB2MBzQkuhGgc6oRh2WZancZQgxktcnjZJ44XdsRiw3jNkbVTK9JW6KFHvnRKgAMtSyuBevMJprSkZ4PTfmTgV/84'/1'/0'/0/*)", - "range": [0, 3] - } - } - } - ``` - - - - The `expression` property specifies the exact characters of the string to match. - - - The `range` property specifies and array of integers representing the desired indexes. - - - - - - - Wallet descriptors provide a compact and semi-standardized method for describing how scripts and addresses within a wallet are generated. Chainhook users that want to track addresses derived from an extended pubkey or a multisig-wallet can now rely on this feature instead of defining one predicate per address. - For example, let's say we wanted to track the first 3 addresses generated by the following descriptor: - - ``` - wpkh(tprv8ZgxMBicQKsPePxn6j3TjvB2MBzQkuhGgc6oRh2WZancZQgxktcnjZJ44XdsRiw3jNkbVTK9JW6KFHvnRKgAMtSyuBevMJprSkZ4PTfmTgV/84'/1'/0'/0/*) - ``` - - This descriptor reads: describe a P2WPKH output with the specified extended public key, and it produces these BIP84 addresses: - - ``` - bcrt1qzy2rdyvu8c57qd8exyyp0mw7dk5drsu9ewzdsu - bcrt1qsfsjnagr29m8h3a3vdand2s85cg4cefkcwk2fy - bcrt1qauewfytqe5mtr0xwp786r6fl39kmum2lr65kmj - ``` - - - - - - - - -
- - - -
- -

`stacks_protocol`

- -The `stacks_protocol` scope allows you query Bitcoin transactions related to the Stacks Proof of Transfer (PoT) [concensus mechanism](https://www.hiro.so/blog/securing-web3-apps-through-bitcoin-an-overview-of-stacks-consensus-mechanism). - -## Parameters - - - -The `operation` property is used to identify the Stacks operation that will trigger Chainhook as it observes Bitcoin transactions. The available operations are `block_committed`, `leader_registered`, `inscription_feed`, `stx_transferred` and `stx_locked`. - - - -
- - - - - - - Using block_committed - - - Using leader_registered - - - Using inscription_feed - - - Using stx_transferred - - - Using stx_locked - - - - - ```json - { - "if_this": { - "scope": "stacks_protocol", - "operation": "block_committed" - } - } - ``` - - - - ```json - { - "if_this": { - "scope": "stacks_protocol", - "operation": "leader_registered" - } - } - ``` - - - - ```json - { - "if_this": { - "scope": "stacks_protocol", - "operation": "inscription_feed" - } - } - ``` - - - `inscription_feed` observes the reveal and transfer of an Ordinal inscription. - - - - - ```json - { - "if_this": { - "scope": "stacks_protocol", - "operation": "stx_transferred" - } - } - ``` - - - - ```json - { - "if_this": { - "scope": "stacks_protocol", - "operation": "stx_locked" - } - } - ``` - - - - - -
- -
\ No newline at end of file diff --git a/content/docs/stacks/chainhook/references/scopes/stacks.mdx b/content/docs/stacks/chainhook/references/scopes/stacks.mdx deleted file mode 100644 index d130f1172..000000000 --- a/content/docs/stacks/chainhook/references/scopes/stacks.mdx +++ /dev/null @@ -1,520 +0,0 @@ ---- -title: Stacks Scopes -description: Reference guide for available scopes for Stacks. -toc: false ---- - -import { Root, API, APIExample } from '@/components/layout'; -import { Property } from 'fumadocs-openapi/ui' - -import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; -import { Badge } from '@/components/ui/badge'; - -import { InlineCode } from '@/components/inline-code'; - -Stacks scopes are parameters you use to define the `if this` specification logic of your Chainhook on the Stacks blockchain. In other words, scopes specify what on-chain events you are looking to monitor and track. For more information on Chainhook design, please view [predicate design](/stacks/chainhook/concepts/predicate-design). - - - - - -
- -

`txid`

- -The `txid` scope allows you to query transactions based on their transaction ID. This is particularly useful for tracking specific transactions or auditing transaction histories. - -## Parameters - - - -The `equals` property is a 32 bytes hex encoded type used to specify the exact transaction ID to match. - - - -
- - - - - - - By transaction ID - - - - ```json - { - "if_this": { - "scope": "txid", - "equals": "0xfaaac1833dc4883e7ec28f61e35b41f896c395f8d288b1a177155de2abd6052f" - } - } - ``` - - - - - -
- - - -
- -

`block_height`

- -The `block_height` scope allows you to query blocks based on their height. This is useful for identifying specific blocks or ranges of blocks in the blockchain. - -## Parameters - - - -The `equals` property specifies the exact height of the block to match. - - - - - -The `higher_than` property specifies that the block height should be greater than the provided value. - - - - - -The `lower_than` property specifies that the block height should be less than the provided value. - - - - - -The `between` property specifies a range of block heights to match, inclusive of the provided start and end values. - - - -
- - - - - - - By block height - - - Using higher_than - - - Using lower_than - - - Between two block heights - - - - ```json - { - "if_this": { - "scope": "block_height", - "equals": 141200 - } - } - ``` - - - ```json - { - "if_this": { - "scope": "block_height", - "higher_than": 10000 - } - } - ``` - - - ```json - { - "if_this": { - "scope": "block_height", - "lower_than": 10000 - } - } - ``` - - - ```json - { - "if_this": { - "scope": "block_height", - "between": [0, 10000] - } - } - ``` - - - - - -
- - - -
- -

`ft_transfer`

- -The `ft_transfer` scope allows you to query transactions based on fungible token transfers. This is useful for tracking specific token movements or auditing token transfer histories. - -## Parameters - - - -The `asset_identifier` property specifies the fully qualified asset identifier to observe. - - - - - -The `actions` property specifies the types of token actions to observe, such as `mint`, `transfer`, or `burn`. - - - -
- - - - - - - By a single action - - - Passing all ft actions - - - - ```json - { - "if_this": { - "scope": "ft_transfer", - "asset_identifier": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.cbtc-token::cbtc", - "actions": ["transfer"] - } - } - ``` - - - ```json - { - "if_this": { - "scope": "ft_transfer", - "asset_identifier": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.cbtc-token::cbtc", - "actions": ["mint", "transfer", "burn"] - } - } - ``` - - - - - -
- - - -
- -

`nft_transfer`

- -The `nft_transfer` scope allows you to query transactions based on non-fungible token transfers. This is useful for tracking specific NFT movements or auditing NFT transfer histories. - -## Parameters - - - -The `asset_identifier` property specifies the fully qualified asset identifier to observe. - - - - - -The `actions` property specifies the types of NFT actions to observe, such as `mint`, `transfer`, or `burn`. - - - -
- - - - - - - By non-fungible token mint - - - Passing all nft actions - - - - ```json - { - "if_this": { - "scope": "nft_transfer", - "asset_identifier": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.monkey-sip09::monkeys", - "actions": ["mint"] - } - } - ``` - - - ```json - { - "if_this": { - "scope": "nft_transfer", - "asset_identifier": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.monkey-sip09::monkeys", - "actions": ["mint", "transfer", "burn"] - } - } - ``` - - - - - -
- - - -
- -

`stx_transfer`

- -The `stx_transfer` scope allows you to query transactions involving STX token movements. This is crucial for monitoring STX transfers, including minting, burning, and locking actions. - -## Parameters - - - -The `actions` property specifies the types of STX token actions to observe, such as `mint`, `transfer`, `burn`, and `lock`. - - - -
- - - - - - - By STX token transfer - - - Passing all actions - - - - ```json - { - "if_this": { - "scope": "stx_transfer", - "actions": ["transfer"] - } - } - ``` - - - ```json - { - "if_this": { - "scope": "stx_transfer", - "actions": ["mint", "transfer", "burn", "lock"] - } - } - ``` - - - - - -
- - - -
- -

`print_event`

- -The `print_event` scope allows you to query transactions based on specific print events emitted during contract execution. This is useful for monitoring specific events for auditing or tracking purposes. - -## Parameters - - - -The `contract_identifier` property specifies the fully qualified contract identifier to observe. - - - - - -The `contains` property is used for matching an event containing the specified string. - - - - - -The `matches_regex` property is used for matching an event that regex matches with the specified string. - - - -
- - - - - - - Using contains - - - Using matches_regex - - - - ```json - { - "if_this": { - "scope": "print_event", - "contract_identifier": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.monkey-sip09", - "contains": "monkey" - } - } - ``` - - - ```json - { - "if_this": { - "scope": "print_event", - "contract_identifier": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.monkey-sip09", - "matches_regex": "(?:^|\\W)monkey(?:$|\\W)" - } - } - ``` - - - - - -
- - - -
- -

`contract_call`

- -The `contract_call` scope allows you to query transactions that involve direct calls to specific methods within a smart contract. This is particularly useful for tracking interactions with critical contract functions. - -## Parameters - - - -The `contract_identifier` property specifies the fully qualified contract identifier to observe. - - - - - -The `method` property specifies the specific method within the contract to observe. - - - -
- - - - - - - Scoping by contract method call - - - - ```json - { - "if_this": { - "scope": "contract_call", - "contract_identifier": "SP000000000000000000002Q6VF78.pox", - "method": "stack-stx" - } - } - ``` - - - - - -
- - - -
- -

`contract_deployment`

- -The `contract_deployment` scope allows you to query transactions involving the deployment of smart contracts. This is crucial for monitoring new contract deployments and ensuring compliance with expected deployments. - -## Parameters - - - -The `deployer` property specifies the STX address of the deployer to observe. - - - - - -The `implement_trait` property specifies the contract trait to observe. - - - -
- - - - - - - By deployer - - - By contract trait - - - - ```json - { - "if_this": { - "scope": "contract_deployment", - "deployer": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM" - } - } - ``` - - - ```json - { - "if_this": { - "scope": "contract_deployment", - "implement_trait": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.sip09-protocol" - } - } - ``` - - - - - -
- -
diff --git a/content/docs/stacks/clarinet-js-sdk/guides/integration-testing.mdx b/content/docs/stacks/clarinet-js-sdk/guides/integration-testing.mdx deleted file mode 100644 index 95bf87afd..000000000 --- a/content/docs/stacks/clarinet-js-sdk/guides/integration-testing.mdx +++ /dev/null @@ -1,241 +0,0 @@ ---- -title: Integration testing -description: Learn how to write and run integration tests for your Clarity smart contracts using the Clarinet JS SDK and Vitest. ---- - -Integration testing is a crucial step in smart contract development that involves testing how different components of your system work together. The Clarinet JS SDK provides powerful tools for writing and running integration tests, allowing you to simulate complex scenarios and interactions between multiple contracts. - -By using integration tests, you can ensure that your smart contracts function correctly as part of a larger system and catch potential issues that might not be apparent in unit tests alone. - -In this guide, you will: - -1. [Set up a Clarinet project with a `defi` contract.](#set-up-a-clarinet-project) -2. [Write an integration test for the smart contract.](#test-the-deposit-and-borrow-functionality) -3. [Run tests and generate coverage reports.](#run-tests-and-generate-coverage-reports) - ---- - -## Set up a Clarinet project - -Start by creating a new Clarinet project. This command will create a new directory named `defi` and set up a basic Clarinet project inside it. - -```terminal -$ clarinet new stx-defi -$ cd stx-defi -``` - -After changing into your project directory, run `npm install` to install the package dependencies for testing. - -```terminal -$ npm install -``` - -We are going to use the same `defi` contract that we used in the [unit testing guide](/stacks/clarinet-js-sdk/guides/unit-testing), but with some additional functionality - the ability to `borrow` STX from the contract. If you don't have this project set up already, follow the steps below: - -```terminal -$ clarinet contract new defi -``` - -Then, inside your `defi.clar` file, copy and paste the following contract code: - -```clarity -;; Error constants for various failure scenarios. -(define-constant err-overborrow (err u300)) - -;; The interest rate for loans, represented as 10% (out of a base of 100). -(define-data-var loan-interest-rate uint u10) ;; Representing 10% interest rate - - -;; Holds the total amount of deposits in the contract, initialized to 0. -(define-data-var total-deposits uint u0) - -;; Maps a user's principal address to their deposited amount. -(define-map deposits { owner: principal } { amount: uint }) - -;; Maps a borrower's principal address to their loan details: amount and the last interaction block. -(define-map loans principal { amount: uint, last-interaction-block: uint }) - -;; Public function for users to deposit STX into the contract. -;; Updates their balance and the total deposits in the contract. -(define-public (deposit (amount uint)) - (let - ( - ;; Fetch the current balance or default to 0 if none exists. - (current-balance (default-to u0 (get amount (map-get? deposits { owner: tx-sender })))) - ) - ;; Transfer the STX from sender = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM" to recipient = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.defi (ie: contract identifier on the chain!)". - (try! (stx-transfer? amount tx-sender (as-contract tx-sender))) - ;; Update the user's deposit amount in the map. - (map-set deposits { owner: tx-sender } { amount: (+ current-balance amount) }) - ;; Update the total deposits variable. - (var-set total-deposits (+ (var-get total-deposits) amount)) - ;; Return success. - (ok true) - ) -) - -;; Public function for users to borrow STX based on their deposits. -(define-public (borrow (amount uint)) - (let - ( - ;; Fetch user's deposit or default to 0. - (user-deposit (default-to u0 (get amount (map-get? deposits { owner: tx-sender })))) - ;; Calculate the maximum amount the user is allowed to borrow. (which will be upto HALF of what they deposited) - (allowed-borrow (/ user-deposit u2)) - ;; Fetch current loan details or default to initial values. - (current-loan-details (default-to { amount: u0, last-interaction-block: u0 } (map-get? loans tx-sender ))) - ;; Calculate accrued interest on the current loan. - (accrued-interest (calculate-accrued-interest (get amount current-loan-details) (get last-interaction-block current-loan-details))) - ;; Calculate the total amount due including interest. - (total-due (+ (get amount current-loan-details) (unwrap-panic accrued-interest))) - ;; Calculate the new loan total after borrowing additional amount. - (new-loan (+ amount)) - ) - ;; Ensure the requested borrow amount does not exceed the allowed amount. - (asserts! (<= new-loan allowed-borrow) err-overborrow) - ;; Transfer the borrowed STX to the user. - (let - ( - (recipient tx-sender) - ) - (try! (as-contract (stx-transfer? amount tx-sender recipient))) - ) - ;; Update the user's loan details in the map. - (map-set loans tx-sender { amount: new-loan, last-interaction-block: block-height }) - ;; Return success. - (ok true) - ) -) - -;; Read-only function to get the total balance by tx-sender -(define-read-only (get-balance-by-sender) - (ok (map-get? deposits { owner: tx-sender })) -) - -;; Read-only function to get the total amount owed by the user. -(define-read-only (get-amount-owed) - (let - ( - ;; Fetch current loan details or default to initial values. - (current-loan-details (default-to { amount: u0, last-interaction-block: u0 } (map-get? loans tx-sender ))) - ;; Calculate accrued interest on the current loan. - (accrued-interest (calculate-accrued-interest (get amount current-loan-details) (get last-interaction-block current-loan-details))) - ;; Calculate the total amount due including interest. - (total-due (+ (get amount current-loan-details) (unwrap-panic accrued-interest))) - ) - ;; Return the total amount due. - (ok total-due) - ) -) - -;; Private function to calculate the accrued interest on a loan. -(define-private (calculate-accrued-interest (principal uint) (start-block uint)) - (let - ( - ;; Calculate the number of blocks elapsed since the last interaction. - (elapsed-blocks (- block-height start-block)) - ;; Calculate the interest based on the principal, rate, and elapsed time. - (interest (/ (* principal (var-get loan-interest-rate) elapsed-blocks) u10000)) - ) - ;; Ensure the loan started in the past (not at block 0). - (asserts! (not (is-eq start-block u0)) (ok u0)) - ;; Return the calculated interest. - (ok interest) - ) -) -``` - -Run `clarinet check` to ensure that your smart contract is valid and ready for testing. - - -You can find the full code for this project in [this repo](https://github.com/hirosystems/clarity-examples/tree/main/examples/stx-defi). - - -## Test the deposit and borrow functionality - -In order to `borrow` STX from the contract, users must first `deposit` STX into it. Therefore, we need to write an integration test that simulates the interaction between these two functions. - -Inside of your `defi.test.ts` file, replace the boilerplate code and add the following: - -```typescript -import { describe, it, expect } from 'vitest'; -import { Cl } from '@stacks/transactions'; - -const accounts = simnet.getAccounts(); -const wallet1 = accounts.get('wallet_1')!; - -describe('stx-defi', () => { - it('borrows 10 and verifies the amount owed to be 10', () => { - simnet.callPublicFn('defi', 'deposit', [Cl.uint(1000)], wallet1); - const totalDeposits = simnet.getDataVar('defi', 'total-deposits'); - expect(totalDeposits).toBeUint(1000); - - simnet.callPublicFn('defi', 'borrow', [Cl.uint(10)], wallet1); - const { result } = simnet.callReadOnlyFn('defi', 'get-amount-owed', [], wallet1); - expect(result).toBeOk(Cl.uint(10)); - }); -}); -``` - -In this integration test, we're simulating a scenario where a user deposits STX into the DeFi contract and then borrows against that deposit. Let's walk through the process step by step. - -We start by simulating a deposit of 1000 STX from `wallet1`. To do this, we use the `callPublicFn` method from the Clarinet JS SDK `simnet` object, which allows us to call public functions in our smart contract just as we would on the actual blockchain. - -After making the deposit, we want to verify that it was successful. We do this by checking the total deposits in the contract using `getDataVar`. - -This handy method lets us peek at the value of data variables defined in your contract. - - -To learn more about available methods for integration testing, check out the [reference page](/stacks/clarinet-js-sdk/references/methods). - - -To ensure the deposit was recorded correctly, we use a custom matcher, `toBeUint`. This matcher is specifically designed to check if a value is a Clarity unsigned integer with the exact value we expect. - -With the deposit confirmed, we simulate `wallet1` borrowing 10 STX. We do this with another call to `callPublicFn`, this time invoking the `borrow` function of our contract. - -After the borrowing operation, we want to check how much `wallet1` owes. We use `callReadOnlyFn` to call a read-only function named `get-amount-owed` in our contract. - -Finally, we verify the amount owed using another custom matcher, `toBeOk(Cl.uint(10))`. This matcher is particularly useful because it checks two things at once: - -1. That our contract returned a successful Clarity response type. -2. That the value returned is a Clarity unsigned integer with the exact value we expect (`10`). - -These custom matchers and simnet methods are powerful tools and allow you to simulate complex interactions with your smart contracts and make detailed assertions about the results. - -## Run tests and generate coverage reports - -To run your tests, use: - -```terminal -$ npm run test -``` - -To generate a coverage report, use: - -```terminal -$ npm run coverage -``` - -This will run your tests and produce a detailed coverage report, helping you identify any untested parts of your contract. - ---- - -## Next steps - - - - - - diff --git a/content/docs/stacks/clarinet-js-sdk/guides/mainnet-execution-simulation.mdx b/content/docs/stacks/clarinet-js-sdk/guides/mainnet-execution-simulation.mdx deleted file mode 100644 index 5381652f1..000000000 --- a/content/docs/stacks/clarinet-js-sdk/guides/mainnet-execution-simulation.mdx +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: Mainnet execution simulation -description: Learn how to test your Clarity smart contracts against real-world Mainnet data using the Clarinet JS SDK's Mainnet Execution Simulation (MXS) feature. ---- - -Mainnet Execution Simulation (MXS) allows you to test your Clarity smart contracts using actual data and state from the Stacks mainnet. This powerful feature helps ensure your contracts behave as expected in a live environment by enabling you to: - -- Test contract interactions against real-world data and dependencies. -- Simulate any historical or recent mainnet transaction to observe its outcome or evaluate its execution cost. - -This guide focuses on using MXS within the context of unit tests using Vitest, which is the primary use case. - -In this guide, you will learn: - -1. [What Mainnet Execution Simulation (MXS) is and why it's valuable](#what-is-mainnet-execution-simulation). -2. [How to enable and configure MXS in your Clarinet project](#enable-mxs-in-your-project). -3. [How to write and run unit tests using MXS](#write-tests-with-mxs). -4. [Current limitations of the MXS feature](#limitations). - ---- - -## What is Mainnet execution simulation? - -When developing smart contracts, testing against realistic conditions is crucial. Simnet provides an isolated testing environment, but it lacks the complexity and historical state of the live Stacks mainnet. - -MXS bridges this gap by allowing your unit tests, executed via the Clarinet JS SDK and Vitest, to interact with a simulated environment that mirrors the Stacks mainnet state at a specific block height. This means you can: - -- **Validate contract logic against real data:** Call mainnet contracts or check data derived from mainnet state directly within your tests. -- **(Re)simulate transactions:** Execute specific mainnet transactions to analyze their exact results, trace their execution, or estimate their costs without deploying or spending actual STX. - ---- - -## Enable MXS in your project - -To use MXS in your unit tests, you need to enable it in your `Clarinet.toml` file. Add the following section: - -```toml -c -[repl.remote_data] -# Enable mainnet execution simulation -enabled = true -# Specify the Stacks block height to fork from (optional, default to latest) -initial_height = 522000 -# Specify the API URL to use (optional, default to https://api.hiro.so) -api_url = 'https://api.hiro.so' -``` - -- `enabled = true`: This flag activates the MXS feature for your tests. -- `initial_height = `: This optional setting specifies the Stacks block height at which the simulation should start. - - If omitted, Clarinet defaults to the latest finalized Stacks block height at the time of execution. - - **Recommendation:** Setting a specific `initial_height` is highly recommended for consistent and reproducible test results, as the mainnet state constantly changes. -- `api_url = 'https://api.hiro.so'`: This optional setting specifies the API URL to use. - - -You can explore a project demonstrating MXS usage with a Pyth oracle contract in [this repository](https://github.com/hirosystems/clarinet-pyth-example). - - ---- - -## Write tests with MXS - -Once MXS is enabled, your Vitest tests running via the Clarinet JS SDK (`npm run test`) will automatically operate against the specified mainnet state. You don't need to change your test writing approach significantly. - -The `simnet` object, typically used for interacting with the simulated environment in tests, will now interact with the mainnet state snapshot defined by `initial_height`. - -For example, you could write a test that calls a function on a mainnet contract like `pox-4`: - -```ts -cn -import { describe, it, expect } from "vitest"; -import { Cl } from "@stacks/transactions"; - -const accounts = simnet.getAccounts(); -const deployer = accounts.get("deployer")!; // Or any other account - -describe("pox-4 reward cycle", () => { - it("returns pox reward cycle id", () => { - // Call the current-pox-reward-cycle function on the mainnet pox-4 contract - const call = simnet.callReadOnlyFn( - "SP000000000000000000002Q6VF78.pox-4", // Mainnet pox-4 contract principal - "current-pox-reward-cycle", - [], // No arguments needed for this function - deployer // Caller address doesn't impact read-only calls usually - ); - - // Assert that the call was successful and returns cycle number u109 - expect(call.result).toBeUint(109); - - // You can further assert other values by tweaking the initial_height in `Clarinet.toml` - // For example, if initial_height = 299000, the value might be: - // expect(call.result).toBeUint(98); - console.log("Current POX reward cycle:", Cl.prettyPrint(call.result)); - }); -}); - -``` - -This test uses `simnet.callReadOnlyFn` just like in standard unit tests, but because MXS is enabled, the call targets the actual `pox-4` contract state at the `initial_height` specified in `Clarinet.toml`. - ---- - -## Test MXS in the playground - -You can quickly experiment with MXS without setting up a full project using the Clarinet Playground. - -1. Go to: [https://play.hiro.so/?remote_data=true](https://play.hiro.so/?remote_data=true) - - The `?remote_data=true` query parameter enables MXS. -2. In the command input field, call a mainnet contract function. For example, to call `current-pox-reward-cycle` on `pox-4`: - ```terminal - $ contract-call? 'SP000000000000000000002Q6VF78.pox-4 current-pox-reward-cycle - ``` -The playground will execute the call against the latest mainnet state and display the result. - ---- - -## Setting up an API Key for MXS - -While you can use Mainnet Execution Simulation (MXS) without an API key, you may run into rate limits that could disrupt your development workflow. We recommend using an API key to ensure reliable and uninterrupted access to MXS functionality. - -To use an API key with MXS, set the `HIRO_API_KEY` environment variable in your terminal. - -```terminal -$ export HIRO_API_KEY="" -``` - -Replace `` with the actual API key you obtain from the Hiro Platform. - - -If you're interested in obtaining an API key, you can generate one for free in the [Hiro Platform](https://platform.hiro.so) by creating an account. - -All API keys are set by default to the free "starter" account tier, which comes with a 900RPM rate limit. For builders who need access to higher API rate limits, dedicated support channels, and reliability guarantees through SLAs, you can upgrade your account tier through the Hiro Platform. - - -Currently, the `HIRO_API_KEY` is specifically utilized by the Mainnet Execution Simulation (MXS) feature within Clarinet. Other Clarinet features do not use this API key at this time. - ---- - -## Limitations - -Currently, MXS does not support Clarity functions that rely on querying specific information related to burn blocks or miner tenures. The following functions are **not implemented** in the simulation environment: - -- `(get-burn-block-info? pox-addrs )` -- `(get-tenure-info? block-reward )` -- `(get-tenure-info? miner-spend-total )` -- `(get-tenure-info? miner-spend-winner )` - -Calls to these functions within an MXS context will result in runtime errors. - ---- - -## Next steps - - - - - diff --git a/content/docs/stacks/clarinet-js-sdk/guides/unit-testing.mdx b/content/docs/stacks/clarinet-js-sdk/guides/unit-testing.mdx deleted file mode 100644 index ac6298787..000000000 --- a/content/docs/stacks/clarinet-js-sdk/guides/unit-testing.mdx +++ /dev/null @@ -1,233 +0,0 @@ ---- -title: Unit testing -description: Learn how to write and run unit tests for your Clarity smart contracts using the Clarinet JS SDK and Vitest. ---- - -import { Accordions, Accordion } from 'fumadocs-ui/components/accordion'; - -Unit testing is the process of testing individual components or functions of smart contracts to ensure they work as expected. The Clarinet JS SDK provides a testing framework that allows you to write these tests using the Vitest testing framework, helping you catch bugs and errors early in the development process. - -In this guide, you will: - -1. [Set up a new Clarinet project with a `defi` contract](#set-up-a-new-clarinet-project). -2. [Write a unit test covering the `deposit` function](#test-the-deposit-function). -3. [Run tests and generate coverage reports](#run-tests-and-generate-coverage-reports). - ---- - -## Set up a new Clarinet project - -Start by creating a new project with the Clarinet CLI. The command below will create a project structure inside of `defi` with the necessary files and folders, including the Clarinet JS SDK already set up for testing. - -```terminal -$ clarinet new stx-defi -$ cd stx-defi -``` - -After changing into your project directory, run `npm install` to install the package dependencies for testing. - -```terminal -$ npm install -``` - -Since the smart contract code is out of scope for this guide, we are going to use a pre-existing contract. First, generate a new file using the `clarinet contract new` command in order to set up your project with the necessary configuration and test files. - -```terminal -$ clarinet contract new defi -``` - -Now, inside your `defi.clar` file, copy and paste the following contract code: - -```clarity -;; Holds the total amount of deposits in the contract, initialized to 0. -(define-data-var total-deposits uint u0) - -;; Maps a user's principal address to their deposited amount. -(define-map deposits { owner: principal } { amount: uint }) - -;; Public function for users to deposit STX into the contract. -;; Updates their balance and the total deposits in the contract. -(define-public (deposit (amount uint)) - (let - ( - ;; Fetch the current balance or default to 0 if none exists. - (current-balance (default-to u0 (get amount (map-get? deposits { owner: tx-sender })))) - ) - ;; Transfer the STX from sender = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM" to recipient = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.defi (ie: contract identifier on the chain!)". - (try! (stx-transfer? amount tx-sender (as-contract tx-sender))) - ;; Update the user's deposit amount in the map. - (map-set deposits { owner: tx-sender } { amount: (+ current-balance amount) }) - ;; Update the total deposits variable. - (var-set total-deposits (+ (var-get total-deposits) amount)) - ;; Return success. - (ok true) - ) -) - -;; Read-only function to get the total balance by tx-sender -(define-read-only (get-balance-by-sender) - (ok (map-get? deposits { owner: tx-sender })) -) -``` - -Run `clarinet check` to ensure that your smart contract is valid and ready for testing. - - -You can find the full code for this project in [this repo](https://github.com/hirosystems/clarity-examples/tree/main/examples/stx-defi). - - -## Test the deposit function - -This `deposit` function allows users to deposit STX into the contract, updating their balance inside a `deposits` map and adding to the total deposits stored in a `total-deposits` variable. The key tests we want to cover are that the deposit is successful and that the user's balance, as well as the contract's total deposits, are updated correctly. - -Inside of your `defi.test.ts` file, replace the boilerplate code and add the following: - -```typescript -import { describe, it, expect } from 'vitest'; -import { Cl } from '@stacks/transactions'; - -const accounts = simnet.getAccounts(); -const wallet1 = accounts.get('wallet_1')!; -``` - -These imports provide the testing framework and utilities we need. We also get the `wallet_1` account, which will act as our test user. - -Next, define the test suite and the specific test case: - -```typescript -describe('stx-defi', () => { - it('allows users to deposit STX', () => { - // Test code will go here - }); -}); -``` - -This structure comes from our Vitest integration, and it organizes our tests and describes what we're testing. The `describe` block groups multiple test cases together, while the `it` block represents a single test case. - -Now, let's simulate a deposit. Inside of the `it` block, define the amount to deposit and call the `deposit` function: - -```typescript -const amount = 1000; -const deposit = simnet.callPublicFn('defi', 'deposit', [Cl.uint(amount)], wallet1); -``` - -This code simulates a deposit by calling the `deposit` function, using the `callPublicFn` method from the Clarinet JS SDK, in our contract with a specified amount, just as a user would in the real world. - -After making the deposit, create an assertion to verify that the call itself was successful and returns an `ok` response type with the value `true`: - -```typescript -expect(deposit.result).toBeOk(Cl.bool(true)); -``` - -Run `npm run test` to confirm that this test passes. - -Let's go over some of the code in this assertion: - -- `expect` is a function from Vitest that makes an assertion about the value we expect to get back from the `deposit` function. - -But how do we test against Clarity types and values? This is where the `Cl` and `toBeOk` helpers come in. - -- `toBeOk` is a custom matcher function built into Vitest that checks if the result of the deposit call is an `Ok` response, which is a Clarity type. This is important because it confirms that the deposit transaction was processed successfully. -- `Cl` helper is from the `@stacks/transactions` package and is used to create Clarity values in JavaScript. In this case, it's used to create a Clarity boolean with the value of `true`. - - -To see more custom matcher examples, check out the [reference page](/stacks/clarinet-js-sdk/references/custom-matchers). - - -Once we can confirm that the deposit was successful, write a test to verify that the contract's total deposits have been updated correctly. - -```typescript -const totalDeposits = simnet.getDataVar('defi', 'total-deposits'); -expect(totalDeposits).toBeUint(amount); -``` - -Run `npm run test` again to confirm that this test also passes. - -This check ensures that the contract accepted our deposit without any issues. - -Lastly, verify that the user's balance has been updated correctly: - -```typescript -const balance = simnet.callReadOnlyFn('defi', 'get-balance-by-sender', [], wallet1); -expect(balance.result).toBeOk( - Cl.some( - Cl.tuple({ - amount: Cl.uint(amount), - }) - ) -); -``` - -We call the `get-balance-by-sender` function and check if it matches the amount we just deposited. - -By following these steps, our test comprehensively verifies that the `deposit` function works as intended, updating individual balances and total deposits accurately. - - - -```typescript - import { describe, it, expect } from 'vitest'; - import { Cl } from '@stacks/transactions'; - - const accounts = simnet.getAccounts(); - const wallet1 = accounts.get('wallet_1')!; - - describe('stx-defi', () => { - it('allows users to deposit STX', () => { - const amount = 1000; - const deposit = simnet.callPublicFn('defi', 'deposit', [Cl.uint(amount)], wallet1); - expect(deposit.result).toBeOk(Cl.bool(true)); - - const totalDeposits = simnet.getDataVar('defi', 'total-deposits'); - expect(totalDeposits).toBeUint(amount); - - const balance = simnet.callReadOnlyFn('defi', 'get-balance-by-sender', [], wallet1); - expect(balance.result).toBeOk( - Cl.some( - Cl.tuple({ - amount: Cl.uint(amount), - }) - ) - ); - }); - }); -``` - - - -## Run tests and generate coverage reports - -To run your tests, use: - -```terminal -$ npm run test -``` - -To generate a coverage report, use: - -```terminal -$ npm run coverage -``` - -This will run your tests and produce a detailed coverage report, helping you identify any untested parts of your contract. - ---- - -## Next steps - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/clarinet-js-sdk/index.mdx b/content/docs/stacks/clarinet-js-sdk/index.mdx deleted file mode 100644 index b6dedd216..000000000 --- a/content/docs/stacks/clarinet-js-sdk/index.mdx +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Overview -description: The Clarinet JS SDK is a JavaScript library used to write unit tests for Clarity smart contracts. ---- - -import { SecondaryCard } from '@/components/card'; - -The Clarinet JS SDK allows you to write unit tests for your Clarity smart contracts. You can theoretically use any JavaScript test framework, but the SDK supports Vitest out of the box. This SDK leverages `simnet`, a simulated network that offers a rapid feedback loop for initial testing. - -Here is a non-exhaustive list of some of simnet's use-cases: - -- Call public and read-only functions from smart contracts -- Get Clarity maps or data-var values -- Get contract interfaces (available functions and data) -- Write unit tests for Clarity smart contracts - - - The SDK requires Node.js >= 18.0 and NPM to be installed. - - -## Guides - - - - - - -## Related tools - -- **[Clarinet](/stacks/clarinet)**: Build your app in a local environment on Stacks. -- **[Stacks.js](/stacks/stacks.js)**: Don’t reinvent the wheel and build faster with a JS library that handles basic blockchain functionality. -- **[Stacks Blockchain API](/stacks/api)**: Fetch data and broadcast transactions with the Stacks Blockchain API. - -
- - -Reach out to us on the #clarinet channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET. - diff --git a/content/docs/stacks/clarinet-js-sdk/installation.mdx b/content/docs/stacks/clarinet-js-sdk/installation.mdx deleted file mode 100644 index 8a4131de2..000000000 --- a/content/docs/stacks/clarinet-js-sdk/installation.mdx +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Installation -description: Clarinet JS SDK can be installed using your preferred package manager. -toc: false ---- - - - The SDK requires Node.js >= 18.0 and NPM to be installed. - - -```package-install -@hirosystems/clarinet-sdk -``` diff --git a/content/docs/stacks/clarinet-js-sdk/meta.json b/content/docs/stacks/clarinet-js-sdk/meta.json deleted file mode 100644 index ce117ac35..000000000 --- a/content/docs/stacks/clarinet-js-sdk/meta.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "title": "Clarinet JS SDK", - "root": true, - "pages": [ - "---Clarinet JS SDK---", - "index", - "installation", - "quickstart", - "---Guides---", - "guides/unit-testing", - "guides/integration-testing", - "guides/mainnet-execution-simulation", - "---Reference---", - "references/simnet", - "references/properties", - "references/methods", - "references/custom-matchers" - ] -} diff --git a/content/docs/stacks/clarinet-js-sdk/quickstart.mdx b/content/docs/stacks/clarinet-js-sdk/quickstart.mdx deleted file mode 100644 index b31b04294..000000000 --- a/content/docs/stacks/clarinet-js-sdk/quickstart.mdx +++ /dev/null @@ -1,222 +0,0 @@ ---- -title: Quickstart -description: Learn how to test a simple counter contract using the Clarinet JS SDK. ---- - -import { ChevronRight, Code, Terminal } from 'lucide-react'; -import { File, Folder, Files } from 'fumadocs-ui/components/files'; -import { Steps, Step } from 'fumadocs-ui/components/steps'; -import { SmallCard } from '@/components/card'; - -In this quickstart guide, you will initialize a simulated development network for testing a smart contract using the Clarinet JS SDK. You'll learn how to initialize your project, interact with a smart contract, call its functions, and test the results. - -Check out the [methods](/stacks/clarinet-js-sdk/references/methods) page for the Clarinet JS SDK to learn about the different ways that you can interact with simnet. - ---- - - - - ## Importing dependencies - - Before we dive in, navigate to your project and import the `Cl` helper from the `@stacks/transactions` package in your test file. - - - - - - - - - - - - - - - - - ```ts counter.test.ts - import { describe, expect, it } from "vitest"; - import { Cl } from "@stacks/transactions"; - ``` - - The `Cl` namespace simplifies the process of creating and handling Clarity values. This functionality is particularly useful in testing environments where developers need to simulate contract interactions accurately. - - - - ## Retrieve an account from the simnet - - For most test cases, you'll want to retrieve an account from the network in order to interact with your smart contracts. The following code uses the `getAccounts` method to achieve this. - - ```ts counter.test.ts - import { describe, expect, it } from "vitest"; - import { Cl } from "@stacks/transactions"; - - const accounts = simnet.getAccounts(); - const wallet = accounts.get("wallet_1")!; - ``` - - - The `--stacks` flag is required and allows you to specify the network to scan. Other options include `--bitcoin`. - - - - ## Write your first test - - The process for writing tests for smart contracts with the Clarinet JS SDK follows a structured approach similar to testing in JavaScript. Here's a breakdown of the steps involved: - - 1. Define the group of tests you want to run using the `describe` block. - 2. Define the test you want to run using the `it` block. - 3. Call the function and assert the result using the `expect` function. - - Now that you understand the key components for writing tests, start by writing a test that ensures the `counter` contract has been deployed. - - ```ts counter.test.ts - describe("counter contract", () => { - it("ensures the contract is deployed", () => { - const contractSource = simnet.getContractSource("counter"); - expect(contractSource).toBeDefined(); - }); - }); - ``` - - - ## Test the count-up function - - Now it's time to call a public function and assert the result. The count-up function is expected to increment the count of the user's principal by 1. Write a test to ensure this behaves as expected. - - ```ts counter.test.ts - describe("counter contract", () => { - it("increments the count of the user's principal by 1", () => { - const countUpCall = simnet.callPublicFn("counter", "count-up", [], wallet); - expect(countUpCall.result).toBeOk(Cl.bool(true)); - - const getCountCall = simnet.callReadOnlyFn( - "counter", - "get-count", - [Cl.principal(wallet)], - wallet - ); - expect(getCountCall.result).toBeUint(1); - }); - }); - ``` - - Above, the `count-up` function is called, and the result is asserted to return an `(ok true)`. Then, the count for the user's principal is retrieved and asserted to be `u1`. - - -

The toBeOk and toBeUint methods are used to ensure the `count-up` function returns the proper Clarity values. For more details, check out the [custom matchers](/stacks/clarinet-js-sdk/references/custom-matchers) page.

-
-
- - ## Run your tests - - Every generated project comes with a package.json file that contains the necessary dependencies and scripts to run your tests. - - ```json package.json - "scripts": { - "test": "vitest run", - "test:report": "vitest run -- --coverage --costs", - "test:watch": "chokidar \"tests/**/*.ts\" \"contracts/**/*.clar\" -c \"npm run test:report\"" - } - ``` - - You can now run your tests, with your preferred package manager, by executing the following command: - - ```terminal - $ npm run test - ``` - - - ## Run your tests with code coverage and cost analysis - - Clarinet can automatically also produce a code coverage report and cost analysis on the test you ran. - - ```json package.json - "scripts": { - "test": "vitest run", - "test:report": "vitest run -- --coverage --costs", - "test:watch": "chokidar \"tests/**/*.ts\" \"contracts/**/*.clar\" -c \"npm run test:report\"" - } - ``` - - By running the `npm run test:report` command in your terminal, an `lcov.info` and `costs-reports.json` file will appear in your root folder: - - - - - - - - - - - - - - - - - - - The `costs-reports.json` file will output the cost analysis for every function ran in your tests. Since the `count-up` function was used in our test, this is how the cost analysis output would look like for that function: - - ```json costs-reports.json - { - "test_name": "tests/counter.test.ts__counter contract__increments the count of the user's principal by 1", - "contract_id": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter", - "method": "count-up", - "args": [], - "cost_result": { - "total": { - "write_length": 41, - "write_count": 1, - "read_length": 245, - "read_count": 5, - "runtime": 4752 - }, - "limit": { - "write_length": 15000000, - "write_count": 15000, - "read_length": 100000000, - "read_count": 15000, - "runtime": 5000000000 - }, - "memory": 40, - "memory_limit": 100000000 - } - } - ``` - - To access and read the `lcov.info` file in a human-readable format, we can first install the `lcov` [package](https://github.com/linux-test-project/lcov) that helps generate a graphical front-end for coverage testing tools. - - ```terminal - $ brew install lcov - ``` - - Then we'll run the `genhtml` command below with the following options. This command and its options will generate the actual html file, add in additional branch coverage, and will automatically store the files in a new folder called `coverage`. - - ```terminal - $ genhtml lcov.info --branch-coverage -o coverage - ``` - - You can then navigate into the new `coverage` folder and run the command `open index.html` to view your coverage report. In addition, a summary of the coverage report will be outputted in the terminal. - -
- ---- - -## Next steps - - - - - diff --git a/content/docs/stacks/clarinet-js-sdk/references/custom-matchers.mdx b/content/docs/stacks/clarinet-js-sdk/references/custom-matchers.mdx deleted file mode 100644 index 5eeb90948..000000000 --- a/content/docs/stacks/clarinet-js-sdk/references/custom-matchers.mdx +++ /dev/null @@ -1,996 +0,0 @@ ---- -title: Custom Matchers -description: A set of Vitest matchers that can be used to make assertions on Clarity values with the Clarinet JS SDK. -toc: false ---- - -import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; -import { Badge } from '@/components/ui/badge'; -import { Root, API, APIExample, Property, Info } from '@/components/layout'; -import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; - - - - - - - -# `toHaveClarityType` - -Check that a value has the right Clarity type, without checking its value. - -## Parameters - - - -The Clarity type that the expected value should have. - - - - - - - - - - - Checking for an ok response - - - - ```ts - const { result } = simnet.callPublicFn( - 'counter', - 'increment', - [], - simnet.deployer - ); - - expect(result).toHaveClarityType(ClarityType.ResponseOk); - ``` - - - - ```clarity counter.clar - (define-data-var count uint u0) - - (define-public (increment) - (begin - (var-set count (+ (var-get count) u1)) - (ok (var-get count)) - ) - ) - ``` - - - ```ts - toHaveClarityType(expectedType: ClarityType) - ``` - - - - - - - - - - - - - -# `toBeOk` - -Check that a response is `(ok )` and has the expected value. Any Clarity value can be passed. - -## Parameters - - - -The `ClarityValue` that the expected value should have. - - - - - - - - - - - Checking for an ok response with a specific value - - - - ```ts - const { result } = simnet.callPublicFn( - 'counter', - 'increment', - [], - simnet.deployer - ); - - expect(result).toBeOk(Cl.uint(1)); - ``` - - - - ```clarity counter.clar - (define-data-var count uint u0) - - (define-public (increment) - (begin - (var-set count (+ (var-get count) u1)) - (ok (var-get count)) - ) - ) - ``` - - - ```ts - toBeOk(expected: ClarityValue) - ``` - - - - - - - - - - - - - -# `toBeErr` - -Check that a response is `(err )` and has the expected value. Any Clarity value can be passed. - -## Parameters - - - -The `ClarityValue` that the expected value should have. - - - - - - - - - - - Checking for an err response with a specific value - - - - ```ts - const { result } = simnet.callPublicFn( - 'counter', - 'add', - [Cl.uint(19)], - simnet.deployer - ); - - expect(result).toBeErr(Cl.uint(500)); - ``` - - - - ```clarity counter.clar - (define-constant TOO_BIG u10) - (define-data-var count uint u0) - - (define-public (add (amount uint)) - (begin - (let ((new-count (+ (var-get count) amount))) - (if (<= new-count TOO_BIG) - (begin - (var-set count new-count) - (ok (var-get count)) - ) - (err u500) - ) - ) - ) - ) - ``` - - - ```ts - toBeErr(expected: ClarityValue) - ``` - - - - - - - - - - - - - -# `toBeSome` - -Check that a response is `(some )` and has the expected value. Any Clarity value can be passed. - -## Parameters - - - -The `ClarityValue` that the expected value should have. - - - - - - - - - - - Checking for an optional value - - - - ```ts - const { result } = simnet.callReadOnlyFn( - 'pool', - 'get-participant', - [Cl.standardPrincipal('ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5')], - simnet.deployer - ); - - expect(result).toBeSome(Cl.bool(true)); - ``` - - - - ```clarity pool.clar - (define-map Participants principal bool) - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - - (define-read-only (get-participant (who principal)) - (map-get? ParticipantStatus who) - ) - - (map-set Participants 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5 true) - (map-set ParticipantStatus 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5 { enrollmentBlock: u1, contributionAmount: u19000000 }) - ``` - - - ```ts - toBeSome(expected: ClarityValue) - ``` - - - - - - - - - - - - - -# `toBeNone` - -Check that a response is `(none)`. - - - - - - - - - Checking for a none value - - - - ```ts - const { result } = simnet.callReadOnlyFn( - 'pool', - 'get-participant', - [Cl.standardPrincipal('ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5')], - simnet.deployer - ); - - expect(result).toBeNone(); - ``` - - - - ```clarity pool.clar - (define-map Participants principal bool) - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - - (define-read-only (get-participant (who principal)) - (map-get? ParticipantStatus who) - ) - ``` - - - ```ts - toBeNone() - ``` - - - - - - - - - - - - - -# `toBeBool` - -Asserts the value of Clarity boolean (`true` or `false`). - -## Parameters - - - -The `boolean` that the expected value should have. - - - - - - - - - - - Checking for a boolean value - - - - ```ts - const { result } = simnet.callReadOnlyFn( - 'pool', - 'has-contributed', - [Cl.standardPrincipal('ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM')], - simnet.deployer - ); - - expect(result).toBeBool(true); - ``` - - - - ```clarity pool.clar - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - - (define-read-only (has-contributed (who principal)) - (is-some (get contributionAmount (map-get? ParticipantStatus who))) - ) - - (map-set ParticipantStatus tx-sender { enrollmentBlock: u1, contributionAmount: u19000000 }) - ``` - - - ```ts - toBeBool(expected: boolean) - ``` - - - - - - - - - - - - -# `toBeInt` - -Asserts the value of a Clarity integer. - -## Parameters - - - -The `integer` that the expected value should have. - - - - - - - - - - - Checking for an integer value - - - - ```ts - const { result } = simnet.callReadOnlyFn( - 'counter', - 'increment', - [], - simnet.deployer - ); - - expect(result).toBeInt(1); // or `1n` - ``` - - - - ```clarity counter.clar - (define-data-var count int 0) - - (define-public (increment) - (begin - (var-set count (+ (var-get count) 1)) - (ok (var-get count)) - ) - ) - ``` - - - ```ts - toBeInt(expected: number | bigint) - ``` - - - - - - - - - - - - - -# `toBeUint` - -Asserts the value of a Clarity unsigned integer. - -## Parameters - - - -The `unsigned integer` that the expected value should have. - - - - - - - - - - - Checking for an unsigned integer value - - - - ```ts - const { result } = simnet.callReadOnlyFn( - 'counter', - 'increment', - [], - simnet.deployer - ); - - expect(result).toBeUint(1); // or `1n` - ``` - - - - ```clarity counter.clar - (define-data-var count uint u0) - - (define-public (increment) - (begin - (var-set count (+ (var-get count) u1)) - (ok (var-get count)) - ) - ) - ``` - - - ```ts - toBeUint(expected: number | bigint) - ``` - - - - - - - - - - - - - -# `toBeAscii` - -Asserts the value of a Clarity string-ascii. - -## Parameters - - - -The `string` that the expected value should have. - - - - - - - - - - - Checking for a string-ascii value - - - - ```ts - const { result } = simnet.callReadOnlyFn( - 'hello-world', - 'say-hi', - [], - simnet.deployer - ); - - expect(result).toBeAscii('Hello World'); - ``` - - - - ```clarity hello-world.clar - (define-read-only (say-hi) - "Hello World" - ) - ``` - - - ```ts - toBeAscii(expected: string) - ``` - - - - - - - - - - - - - -# `toBeUtf8` - -Asserts the value of a Clarity string-utf8. - -## Parameters - - - -The `string` that the expected value should have. - - - - - - - - - - - Checking for a string-utf8 value - - - - ```ts - const { result } = simnet.callReadOnlyFn( - 'hello-world', - 'say-hi', - [], - simnet.deployer - ); - - expect(result).toBeUtf8('Hello World'); - ``` - - - - ```clarity hello-world.clar - (define-read-only (say-hi) - u"Hello World" - ) - ``` - - - ```ts - toBeUtf8(expected: string) - ``` - - - - - - - - - - - - - -# `toBePrincipal` - -Asserts the value of a Clarity principal. - -The principal can be a standard or a contract principal. - -## Parameters - - - -The `string` that the expected value should have. - - - - - - - - - - - Checking for a standard principal - - - Checking for a contract principal - - - - ```ts - const deployer = simnet.deployer; - - expect(Cl.standardPrincipal(deployer)).toBePrincipal(deployer); - ``` - - - - ```ts - toBePrincipal(expected: string) - ``` - - - - - ```ts - const contract = `${simnet.deployer}.hello-world`; - - expect(Cl.contractPrincipal(contract)).toBePrincipal(contract); - ``` - - - - ```ts - toBePrincipal(expected: string) - ``` - - - - - - - - - - - - - -# `toBeBuff` - -Asserts the value of a Clarity buffer. It takes an ArrayBuffer as an input. - -For building a buffer, `@stacks/transactions` provides some helper functions: - -- `bufferFromAscii` -- `bufferFromUtf8` -- `bufferFromHex` - -## Parameters - - - -The `Uint8Array` buffer that the expected value should have. - - - - - - - - - - - Checking for a Uint8Array buffer - - - Checking for an ASCII string buffer - - - Checking for a hex string buffer - - - - ```ts - const { result } = simnet.callReadOnlyFn( - 'helpers', - 'get-byte-array', - [], - simnet.deployer - ); - - const buffer = Uint8Array.from([1, 2, 3, 4]); - expect(result).toBeBuff(buffer); - ``` - - - - ```clarity helpers.clar - (define-constant BUFFER 0x01020304) - - (define-read-only (get-byte-array) - BUFFER - ) - ``` - - - ```ts - toBeBuff(expected: Uint8Array) - ``` - - - - - ```ts - import { Cl } from '@stacks/transactions'; - - const { result } = simnet.callReadOnlyFn( - 'helpers', - 'get-btc-buffer', - [], - simnet.deployer - ); - - const btc = Cl.bufferFromAscii('btc'); // or Cl.bufferFromUtf8('btc') - - expect(result).toBeBuff(btc.buffer); - ``` - - - - ```clarity helpers.clar - (define-constant ASCII_BTC 0x627463) - - (define-read-only (get-btc-buffer) - ASCII_BTC - ) - ``` - - - ```ts - toBeBuff(expected: Uint8Array) - ``` - - - - - ```ts - import { Cl } from '@stacks/transactions'; - - const { result } = simnet.callReadOnlyFn( - "helpers", - "get-tx-hash", - [], - simnet.deployer - ); - - const tx = Cl.bufferFromHex( - "73e951acd451060f13bdab7bd947136efd80511309a295e876a682ab8a423a7e" - ); - - expect(result).toBeBuff(tx.buffer); - ``` - - - - ```clarity helpers.clar - (define-constant TX_HASH 0x73e951acd451060f13bdab7bd947136efd80511309a295e876a682ab8a423a7e) - - (define-read-only (get-tx-hash) - TX_HASH - ) - ``` - - - ```ts - toBeBuff(expected: Uint8Array) - ``` - - - - - - - - - - - - - -# `toBeList` - -Asserts the value of a Clarity list containing an array of Clarity values. - -## Parameters - - - -The `Uint8Array` buffer that the expected value should have. - - - - - - - - - - - Checking for a list of Clarity values - - - - ```ts - import { Cl } from '@stacks/transactions'; - - const { result } = simnet.callReadOnlyFn( - 'helpers', - 'get-addresses', - [], - simnet.deployer - ); - - expect(result).toBeList( - [ - Cl.standardPrincipal('ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM'), - Cl.standardPrincipal('ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5'), - Cl.standardPrincipal('ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG') - ] - ); - ``` - - - - ```clarity helpers.clar - (define-read-only (get-addresses) - (list - 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM - 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5 - 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG - ) - ) - ``` - - - ```ts - toBeList(expected: ClarityValue[]) - ``` - - - - - - - - - - - - - -# `toBeTuple` - -Asserts the value of a Clarity tuple. - -## Parameters - - - -The `object` of Clarity values that the expected value should have. - - - - - - - - - - - Checking for a tuple - - - - ```ts - import { Cl } from '@stacks/transactions'; - - const { result } = simnet.callReadOnlyFn( - 'pool', - 'get-participant-data', - [Cl.standardPrincipal(simnet.deployer)], - simnet.deployer - ); - - expect(result).toBeTuple({ - enrollmentBlock: Cl.some(Cl.uint(1)), - contributionAmount: Cl.some(Cl.uint(19000000)), - }); - ``` - - - - ```clarity pool.clar - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - - (define-read-only (get-participant (who principal)) - (map-get? ParticipantStatus who) - ) - - (define-read-only (get-participant-data (who principal)) - { - enrollmentBlock: (get enrollmentBlock (map-get? ParticipantStatus who)), - contributionAmount: (get contributionAmount (map-get? ParticipantStatus who)) - } - ) - - (map-set ParticipantStatus tx-sender { enrollmentBlock: u1, contributionAmount: u19000000 }) - ``` - - - ```ts - toBeTuple(expected: Record) - ``` - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/clarinet-js-sdk/references/methods.mdx b/content/docs/stacks/clarinet-js-sdk/references/methods.mdx deleted file mode 100644 index 061197a34..000000000 --- a/content/docs/stacks/clarinet-js-sdk/references/methods.mdx +++ /dev/null @@ -1,2286 +0,0 @@ ---- -title: Methods -description: The Clarinet JS SDK provides several methods that can be used to interact with simnet. -toc: false ---- - -import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; -import { Badge } from '@/components/ui/badge'; -import { Root, API, APIExample, Property, Info } from '@/components/layout'; -import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; - - - - - -# `getAccounts` - -Retrieve a list of all Stacks addresses configured within the project, including wallets, deployers, and faucets. - - - - - - - - - Getting your accounts - - - Selecting a specific account - - - - ```ts - const accounts = simnet.getAccounts(); - ``` - - - - ```ts - Map(10) { - "wallet_7": "ST3PF13W7Z0RRM42A8VZRVFQ75SV1K26RXEP8YGKJ", - "wallet_1": "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5", - "wallet_3": "ST2JHG361ZXG51QTKY2NQCVBPPRRE2KZB1HR05NNC", - "wallet_5": "ST2REHHS5J3CERCRBEPMGH7921Q6PYKAADT7JP2VB", - "wallet_8": "ST3NBRSFKX28FQ2ZJ1MAKX58HKHSDGNV5N7R21XCP", - "wallet_4": "ST2NEB84ASENDXKYGJPQW86YXQCEFEX2ZQPG87ND", - "deployer": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", - "wallet_6": "ST3AM1A56AK2C1XAFJ4115ZSV26EB49BVQ10MGCS0", - "wallet_2": "ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG", - "faucet": "STNHKEPYEPJ8ET55ZZ0M5A34J0R3N5FM2CMMMAZ6", - } - ``` - - - ```ts - getAccounts(): Map - ``` - - - - - ```ts - const accounts = simnet.getAccounts(); - - const wallet = accounts.get('wallet_1')!; - ``` - - - - ```ts - ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5 - ``` - - - ```ts - getAccounts(): Map - ``` - - - - - - - - - - - - - -# `getAssetsMap` - -Retrieve a list of asset balances associated with Stacks addresses, including fungible and non-fungible tokens. - - - - - - - - - Getting STX account balances - - - Getting ft balances - - - Getting nft balances - - - Filtering for an account - - - - ```ts - const assets = simnet.getAssetsMap(); - - const stxBalances = assets.get('STX')!; - ``` - - - - ```ts - Map(10) { - "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM": 100000000000000n, - "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5": 100000000000000n, - "ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG": 100000000000000n, - "ST2JHG361ZXG51QTKY2NQCVBPPRRE2KZB1HR05NNC": 100000000000000n, - "ST2NEB84ASENDXKYGJPQW86YXQCEFEX2ZQPG87ND": 100000000000000n, - "ST2REHHS5J3CERCRBEPMGH7921Q6PYKAADT7JP2VB": 100000000000000n, - "ST3AM1A56AK2C1XAFJ4115ZSV26EB49BVQ10MGCS0": 100000000000000n, - "ST3NBRSFKX28FQ2ZJ1MAKX58HKHSDGNV5N7R21XCP": 100000000000000n, - "ST3PF13W7Z0RRM42A8VZRVFQ75SV1K26RXEP8YGKJ": 100000000000000n, - "STNHKEPYEPJ8ET55ZZ0M5A34J0R3N5FM2CMMMAZ6": 100000000000000n, - } - ``` - - - ```ts - getAssetsMap(): Map> - ``` - - - - - - ```ts - const contractName = 'token'; - const sourceCode = ` - (define-fungible-token sbtc) - (ft-mint? sbtc u19 tx-sender) - `; - - simnet.deployContract( - contractName, - sourceCode, - null, - simnet.deployer - ); - - const assets = simnet.getAssetsMap(); - - const tokenBalance = assets.get('.token.sbtc')!; - ``` - - - - ```ts - Map(1) { - "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM": 19n, - } - ``` - - - ```ts - getAssetsMap(): Map> - ``` - - - - - - ```ts - const contractName = 'nft'; - const sourceCode = ` - (define-non-fungible-token ticket uint) - (nft-mint? ticket u42 tx-sender) - `; - - simnet.deployContract( - contractName, - sourceCode, - null, - simnet.deployer - ); - - const assets = simnet.getAssetsMap(); - - const nftBalance = assets.get('.nft.ticket')!; - ``` - - - - ```ts - Map(1) { - "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM": 1n, - } - ``` - - - ```ts - getAssetsMap(): Map> - ``` - - - - - - ```ts - const assets = simnet.getAssetsMap(); - const stxBalances = assets.get('STX')!; - - const deployerBalance = stxBalances.get('ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM')!; - ``` - - - - ```ts - 100000000000000n - ``` - - - ```ts - getAssetsMap(): Map> - ``` - - - - - - - - - - - - - - - -# `getDataVar` - -Get the value of a `data-var` defined in a contract. - -## Parameters - - -The contract identifier of the contract. - -Example: `counter` - - - -The name of the `data-var` for the contract. - -Example: `count` - - - - - - - - - - Getting the value of a data variable - - - Converting Clarity values - - - - ```ts - const currentCount = simnet.getDataVar('counter', 'count'); - ``` - - - - ```clarity counter.clar - (define-data-var count uint u0) - (define-data-var contractOwner principal tx-sender) - - (var-set count (+ (var-get count) u1)) - (var-set contractOwner 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5) - ``` - - - ```ts - { - type: 1, - value: 1n - } - ``` - - - ```ts - getDataVar(contract: string, dataVar: string): ClarityValue - ``` - - - - - - ```ts - import { cvToValue } from '@stacks/transactions'; - - const contractOwner = simnet.getDataVar("counter", "contractOwner"); - - const response = cvToValue(contractOwner); - ``` - - - - ```clarity counter.clar - (define-data-var count uint u0) - (define-data-var contractOwner principal tx-sender) - - (var-set count (+ (var-get count) u1)) - (var-set contractOwner 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5) - ``` - - - ```ts - ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5 - ``` - - - ```ts - getDataVar(contract: string, dataVar: string): ClarityValue - ``` - - - - - - - - - - - - - -# `getMapEntry` - -Get the value of a map entry by its key. Note that this method will always return an optional value `some` or `none`, just like Clarity `map-get?`. - -## Parameters - - -The contract identifier of the contract. - -Example: `pool` - - - -The name of the map within the contract. - -Example: `Participants` - - - -The key to access the value in the map. - -Example: `Cl.standardPrincipal( - 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5' -)` - - - - - - - - - - Getting the value of an entry - - - Converting Clarity values - - - - ```ts - import { Cl } from '@stacks/transactions'; - - const accounts = simnet.getAccounts(); - const wallet = accounts.get('wallet_1')!; - - const hasParticipated = simnet.getMapEntry( - "pool", - "Participants", - Cl.standardPrincipal(wallet) - ); - ``` - - - - ```clarity pool.clar - (define-map Participants principal bool) - - (map-set Participants 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5 true) - ``` - - - ```ts - { - type: 10, - value: { - type: 3, - }, - } - ``` - - - ```ts - getMapEntry( - contract: string, - mapName: string, - mapKey: ClarityValue - ): ClarityValue - ``` - - - - - - ```ts - import { Cl, cvToValue } from '@stacks/transactions'; - - const accounts = simnet.getAccounts(); - const wallet = accounts.get('wallet_1')!; - - const hasParticipated = simnet.getMapEntry( - "pool", - "Participants", - Cl.standardPrincipal(wallet) - ); - - const response = cvToValue(hasParticipated); - ``` - - - - ```clarity pool.clar - (define-map Participants principal bool) - - (map-set Participants 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5 true) - ``` - - - ```ts - { - type: "bool", - value: true, - } - ``` - - - ```ts - getMapEntry( - contract: string, - mapName: string, - mapKey: ClarityValue - ): ClarityValue - ``` - - - - - - - - - - - - - - -# `callReadOnlyFn` - -Call read-only functions exposed by a contract. - -This method returns an object with the result of the function call as a `ClarityValue`. It takes function arguments in the form of Clarity values, which are available in the package [`@stacks/transactions`](/stacks/stacks.js/packages/transactions). - -## Parameters - - -The contract identifier of the contract. - -Example: `pool` - - - -The name of the read-only function within the contract. - -Example: `get-participant` - - - -The arguments to pass to the read-only function. If no arguments are needed, pass an empty array. - -Example: `[Cl.standardPrincipal( - 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5' -)]` - - - -The Stacks address of the sender. - -Example: `ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM` - - - - - - - - - - Making a function call - - - With no arguments - - - With an explicit contract address - - - Converting Clarity values - - - - ```ts - import { Cl } from '@stacks/transactions'; - - const accounts = simnet.getAccounts(); - const wallet = accounts.get('wallet_1')!; - - const getContributionAmount = simnet.callReadOnlyFn( - 'pool', - 'get-contribution-amount', - [Cl.standardPrincipal(wallet)], - wallet - ); - - const response = getContributionAmount.result - ``` - - - - ```clarity pool.clar - (define-map Participants principal bool) - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - - (define-read-only (get-participant (who principal)) - (map-get? ParticipantStatus who) - ) - - (define-read-only (get-contribution-amount (who principal)) - (default-to u0 (get contributionAmount (get-participant who))) - ) - - (define-read-only (is-active) - (map-get? Participants tx-sender) - ) - - (map-set Participants tx-sender true) - (map-set ParticipantStatus tx-sender { enrollmentBlock: block-height, contributionAmount: u42000000 }) - ``` - - - ```ts - { - type: 1, - value: 420000000n, - } - ``` - - - ```ts - type ParsedTransactionResult = { - result: ClarityValue; - events: ClarityEvent[]; - } - - callReadOnlyFn( - contract: string, - method: string, - args: ClarityValue[], - sender: string - ): ParsedTransactionResult - ``` - - - - - - ```ts - import { Cl } from '@stacks/transactions'; - - const accounts = simnet.getAccounts(); - const wallet = accounts.get('wallet_1')!; - - const isActive = simnet.callReadOnlyFn( - 'pool', - 'is-active', - [], - wallet - ); - - const response = isActive.result - ``` - - - - ```clarity pool.clar - (define-map Participants principal bool) - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - - (define-read-only (get-participant (who principal)) - (map-get? ParticipantStatus who) - ) - - (define-read-only (get-contribution-amount (who principal)) - (default-to u0 (get contributionAmount (get-participant who))) - ) - - (define-read-only (is-active) - (map-get? Participants tx-sender) - ) - - (map-set Participants tx-sender true) - (map-set ParticipantStatus tx-sender { enrollmentBlock: block-height, contributionAmount: u42000000 }) - ``` - - - ```ts - { - type: 10, - value: { - type: 3, - }, - } - ``` - - - ```ts - type ParsedTransactionResult = { - result: ClarityValue; - events: ClarityEvent[]; - } - - callReadOnlyFn( - contract: string, - method: string, - args: ClarityValue[], - sender: string - ): ParsedTransactionResult - ``` - - - - - - ```ts - import { Cl } from '@stacks/transactions'; - - const accounts = simnet.getAccounts(); - const wallet = accounts.get('deployer')!; - const contractAddress = `${wallet}.pool`; - - const getParticipant = simnet.callReadOnlyFn( - contractAddress, - 'get-participant', - [Cl.standardPrincipal(wallet)], - wallet - ); - - const response = getParticipant.result; - ``` - - - - ```clarity pool.clar - (define-map Participants principal bool) - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - - (define-read-only (get-participant (who principal)) - (map-get? ParticipantStatus who) - ) - - (define-read-only (get-contribution-amount (who principal)) - (default-to u0 (get contributionAmount (get-participant who))) - ) - - (define-read-only (is-active) - (map-get? Participants tx-sender) - ) - - (map-set Participants tx-sender true) - (map-set ParticipantStatus tx-sender { enrollmentBlock: block-height, contributionAmount: u42000000 }) - ``` - - - ```ts - { - type: 9, - } - ``` - - - ```ts - type ParsedTransactionResult = { - result: ClarityValue; - events: ClarityEvent[]; - } - - callReadOnlyFn( - contract: string, - method: string, - args: ClarityValue[], - sender: string - ): ParsedTransactionResult - ``` - - - - - - ```ts - import { Cl, cvToValue } from '@stacks/transactions'; - - const accounts = simnet.getAccounts(); - const wallet = accounts.get('deployer')!; - - const getContributionAmount = simnet.callReadOnlyFn( - 'pool', - 'get-contribution-amount', - [Cl.standardPrincipal(wallet)], - wallet - ); - - const response = cvToValue(getContributionAmount.result); - ``` - - - - ```clarity pool.clar - (define-map Participants principal bool) - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - - (define-read-only (get-participant (who principal)) - (map-get? ParticipantStatus who) - ) - - (define-read-only (get-contribution-amount (who principal)) - (default-to u0 (get contributionAmount (get-participant who))) - ) - - (define-read-only (is-active) - (map-get? Participants tx-sender) - ) - - (map-set Participants tx-sender true) - (map-set ParticipantStatus tx-sender { enrollmentBlock: block-height, contributionAmount: u42000000 }) - ``` - - - ```ts - 42000000n - ``` - - - ```ts - type ParsedTransactionResult = { - result: ClarityValue; - events: ClarityEvent[]; - } - - callReadOnlyFn( - contract: string, - method: string, - args: ClarityValue[], - sender: string - ): ParsedTransactionResult - ``` - - - - - - - - - - - - - - -# `callPublicFn` - -Call public functions exposed by a contract. - -This method returns an object with the result of the function call as a `ClarityValue` and the events fired during the function execution. It takes function arguments in the form of Clarity values, which are available in the package [`@stacks/transactions`](/stacks/stacks.js/packages/transactions). - -This method will simulate a block being mined and increase the block height by one. - -## Parameters - - -The contract identifier of the contract. - -Example: `pool` - - - -The name of the public function within the contract. - -Example: `register-participant` - - - -The arguments to pass to the public function. If no arguments are needed, pass an empty array. - -Example: `[Cl.standardPrincipal( - 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5' -)]` - - - -The Stacks address of the sender. - -Example: `ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM` - - - - - - - - - - Broadcasting your transaction - - - Converting Clarity values - - - Filtering for contract events - - - - ```ts - import { Cl } from '@stacks/transactions'; - - const accounts = simnet.getAccounts(); - const wallet = accounts.get('deployer')!; - - const registerParticipant = simnet.callPublicFn( - 'pool', - 'register-participant', - [Cl.standardPrincipal(wallet)], - wallet - ); - - const response = registerParticipant.result; - ``` - - - - ```clarity pool.clar - (define-map Participants principal bool) - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - - (define-public (register-participant (who principal)) - (begin - (map-set Participants who true) - (map-set ParticipantStatus who { enrollmentBlock: block-height, contributionAmount: u0 }) - (print { message: "Registered", who: who, at: block-height }) - (ok true) - ) - ) - - (map-set Participants tx-sender true) - (map-set ParticipantStatus tx-sender { enrollmentBlock: block-height, contributionAmount: u42000000 }) - ``` - - - ```ts - { - type: 7, - value: { - type: 3, - }, - } - ``` - - - ```ts - type ParsedTransactionResult = { - result: ClarityValue; - events: ClarityEvent[]; - } - - callPublicFn( - contract: string, - method: string, - args: ClarityValue[], - sender: string - ): ParsedTransactionResult - ``` - - - - - - ```ts - import { Cl, cvToValue } from '@stacks/transactions'; - - const accounts = simnet.getAccounts(); - const wallet = accounts.get('deployer')!; - - const registerParticipant = simnet.callPublicFn( - 'pool', - 'register-participant', - [Cl.standardPrincipal(wallet)], - wallet - ); - - const response = cvToValue(registerParticipant.result); - ``` - - - - ```clarity pool.clar - (define-map Participants principal bool) - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - - (define-public (register-participant (who principal)) - (begin - (map-set Participants who true) - (map-set ParticipantStatus who { enrollmentBlock: block-height, contributionAmount: u0 }) - (print { message: "Registered", who: who, at: block-height }) - (ok true) - ) - ) - - (map-set Participants tx-sender true) - (map-set ParticipantStatus tx-sender { enrollmentBlock: block-height, contributionAmount: u42000000 }) - ``` - - - ```ts - { - type: "bool", - value: true, - } - ``` - - - ```ts - type ParsedTransactionResult = { - result: ClarityValue; - events: ClarityEvent[]; - } - - callPublicFn( - contract: string, - method: string, - args: ClarityValue[], - sender: string - ): ParsedTransactionResult - ``` - - - - - - ```ts - import { Cl, cvToValue, type ClarityValue } from '@stacks/transactions'; - - const accounts = simnet.getAccounts(); - const wallet = accounts.get('deployer')!; - - const registerParticipant = simnet.callPublicFn( - 'pool', - 'register-participant', - [Cl.standardPrincipal(wallet)], - wallet - ); - - const eventValues = registerParticipant.events.map((event) => - cvToValue(event.data.value as ClarityValue) - ); - ``` - - - - ```clarity pool.clar - (define-map Participants principal bool) - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - - (define-public (register-participant (who principal)) - (begin - (map-set Participants who true) - (map-set ParticipantStatus who { enrollmentBlock: block-height, contributionAmount: u0 }) - (print { message: "Registered", who: who, at: block-height }) - (ok true) - ) - ) - - (map-set Participants tx-sender true) - (map-set ParticipantStatus tx-sender { enrollmentBlock: block-height, contributionAmount: u42000000 }) - ``` - - - ```ts - [ - { - at: { - type: "uint", - value: "2", - }, - message: { - type: "(string-ascii 10)", - value: "Registered", - }, - who: { - type: "principal", - value: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", - }, - } - ] - ``` - - - ```ts - type ParsedTransactionResult = { - result: ClarityValue; - events: ClarityEvent[]; - } - - callPublicFn( - contract: string, - method: string, - args: ClarityValue[], - sender: string - ): ParsedTransactionResult - ``` - - - - - - - - - - - - - - -# `callPrivateFn` - -Call private functions exposed by a contract. - -This method returns an object with the result of the function call as a `ClarityValue` and the events, if any, fired during the function execution. It takes function arguments in the form of Clarity values, which are available in the package [`@stacks/transactions`](/stacks/stacks.js/packages/transactions). - -This method will simulate a block being mined and increase the block height by one. - -## Parameters - - -The contract identifier of the contract. - -Example: `pool` - - - -The name of the private function within the contract. - -Example: `reward-participant-points` - - - -The arguments to pass to the private function. If no arguments are needed, pass an empty array. - -Example: `[Cl.standardPrincipal( - 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5' -)]` - - - -The Stacks address of the sender. - -Example: `ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM` - - - - - - - - - - Broadcasting your transaction - - - Converting Clarity values - - - - ```ts - import { Cl } from '@stacks/transactions'; - - const accounts = simnet.getAccounts(); - const wallet = accounts.get('deployer')!; - const address1 = accounts.get("wallet_1")! - - const rewardParticipantPoints = simnet.callPrivateFn( - "pool", - "reward-participant-points", - [Cl.standardPrincipal(address1)], - wallet - ); - - const response = rewardParticipantPoints.result; - ``` - - - - ```clarity pool.clar - (define-map Participants principal bool) - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - (define-map ParticipantPoints principal int) - - (define-public (register-participant (who principal)) - (begin - (map-set Participants who true) - (map-set ParticipantStatus who { enrollmentBlock: block-height, contributionAmount: u0 }) - (reward-participant-points who) - (print { message: "Registered", who: who, at: block-height }) - (ok true) - ) - ) - - (define-private (reward-participant-points (who principal)) - (map-insert ParticipantPoints who 100) - ) - - (map-set Participants tx-sender true) - (map-set ParticipantStatus tx-sender { enrollmentBlock: block-height, contributionAmount: u42000000 }) - (map-set ParticipantPoints tx-sender 1000) - ``` - - - ```ts - { - type: 3, - } - ``` - - - ```ts - type ParsedTransactionResult = { - result: ClarityValue; - events: ClarityEvent[]; - } - - callPrivateFn( - contract: string, - method: string, - args: ClarityValue[], - sender: string - ): ParsedTransactionResult - ``` - - - - - - ```ts - import { Cl, cvToValue } from '@stacks/transactions'; - - const accounts = simnet.getAccounts(); - const wallet = accounts.get('deployer')!; - const address1 = accounts.get("wallet_1")! - - const rewardParticipantPoints = simnet.callPrivateFn( - "pool", - "reward-participant-points", - [Cl.standardPrincipal(address1)], - wallet - ); - - const response = cvToValue(registerParticipant.result); - ``` - - - - ```clarity pool.clar - (define-map Participants principal bool) - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - (define-map ParticipantPoints principal int) - - (define-public (register-participant (who principal)) - (begin - (map-set Participants who true) - (map-set ParticipantStatus who { enrollmentBlock: block-height, contributionAmount: u0 }) - (reward-participant-points who) - (print { message: "Registered", who: who, at: block-height }) - (ok true) - ) - ) - - (define-private (reward-participant-points (who principal)) - (map-insert ParticipantPoints who 100) - ) - - (map-set Participants tx-sender true) - (map-set ParticipantStatus tx-sender { enrollmentBlock: block-height, contributionAmount: u42000000 }) - (map-set ParticipantPoints tx-sender 1000) - ``` - - - ```ts - { - type: "bool", - value: true, - } - ``` - - - ```ts - type ParsedTransactionResult = { - result: ClarityValue; - events: ClarityEvent[]; - } - - callPrivateFn( - contract: string, - method: string, - args: ClarityValue[], - sender: string - ): ParsedTransactionResult - ``` - - - - - - - - - - - - - - - -# `transferSTX` - -Transfer STX from one address to another. The amount transferred is in `uSTX`. - -This method will simulate a block being mined and increase the block height by one. - -## Parameters - - -The amount of `uSTX` to transfer. - -Example: `1000000` equals 1 STX - - - -The Stacks address of the recipient. - -Example: `ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5` - - - -The Stacks address of the sender. - -Example: `ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM` - - - - - - - - - - Transferring STX - - - Converting Clarity values - - - Filtering for contract events - - - - ```ts - const accounts = simnet.getAccounts(); - const recipient = accounts.get('wallet_1')!; - - const transfer = simnet.transferSTX( - 42000000, // 42 STX - recipient, - simnet.deployer - ); - ``` - - - - ```ts - { - result: { - type: 7, - value: { - type: 3, - }, - }, - events: [ - { - event: "stx_transfer_event", - data: [ - { - amount: "42000000", - memo: "", - recipient: "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5", - sender: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", - }, - ], - } - ], - } - ``` - - - ```ts - type ParsedTransactionResult = { - result: ClarityValue; - events: ClarityEvent[]; - } - - transferSTX( - amount: number | bigint, - recipient: string, - sender: string - ): ParsedTransactionResult - ``` - - - - - - ```ts - import { cvToValue } from '@stacks/transactions'; - - const accounts = simnet.getAccounts(); - const recipient = accounts.get('wallet_1')!; - - const transfer = simnet.transferSTX( - 42000000, // 42 STX - recipient, - simnet.deployer - ); - - const response = cvToValue(transfer.result); - ``` - - - - ```ts - { - type: "bool", - value: true, - } - ``` - - - ```ts - type ParsedTransactionResult = { - result: ClarityValue; - events: ClarityEvent[]; - } - - transferSTX( - amount: number | bigint, - recipient: string, - sender: string - ): ParsedTransactionResult - ``` - - - - - - ```ts - const accounts = simnet.getAccounts(); - const recipient = accounts.get('wallet_1')!; - - const transfer = simnet.transferSTX( - 42000000, // 42 STX - recipient, - simnet.deployer - ); - - const events = transfer.events.map((event) => event); - ``` - - - - ```ts - [ - { - event: "stx_transfer_event", - data: { - amount: "42000000", - memo: "", - recipient: "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5", - sender: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", - }, - } - ] - ``` - - - ```ts - type ParsedTransactionResult = { - result: ClarityValue; - events: ClarityEvent[]; - } - - transferSTX( - amount: number | bigint, - recipient: string, - sender: string - ): ParsedTransactionResult - ``` - - - - - - - - - - - - - - -# `deployContract` - -Deploy a contract to simnet. - -This method will simulate a block being mined and increase the block height by one. - -## Parameters - - -The name of the contract to be deployed. - -Example: `hello-world` - - - -The Clarity source code (or content) of the contract. - -Example: `(define-read-only (say-hi) (ok "Hello World"))` - - - -An object to specify options, such as the Clarity version. - -Example: `{ clarityVersion: 2 }` | `null` - - - -The Stacks address of the sender. - -Example: `ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM` - - - - - - - - - - Deploying your contract - - - Specifying a Clarity version - - - Interacting with your contract - - - - ```ts - import { cvToValue } from '@stacks/transactions'; - - const sourceCode = '(define-read-only (say-hi) (ok "Hello World"))'; - - const contract = simnet.deployContract( - 'hello-world', - sourceCode, - null, - simnet.deployer - ); - - const response = cvToValue(contract.result); - ``` - - - - ```ts - true - ``` - - - ```ts - type ParsedTransactionResult = { - result: ClarityValue; - events: ClarityEvent[]; - } - - deployContract( - name: string, - content: string, - options: DeployContractOptions | null, - sender: string - ): ParsedTransactionResult - ``` - - - - - - ```ts - import { cvToValue } from '@stacks/transactions'; - - const sourceCode = '(define-read-only (say-hi) (ok "Hello World"))'; - - const contract = simnet.deployContract( - 'hello-world', - sourceCode, - { clarityVersion: 2 }, - simnet.deployer - ); - - const response = cvToValue(contract.result); - ``` - - - - ```ts - true - ``` - - - ```ts - type ParsedTransactionResult = { - result: ClarityValue; - events: ClarityEvent[]; - } - - deployContract( - name: string, - content: string, - options: DeployContractOptions | null, - sender: string - ): ParsedTransactionResult - ``` - - - - - - ```ts - import { cvToValue } from '@stacks/transactions'; - - const sourceCode = '(define-read-only (say-hi) (ok "Hello World"))'; - - simnet.deployContract( - 'hello-world', - sourceCode, - null, - simnet.deployer - ); - - const sayHi = simnet.callReadOnlyFn("hello-world", "say-hi", [], simnet.deployer); - - const response = sayHi.result - ``` - - - - ```ts - { - type: "(string-ascii 11)", - value: "Hello World", - } - ``` - - - ```ts - type ParsedTransactionResult = { - result: ClarityValue; - events: ClarityEvent[]; - } - - deployContract( - name: string, - content: string, - options: DeployContractOptions | null, - sender: string - ): ParsedTransactionResult - ``` - - - - - - - - - - - - - - -# `mineBlock` - -The `callPublicFn`, `transferSTX`, and `deployContract` methods all mine one block with only one transaction. It can also be useful to mine a block with multiple transactions. - -This is what `mineBlock` is for. - -This method takes an array of transaction objects. The transactions can be built with the `tx` helper exported by the SDK. - -The `tx` helper has three methods: -- `callPublicFn` -- `transferSTX` -- `deployContract` - -These methods have the same interface as simnet methods but instead of performing a transaction, they will build a transaction object that can be passed to the `mineBlock` function. - -In epochs from 3.0 on, the stacks chaintip is advanced separately from the burn chaintip. This means `mineBlock` will only affect the stacks chaintip. If you'd like to also mine burn blocks, use the `mineEmptyBurnBlock` function. - -## Parameters - - -An array of transactions to be included in the block. - -Example: `[tx.transferSTX(100, recipient, sender), ...]` - - - - - - - - - - Mining multiple transactions in a single block - - - - ```ts - import { tx } from '@hirosystems/clarinet-sdk'; - import { Cl, cvToValue } from '@stacks/transactions'; - - const accounts = simnet.getAccounts(); - const wallet = accounts.get("wallet_1")!; - - const block = simnet.mineBlock([ - tx.callPublicFn("counter", "increment", [], simnet.deployer), - tx.callPublicFn("counter", "add", [Cl.uint(10)], simnet.deployer), - tx.transferSTX(19000000, wallet, simnet.deployer), - ]); - - block.forEach((transaction) => { - console.log(cvToValue(transaction.result)); - if (transaction.events.length > 0) console.log(transaction.events); - }); - ``` - - - - ```clarity counter.clar - (define-data-var count uint u0) - - (define-public (increment) - (begin - (var-set count (+ (var-get count) u1)) - (ok (var-get count)) - ) - ) - - (define-public (add (amount uint)) - (begin - (var-set count (+ (var-get count) amount)) - (ok (var-get count)) - ) - ) - ``` - - - ```ts - { - type: "uint", - value: "1", - } - { - type: "uint", - value: "11", - } - { - type: "bool", - value: true, - } - [ - { - event: "stx_transfer_event", - data: { - amount: "19000000", - memo: "", - recipient: "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5", - sender: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", - }, - } - ] - ``` - - - ```ts - type ParsedTransactionResult = { - result: ClarityValue; - events: ClarityEvent[]; - } - - mineBlock(txs: Tx[]): ParsedTransactionResult[] - ``` - - - - - - - - - - - - - - -# `mineEmptyBlock` - -Mine one empty block and increase the block height by one. - -Returns the new block height. - - - - - - - - - Mining an empty block - - - - ```ts - simnet.mineEmptyBlock(); - - const response = simnet.blockHeight; - ``` - - - - ```ts - 2 - ``` - - - ```ts - mineEmptyBlock(): number - ``` - - - - - - - - - - - - - - -# `mineEmptyBlocks` - -Mine multiple empty blocks to reach a certain block height. - -Returns the new block height. - -## Parameters - - -The number of empty blocks to mine. This parameter is optional. - -Example: `5` - - - - - - - - - - Mining multiple empty blocks - - - Mining an empty block without a count - - - - ```ts - simnet.mineEmptyBlocks(5); - - const response = simnet.blockHeight; - ``` - - - - ```ts - 6 - ``` - - - ```ts - mineEmptyBlocks(count?: number): number - ``` - - - - - ```ts - simnet.mineEmptyBlocks(); - - const response = simnet.blockHeight; - ``` - - - - ```ts - 2 - ``` - - - ```ts - mineEmptyBlocks(count?: number): number - ``` - - - - - - - - - - - - - -# `runSnippet` - -Execute arbitrary Clarity code directly, which allows you to test and interact with smart contract functions without deploying them. - -## Parameters - - -The Clarity code snippet to be executed. - -Example: `(define-read-only (get-balance) (ok stx-balance))` - - - - - - - - - - Executing arbitrary Clarity code - - - Running a snippet for a STX transfer - - - - ```ts - import { Cl } from '@stacks/transactions'; - - const codeSnippet = simnet.runSnippet( - '(stx-account tx-sender)' - ); - - const response = Cl.prettyPrint(codeSnippet, 2); - ``` - - - - ```ts - { - locked: u0, - unlock-height: u0, - unlocked: u100000000000000 - } - ``` - - - ```ts - runSnippet(snippet: string): string | ClarityValue - ``` - - - - - ```ts - import { cvToValue } from "@stacks/transactions"; - - const accounts = simnet.getAccounts(); - const recipient = accounts.get("wallet_1")!; - - const codeSnippet = simnet.runSnippet( - `(stx-transfer? u19000000 tx-sender '${recipient})` - ); - - const response = cvToValue(codeSnippet); - ``` - - - - ```ts - { - type: "bool", - value: true, - } - ``` - - - ```ts - runSnippet(snippet: string): string | ClarityValue - ``` - - - - - - - - - - - - - -# `getContractsInterfaces` - -Returns the interfaces of the project contracts as a Map of Contracts, with the keys being the contract addresses. - -These interfaces contain information such as the available `functions`, `data-vars`, `maps`, `NFTs`, and `FTs` defined in the contract. - - - - - - - - - Getting a specific contract interface - - - Filtering for contract functions - - - - ```ts - const contractInterfaces = simnet.getContractsInterfaces(); - - const response = contractInterfaces.get(`${simnet.deployer}.pool`); - ``` - - - - ```clarity pool.clar - (define-map Participants principal bool) - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - - (define-read-only (get-participant (who principal)) - (map-get? ParticipantStatus who) - ) - - (define-read-only (is-active) - (map-get? Participants tx-sender) - ) - ``` - - - ```ts - { - functions: [ - { - name: "get-participant", - access: "read_only", - args: [ - [Object ...] - ], - outputs: [Object ...], - }, { - name: "is-active", - access: "read_only", - args: [], - outputs: [Object ...], - } - ], - variables: [], - maps: [ - { - name: "ParticipantStatus", - key: "principal", - value: [Object ...], - }, { - name: "Participants", - key: "principal", - value: "bool", - } - ], - fungible_tokens: [], - non_fungible_tokens: [], - epoch: "Epoch25", - clarity_version: "Clarity2", - } - - ``` - - - ```ts - getContractsInterfaces(): Map - ``` - - - - - ```ts - const poolContract = contractInterfaces.get(`${simnet.deployer}.pool`); - - const response = poolContract?.functions; - ``` - - - - ```clarity pool.clar - (define-map Participants principal bool) - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - - (define-read-only (get-participant (who principal)) - (map-get? ParticipantStatus who) - ) - - (define-read-only (is-active) - (map-get? Participants tx-sender) - ) - ``` - - - ```ts - [ - { - name: "get-participant", - access: "read_only", - args: [ - [Object ...] - ], - outputs: [Object ...], - }, { - name: "is-active", - access: "read_only", - args: [], - outputs: [Object ...], - } - ] - - ``` - - - ```ts - getContractsInterfaces(): Map - ``` - - - - - - - - - - - - - -# `getContractSource` - -Get the source code of a contract as a string. - -## Parameters - - -The identifier of the contract for which the source code is requested. - -Example: `pool` - - - - - - - - - - Getting the source code of a contract - - - - ```ts - const contractSource = simnet.getContractSource('pool'); - ``` - - - - ```clarity pool.clar - (define-map Participants principal bool) - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - - (define-read-only (get-participant (who principal)) - (map-get? ParticipantStatus who) - ) - - (define-read-only (is-active) - (map-get? Participants tx-sender) - ) - ``` - - - ```clarity - (define-map Participants principal bool) - (define-map ParticipantStatus principal { enrollmentBlock: uint, contributionAmount: uint }) - - (define-read-only (get-participant (who principal)) - (map-get? ParticipantStatus who) - ) - - (define-read-only (is-active) - (map-get? Participants tx-sender) - ) - ``` - - - ```ts - getContractSource(contract: string): string | undefined - ``` - - - - - - - - - - - - - -# `getContractAST` - -Get the full AST (Abstract Syntax Tree) of a Clarity contract. - -This method throws an error if it fails to get the AST or to encode it. - -## Parameters - - -The identifier of the contract for which the AST (Abstract Syntax Tree) is requested. - -Example: `pool` - - - - - - - - - - Getting the source code of a contract - - - - ```ts - const contractAST = simnet.getContractAST('pool'); - ``` - - - - ```ts - { - contract_identifier: { - issuer: [ 26, [ - 109, 120, 222, 123, 6, 37, 223, 191, 193, 108, 58, 138, 87, 53, 246, 220, - 61, 195, 242, 206 - ] ], - name: "pool", - }, - pre_expressions: [], - expressions: [ - { - expr: [Object ...], - id: 1, - span: [Object ...], - pre_comments: [], - end_line_comment: undefined, - post_comments: [], - }, - ... - ], - top_level_expression_sorting: [ 0, 1, 2, 3 ], - referenced_traits: Map {}, - implemented_traits: [], - wasm_module: undefined, - } - ``` - - - ```ts - getContractAST(contractId: string): ContractAST - ``` - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/clarinet-js-sdk/references/properties.mdx b/content/docs/stacks/clarinet-js-sdk/references/properties.mdx deleted file mode 100644 index 687910400..000000000 --- a/content/docs/stacks/clarinet-js-sdk/references/properties.mdx +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: Properties -description: The Clarinet JS SDK provides properties that can be used to interact with simnet. -toc: false ---- - -import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; -import { Badge } from '@/components/ui/badge'; -import { Root, API, APIExample, Property, Info } from '@/components/layout'; -import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; - - - - - - - -# `blockHeight` - -Returns the current block height of simnet. - - - - - - - - - Getting the current block height - - - - ```ts - const currentBlockHeight = simnet.blockHeight; - ``` - - - - - - ```ts - 1 - ``` - - - - - - - - - - - -# `deployer` - -Returns the default deployer address as defined in the project file. - - - - - - - - - Getting the deployer address - - - Setting the deployer to a new address - - - - ```ts - const currentDeployerAddress = simnet.deployer; - ``` - - - - ```ts - ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM - ``` - - - - - ```ts - simnet.deployer = 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5'; - const newDeployer = simnet.deployer - ``` - - - - ```ts - ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5 - ``` - - - - - - - - - - - - - -# `currentEpoch` - -Returns the current epoch of simnet. - -This represents the Stacks blockchain's progress through discrete time periods, cycles, or upgrades. - - - - - - - - - Getting the current epoch of simnet - - - - ```ts - const epoch = simnet.currentEpoch; - ``` - - - - - - ```ts - 2.5 - ``` - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/clarinet-js-sdk/references/simnet.mdx b/content/docs/stacks/clarinet-js-sdk/references/simnet.mdx deleted file mode 100644 index 98fa21ee8..000000000 --- a/content/docs/stacks/clarinet-js-sdk/references/simnet.mdx +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Simnet -description: The Simnet class is the main entry point for the Clarinet JS SDK. It provides properties and methods for interacting with the Clarinet network. -toc: false ---- - -import { - Accordion, - AccordionContent, - AccordionItem, - AccordionTrigger, -} from "@/components/ui/accordion" -import { Badge } from '@/components/ui/badge'; -import { Root, API, APIExample, Property, Info } from '@/components/layout'; -import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; - - - - - -# `initSimnet` - -The `initSimnet` function initializes a simulated network. It will often be the first function you call when using the SDK. - -## Parameters - - - -The `manifestPath` is the path to the `Clarinet.toml` manifest file. - - - - - - - - - - Creating a new instance of simnet - - - With a custom config path - - - - ```ts - import { initSimnet } from '@hirosystems/clarinet-sdk'; - - const simnet = await initSimnet(); - ``` - - - ```ts - import { initSimnet } from '@hirosystems/clarinet-sdk'; - - const simnet = await initSimnet('./config/Clarinet.toml'); - ``` - - - - - - Schema - - ```ts - initSimnet(manifestPath?: string): Promise - ``` - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/clarinet/clarity-formatter.mdx b/content/docs/stacks/clarinet/clarity-formatter.mdx deleted file mode 100644 index 8a0b52690..000000000 --- a/content/docs/stacks/clarinet/clarity-formatter.mdx +++ /dev/null @@ -1,277 +0,0 @@ ---- -title: Clarity Formatter -description: Learn how to use the Clarity formatter to standardize the style of your smart contract code. ---- -import { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from '@/components/ui/accordion'; - -The Clarity formatter is a tool designed to automatically format your Clarity smart contract code according to a standardized style. Using a consistent style improves code readability and maintainability, making it easier for developers to understand, collaborate on, and learn from existing Clarity projects. - -As Clarity is a relatively young language, establishing formatting standards helps reduce friction for both new and experienced developers, but these standards are still evolving! If you have suggestions for how we can improve the formatting rules, ping us on Discord or [add your thoughts here](https://github.com/hirosystems/clarinet/discussions/1689). - -## Introduction - -The Clarity formatter is integrated into two primary development tools: - -1. **[Clarity VS Code Extension](https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp)**: Allows formatting directly within your editor. -2. **Clarinet CLI**: Enables formatting via the command line, including the ability to format entire projects. - -## Configuration - -The formatter applies an opinionated standard with the following default settings: - -- **Line Length**: Lines wrap at 80 characters. -- **Indentation**: Uses 2 spaces for indentation. - -These defaults are configurable to match your preferences, although the specific configuration method depends on whether you are using VS Code or Clarinet. - -## Usage - -### In VS Code - -The [Clarity VS Code extension](https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp) provides several ways to format your code: - -- **Format Document**: Formats the entire active file (Right-click -> Format Document or Shift+Option+F / Shift+Alt+F). -- **Format Selection**: Formats only the highlighted code (Right-click -> Format Selection). -- **Format On Save**: Automatically formats the file when you save it. This can be enabled in VS Code settings (`editor.formatOnSave`) and is off by default. - -For example, you can configure format-on-save for all clarity files within the settings.json with this entry: - -```json -c -"[clarity]": { - "editor.formatOnSave": true, -}, -``` - -### With Clarinet CLI - -The Clarinet CLI allows you to format contracts from the command line using `clarinet format` (or the alias `clarinet fmt`). You can format individual files or all contracts defined in your project's `Clarinet.toml` manifest. - -**Format all checkable contracts and print the result without saving:** - -```terminal -$ clarinet format --dry-run -(define-map counters - principal - uint -) -(define-public (count-up) - (ok (map-set counters tx-sender (+ (get-count tx-sender) u1))) -) - -(define-read-only (get-count - (who principal) - ) - (default-to u0 (map-get? counters who)) -) -``` -**Format all checkable contracts (`--in-place`):** - -```terminal -$ clarinet format --in-place -``` - -**Format a specific file using tabs and print the result without saving (`--dry-run`):** - -```terminal -$ clarinet format -f contracts/my-contract.clar -t --dry-run -``` - -**Format a specific file, overwriting it (`--in-place`) with 4-space indents and 120 max line length:** -```terminal -$ clarinet format -f contracts/my-contract.clar -i 4 -l 120 --in-place -``` - -## Formatting Rules - -Alongside these settings, the Clarity formatter introduces formatting rules for many basic Clarity constructs: - - - - View Formatted Constructs - -
    -
  • let
  • -
  • begin
  • -
  • match
  • -
  • tuples and map sugar
  • -
  • if
  • -
  • and/or
  • -
  • comments
  • -
  • public/read-only/private functions
  • -
  • constant/persisted-variable/ft/nft/impl-trait/use-trait
  • -
  • define-map
  • -
  • define-trait
  • -
-
-
-
- -The following sections provide examples of how common constructs are formatted. - -### Basic Indentation & Line Wrapping - -Code is indented using 2 spaces per level. Long expressions exceeding the configured line length (default 80 characters) are automatically broken across multiple lines. - -```clarity -;; Example of line wrapping -(try! (unwrap! - (complete-deposit-wrapper (get txid deposit) (get vout-index deposit)) - (err (+ ERR_DEPOSIT_INDEX_PREFIX (+ u10 index))) -)) -``` - -### Function Definitions - -Functions (`define-public`, `define-private`, `define-read-only`) always span multiple lines. Arguments are double-indented if there is more than one, and if a single argument fits on the first line, it remains there. - -The function body is single-indented, aligning with the closing parenthesis of the arguments. A trailing newline is added after each function definition. - -```clarity -(define-public (my-func - (amount uint) - (sender principal) - ) - (ok true) -) - -(define-read-only (get-balance (who principal)) - (ok u0) -) -``` - -### `let` Expressions - -Bindings within a `let` expression are placed on separate lines, indented once. The body of the `let` expression is indented at the same level as the bindings. - -```clarity -(let ( - (a u1) - (b u2) -) - (body-expression) -) -``` - -### `begin` Blocks - -`begin` blocks are always formatted across multiple lines, even for a single expression. The expressions within the block are indented once. - -```clarity -(begin - (ok true) -) -``` - -### Boolean Operators (`and`, `or`) - -If an `and` or `or` expression contains more than two conditions, each condition is placed on a new line, indented once. - -```clarity -(or - true - (is-eq 1 2) - false -) -``` - -### `if` Statements - -The `then` and `else` branches of an `if` statement are always placed on separate lines, indented once. - -```clarity -(if (condition) - (expression-true) - (expression-false) -) -``` - -### `match` Expressions - -`match` expressions are always multi-line. Each match arm (pattern and corresponding expression) is placed on a new line, with the pattern and expression aligned. - -```clarity -;; Option syntax -(match opt - value (ok (handle-new-value value)) - (ok 1) -) - -;; Response syntax -(match (sbtc-transfer amount tx-sender (as-contract tx-sender)) - success (ok id) - error (err (* error u1000))))) -) -``` - -### Tuples & Maps (Sugared Syntax) - -Tuples defined using `(tuple ...)` are automatically converted to the sugared `{ key: value }` syntax. - -```clarity -;; Input: (tuple (n1 u1)) -;; Output: -{ n1: u1 } -``` - -Maps with multiple key-value pairs are broken across multiple lines. Each pair is indented once and followed by a comma (`,`), including the last pair. - -```clarity -{ - name: (buff 48), - owner: principal, -} -``` - -### Nested Maps - -Indentation is applied consistently for nested map structures. - -```clarity -{ - name: { - first: "Hiro", - last: "Protagonist", - }, - age: u33, -} -``` - -### Trait Definitions (`define-trait`) - -Trait definitions follow specific layout rules for function signatures within the trait body. - -```clarity -(define-trait token-trait - ( - (transfer? (principal principal uint) (response uint uint)) - (get-balance (principal) (response uint uint)) - ) -) -``` - -### Trailing Comments - -Trailing comments (` ;; comment`) are preserved and placed after the expression on the same line. They do not count towards the maximum line length calculation. - -```clarity -(get-value key) ;; Retrieves the stored value -``` - -## Ignoring Formatting - -You can prevent the formatter from modifying specific sections of your code by adding a `;; @format-ignore` comment immediately before the block you wish to exclude. - -```clarity -;; @format-ignore -(define-constant something (list - 1 2 3 ;; comment - 4 5 )) -``` - -Refer to the [Clarity formatter readme](https://github.com/hirosystems/clarity-formatter/blob/main/README.md) for the full list of commands and options. - -## Feedback & Further Information - -The Clarity formatter is continually evolving based on community feedback. Please try it out and share your thoughts to help improve the standards for the ecosystem. - -For more detailed information, please consult the [Clarity formatter readme](https://github.com/hirosystems/clarity-formatter/blob/main/README.md). diff --git a/content/docs/stacks/clarinet/concepts.mdx b/content/docs/stacks/clarinet/concepts.mdx deleted file mode 100644 index 213a42302..000000000 --- a/content/docs/stacks/clarinet/concepts.mdx +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Concepts -description: Learn about the concepts behind Clarinet. ---- - -## Network types - -Clarinet supports different network types to cater to various development and testing needs: - -| Network | Description | Use case -| -------------- | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -| `simnet` | Optimized for fast feedback loops, introspection, and portability. | Ideal for initial development and unit-testing. | -| `devnet` | Local Stacks and Bitcoin nodes running on Docker for faster feedback loops. | Use for integration tests or local frontend development. | -| `testnet` | A pre-production network that offers a realistic environment for testing. | Ideal for final testing before deploying to Mainnet. | -| `mainnet` | The production network where real transactions occur. | Use when you're ready to deploy your smart contract to production. | - -## Deployment plans - -The default deployment plan of every Clarinet project is contained within specifications set inside certain files. In addition to this default deployment plan, the user can manually configure each plan, adding additional transactions or contract calls across multiple Stacks or Bitcoin blocks. - -You can commit, audit, and test contracts without including any secrets in the deployment plan, and you can share these contracts without exposing any sensitive information. - -### Primitives - -| Transaction primitive | Typical usage | -| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Publish contracts | Deploy contracts to an in-memory simulated Stacks chain, public networks like testnet and mainnet, or deploy external contracts to your local network for testing purposes. | -| Call contract functions | Call a contract deployed to any of your local devnets or public networks. | -| Send BTC | Perform a simple bitcoin transfer from a p2pkh address to a p2pkh address. | -| Wait for block | Test or automate contract deployment across multiple Stacks or Bitcoin blocks. | -| Send STX | Send stacks to an address or contract. | \ No newline at end of file diff --git a/content/docs/stacks/clarinet/guides/add-a-contract.mdx b/content/docs/stacks/clarinet/guides/add-a-contract.mdx deleted file mode 100644 index 912c5ce19..000000000 --- a/content/docs/stacks/clarinet/guides/add-a-contract.mdx +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Add a contract -description: Clarinet can handle adding and configuring a new contract to your project. ---- - -import { File, Folder, Files } from 'fumadocs-ui/components/files'; - -To add a new contract, run the `clarinet contract new` command, along with your contract name, inside your project. - -```terminal -$ clarinet contract new my-contract -``` - -## Project structure - -**Clarinet** will add 2 files to your project: `my-contract.clar` and `my-contract.test.ts`. - - - - - - - - - - - - - - - - -**Clarinet** will also add the configuration to the `Clarinet.toml` file for your contract. - -```toml -[contracts.my-contract] -path = 'contracts/my-contract.clar' -clarity_version = 2 -epoch = 2.4 -``` - - -You can also add contracts to your project by adding the files manually. However, you must add the appropriate configuration to `Clarinet.toml` in order for **Clarinet** to recognize the contracts. - \ No newline at end of file diff --git a/content/docs/stacks/clarinet/guides/anatomy-of-a-clarinet-project.mdx b/content/docs/stacks/clarinet/guides/anatomy-of-a-clarinet-project.mdx deleted file mode 100644 index b382d6e54..000000000 --- a/content/docs/stacks/clarinet/guides/anatomy-of-a-clarinet-project.mdx +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: Anatomy of a Clarinet Project -description: Learn about how a Clarinet project is structured. ---- - -import { File, Folder, Files } from 'fumadocs-ui/components/files'; - -This document provides a detailed overview of the files that need to be present in a Clarinet -project. And how to configure the different tools being used. Including Clarinet but also other -tools like Vitest, TypeScript, etc. - -## Project Structure - - - - - - - - - - - - - - - - - - - -## Clarinet.toml - -This is the manifest of the project. It contains the name of the project as well as a few other -properties. - -This is also this file that will list the smart contracts that are part of the project, including -their name and the path to the file. We recommend to always set the `clarity_version` and `epoch` to -the latest. Especially the `epoch`, since you smart contract will eventually be deployed in this -epoch on mainnet. - -```toml -[contracts.my-contract] -path = 'contracts/my-contract.clar' -clarity_version = 3 -epoch = 3.1 -``` - -## package.json - -Because Clarinet relies on Node.js and NPM to write unit tests for your project, there is a -package.json file that will list the dependencies of the project. By default, Clarinet comes with -the following dependencies: - -- `@hirosystems/clarinet-sdk`: The Clarinet JS SDK is a version of the Clarinet that is compiled to - Wasm that can run in Node.js. It's used to interact with the Simnet. -- `vitest`: This the testing framework that Clarinet uses to run the tests. Learn more on the - [Vitest website](https://vitest.dev/). -- `@stacks/transactions`: This is the Stacks transactions library that is used to interact with - Clarity values in JavaScript -- `chokidar-cli`: This is a library that is used to watch the files and re-run tests on changes. -- `vitest-environment-clarinet`: this library help bootstrapping the Simnet in the testing - environment. For example, it will initialize the Simnet and makes sure it available globally in - the testing environment. - -As of May 2025, Clarinet 3.0 supports the latest version of these dependencies, especially: - -- `vitest` 3.x -- `@stacks/transactions` 7.x - -We recommend to always use the latest version of `@hirosystems/clarinet-sdk` and -`vitest-environment-clarinet`. - -## vitest.config.js - -This is the configuration file for Vitest. Here, we specify some important settings for the testing -framework to work with Clarinet. This is what the default configuration looks like: - -```js -/// - -import { defineConfig } from "vite"; -import { vitestSetupFilePath, getClarinetVitestsArgv } from "@hirosystems/clarinet-sdk/vitest"; - -export default defineConfig({ - test: { - environment: "clarinet", // use vitest-environment-clarinet - pool: "forks", - poolOptions: { - forks: { singleFork: true }, - }, - setupFiles: [ - vitestSetupFilePath, - // custom setup files can be added here - ], - environmentOptions: { - clarinet: { - ...getClarinetVitestsArgv(), - // add or override options - }, - }, - }, -}); -``` - -It exports a configuration object with `export default defineConfig({ test: {}})` where we specify -the following options: - -- `environment: "clarinet"`: Tells vitest to use the `vitest-environment-clarinet` environment. -- `pool: "forks"`, now the default value in Vitest 3.x. Tells Vitest to run process in - `child_process`, learn more in [Vitest docs](https://vitest.dev/config/#pool). -- `poolOptions: { forks: { singleFork: true } }`, run all tests in the same process. Thus allowing - efficient re-use of the Simnet and caching. Test isolation is provided by resetting the Simnet for - each test. The `setupFiles` are taking care of it. - -## tsconfig.json - -This is a regular TypeScript configuration file. The `compilerOptions` are customizable to suit your -needs and preferences. - -It's important to properly set the `include` property, by default it points to the helpers files -defined in the clarinet-sdk package, and to the tests directory. In a monorepo setup with multiple -package, you might need to adjust the path to node_modules. - -```json - "include": [ - "node_modules/@hirosystems/clarinet-sdk/vitest-helpers/src", - "tests" - ] -``` diff --git a/content/docs/stacks/clarinet/guides/create-a-new-project.mdx b/content/docs/stacks/clarinet/guides/create-a-new-project.mdx deleted file mode 100644 index f750e1a2f..000000000 --- a/content/docs/stacks/clarinet/guides/create-a-new-project.mdx +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Create a new project -description: Once you install Clarinet, you can use Clarinet to create a new project. ---- - -import { File, Folder, Files } from 'fumadocs-ui/components/files'; - -Create a new Clarinet project with the basic directory structure and configuration files: - -```terminal -$ clarinet new my-project -Create directory my-project -Create directory contracts -Create directory settings -Create directory tests -Create file Clarinet.toml -Create file settings/Mainnet.toml -Create file settings/Testnet.toml -Create file settings/Devnet.toml -Create directory .vscode -Create file .vscode/settings.json -Create file .vscode/tasks.json -Create file .gitignore -Create file .gitattributes -Create file package.json -Create file tsconfig.json -Create file vitest.config.js -``` -This will create a project directory with the following directory layout: - - - - - - - - - - - - - - - - -The _txt`Clarinet.toml`_ file contains configuration for the smart contracts in your project. When you create contracts in your project, Clarinet will automatically add them to this file. - -The _txt`settings/Devnet.toml`_ file contains configuration for accounts in the Clarinet console, including the seed phrases and initial balances for a set of out-of-the-box wallets that you can use for testing in the devnet environment. \ No newline at end of file diff --git a/content/docs/stacks/clarinet/guides/create-deployment-plans.mdx b/content/docs/stacks/clarinet/guides/create-deployment-plans.mdx deleted file mode 100644 index 66e1f5ea6..000000000 --- a/content/docs/stacks/clarinet/guides/create-deployment-plans.mdx +++ /dev/null @@ -1,248 +0,0 @@ ---- -title: Create deployment plans -description: Learn how to create deployment plans. ---- - -import { Clarinet, Js } from '@/components/ui/icon'; -import { - Tooltip, - TooltipContent, - TooltipProvider, - TooltipTrigger, -} from "@/components/ui/tooltip"; - - -Deployment plans minimize the inherent complexity of deployments, such as smart contract dependencies and interactions, transaction chaining limits, deployment costs, and more. Deployment plans ensure reproducible deployments, a critical workflow for testing purposes. - -In this guide, you will learn how to: - -1. [Generate and configure a deployment plan.](#generate-a-deployment-plan) -2. [Set deployment plan specifications.](#deployment-plan-specifications) -3. [Add project contract requirements.](#adding-project-contract-requirements) -4. [Customize your deployment plan.](#edit-your-deployment-plan) - ---- - -## Generate a deployment plan - -Clarinet uses a deployment plan for every deployment—whether for a basic `simnet`, `devnet` (for use with the `clarinet devnet start` command), or the public `testnet` and `mainnet`. - -You can view the current deployment plan saved to disk at any time with the following command (specifying the network `simnet`, `devnet`, `testnet`, `mainnet`) - -```terminal -$ clarinet deployments generate -- -``` - -Upon this command, your project's default deployment plan, a `.yaml` file (for example, `default.devnet-plan.yaml`), is generated from your project specifications and contracts. Here, for example, is the deployment plan for [the counter smart contract](/stacks/clarinet/quickstart) used in our quickstart guide: - -```yaml deployments/default.devnet-plan.yaml ---- -id: 0 -name: Devnet deployment -network: devnet -stacks-node: "http://localhost:20443" -bitcoin-node: "http://devnet:devnet@localhost:18443" -plan: - batches: - - id: 0 - transactions: - - contract-publish: - contract-name: counter - expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM - cost: 6940 - path: contracts/counter.clar - anchor-block-only: true - clarity-version: 2 - epoch: "2.5" -``` - -## Deployment plan specifications - -A project's deployment plan specifications are set on two files within a Clarinet project—the `Clarinet.toml` file as well as the network’s corresponding `.toml` file (for example, `Devnet.toml`) in the `settings/` folder. - -Specifications in the `Clarinet.toml` file you can change include: - -- The Clarity version or blockchain epoch that Clarinet emulates for your smart contracts -- Project requirements in the form of contract dependencies (see next section) - -Specifications in the `Devnet.toml` file you can change include: - -- Accounts, balances, and names -- Blockchain environment features of your devnet, such as block time or API ports -- Stacking orders -- Specifying derivation path of a given account: - -```toml settings/devnet.toml -[accounts.deployer] -mnemonic = "" -balance = 100_000_000_000_000 -derivation = "m/44'/5757'/0'/0/2" -``` - -## Adding project contract requirements - -Your project can reference a smart contract that already exists on the blockchain. - -For example, [Stacks Improvement Proposal 009](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) specifies a trait reference for all non-fungible tokens. Instead of redeploying this trait as a separate contract each time a new NFT collection is published, you can reference the contract directly within deployment plans with the following Clarinet command, including the contract principal reference: - -```terminal -$ clarinet requirements add SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait -``` - -This command updates a Clarinet project's deployment plan for use in development. - -For instance, `clarinet devnet start` would now download a copy of the contract principal via the Stacks API node that is booted alongside each devnet deployment, and it would remap the principal that publishes this contract to one of the accounts specified in your `Devnet.toml` file. - -This permits a developer to maintain the minimum set of contracts their Clarinet project will deploy to mainnet (with a single use of an `impl-trait` statement in their Clarity contract). - -## Edit your deployment plan - -Recall that a default deployment plan is used for every deployment, comprising your projects specifications as set in your `Clarinet.toml` and `.toml` files. - -The default plan is generated upon each `clarinet deployments generate --` shell command to your `deployments/` folder. - -However, you can also manually edit this default deployment `.yaml` file directly—programmatically orchestrating your contract publication and user interaction beyond your plan's defaults. - - -When deploying, Clarinet prompts you to overwrite any manually added or edited changes that differ from the specifications laid out in your project's .toml files. Type `no` to proceed with your manually configured deployment plan instead of the default. - - -Here are some of the relevant transactions and configurations available to developers manually configuring their deployment plans: - -[`emulated-contract-publish:`](#emulated-contract-publish) Deploy a contract in an in-memory simulated chain. - -[`emulated-contract-call:`](#emulated-contract-call) Call a contract that has been deployed in an in-memory simulated chain. - -[`requirement-publish:`](#requirement-publish) Deploy an external contractOne that is not published by the same set of private keys as the user wallet currently deploying. on another `testnet`/`devnet` using another wallet. - -[`contract-publish:`](#contract-publish) Deploy a contract. - -[`contract-call:`](#contract-call) Call a contract. - -[`stx-transfer:`](#stx-transfer) Transfer STX between specified accounts. - -[`btc-transfer:`](#btc-transfer) Simple bitcoin transfer from a p2pkh address to a p2pkh address (experimental, `regtest`/`testnet`/`mainnet`). - -### emulated-contract-publish - -This default transaction is included in every generated deployment for a `simnet` deployment. - -```yaml -- emulated-contract-publish: - contract-name: extension-trait - emulated-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM - path: contracts/dao/traits/extension-trait.clar - clarity-version: 1 -``` - -### emulated-contract-call - -This is a transaction type for a `simnet` deployment where the developer wants to emulate a contract call. - -```yaml -- emulated-contract-call: - contract-id: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter - emulated-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM - method: increment - parameters: - - u1 -``` - - -Read-only functions and functions that take no arguments are passed an empty list like so: `parameters: []` - - -### requirement-publish - -This cBTC smart contract application has a [devnet deployment plan](https://github.com/hirosystems/clarinet/blob/develop/components/clarinet-cli/examples/cbtc/deployments/default.devnet-plan.yaml) that publishes the contract required by its core smart contract. - -```yaml -- requirement-publish: - contract-id: SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard - remap-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM - remap-principals: - SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM - cost: 8400 - path: '.cache/requirements/SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.clar' -``` - -### contract-publish - -This default transaction is included in every generated deployment plan for every contract your Clarinet project has. This `counter` application has a [devnet deployment plan](https://github.com/hirosystems/clarinet/blob/develop/components/clarinet-cli/examples/counter/deployments/default.devnet-plan.yaml) that publishes its core smart contract. - -```yaml -- contract-publish: - contract-name: counter - expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM - cost: 5960 - path: contracts/counter.clar - anchor-block-only: true - clarity-version: 1 -``` - -### contract-call - -The developer can call a function and pass arguments of any valid Clarity type. - -```yaml -- contract-call: - contract-id: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.bitcoin-dao - expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM - method: add-new-member - parameters: - - u1 - - "0x01" - - "{ id: u4, username: "Satoshi", address: 'SP1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE }" - - "'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM" - cost: 5960 -``` - - -Read-only functions and functions that take no arguments are passed an empty list like so: `parameters: []` - - -### stx-transfer - -The developer can specify the originating account of an STX transfer, the quantity denominated in microstacks, and the recipient, as well as an optional memo field (Note: the memo field can only contain a Clarity [buffer type](https://book.clarity-lang.org/ch02-02-sequence-types.html) up to 34 bytes in size, pre-fixed with `0x` (for example, `0x68656c6c6f21`), not ASCII text or strings) - -```yaml -- stx-transfer: - expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM - recipient: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.my-contract - mstx-amount: 1000 - memo: '0x01' - cost: 10000 -``` - -### btc-transfer - -This cBTC smart contract application has a [devnet deployment plan](https://github.com/hirosystems/clarinet/blob/develop/components/clarinet-cli/examples/cbtc/deployments/wrap-btc.devnet-plan.yaml) that includes broadcasting a BTC transfer transaction to the emulated bitcoin chain with these parameters. - -```yaml -- btc-transfer: - expected-sender: mjSrB3wS4xab3kYqFktwBzfTdPg367ZJ2d - recipient: bcrt1qnxknq3wqtphv7sfwy07m7e4sr6ut9yt6ed99jg - sats-amount: 100000000 - sats-per-byte: 10 -``` - ---- - -## Next steps - - - } - href="/stacks/clarinet/guides/run-a-local-devnet" - title="Run a local devnet" - description="Learn how to run a local devnet." - tag='Clarinet' - /> - } - href="/stacks/clarinet-js-sdk/references/simnet" - title="Simnet reference" - description="Learn how to use simnet with the Clarinet JS SDK." - tag='Clarinet JS SDK' - /> - \ No newline at end of file diff --git a/content/docs/stacks/clarinet/guides/debug-a-contract.mdx b/content/docs/stacks/clarinet/guides/debug-a-contract.mdx deleted file mode 100644 index 23259f937..000000000 --- a/content/docs/stacks/clarinet/guides/debug-a-contract.mdx +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: Debug a contract -description: Step through and debug your contracts inside the command line. ---- - -import { Clarinet, Js } from '@/components/ui/icon'; -import { File, Folder, Files } from 'fumadocs-ui/components/files'; - -Inside the console, you can use these debugging commands: - -```terminal -$ ::trace (contract-call? .my-contract my-function) -$ ::debug (contract-call? .my-contract my-function) -$ break my-function -``` - -Debug navigation commands: -- _console`step`_ or _console`s`_ - Step into -- _console`finish`_ or _console`f`_ - Step out -- _console`next`_ or _console`n`_ - Step over -- _console`continue`_ or _console`c`_ - Continue execution - -Let's take the clarity_`counter`_ contract as an example: - -```clarity -(define-map Counters principal uint) - -(define-read-only (get-count (who principal)) - (default-to u0 (map-get? Counters who)) -) - -(define-public (count-up) - (ok (map-set Counters tx-sender (+ (get-count tx-sender) u1))) -) -``` - -### Trace - -The _console`::trace`_ command expects an expression, so make a _clarity`contract-call?`_ with our _clarity`count-up`_ function and see what happens. - -```terminal -$ ::trace (contract-call? .counter count-up) -(contract-call? .counter count-up)  -( get-count tx-sender ) counter:4:38 - ↳ args: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM - u0 -(ok true) -``` - -### Breakpoints - -You can also set a breakpoint at a specific line to better understand what's happening in your contract. - -With `::debug`, you can add breakpoints at a specific line of a contract or function to better understand what's happening in your contracts. - -```clarity -(define-map Counters principal uint) - -(define-read-only (get-count (who principal)) - (default-to u0 (map-get? Counters who)) -) - -(define-public (count-up) - (ok (map-set Counters tx-sender (+ (get-count tx-sender) u1))) -) - -;; !mark(1:3) -(define-public (count-twice) - (double) -) - -;; !mark(1:6) -(define-private (double) - (begin - (unwrap-panic (count-up)) - (count-up) - ) -) -``` - -```terminal -$ ::debug (contract-call? .counter count-twice) -$ break count-up -``` - - - -To step through these breakpoints, you can use one of the following commands: - -- **Step-in (`step` or `s`)**: Step into the sub-expressions. -- **Step-out (`finish` or `f`)**: Complete execution of the current expression and return the result to the parent. -- **Step-over (`next` or `n`)**: Continue to completion of the current expression, stepping over sub-expressions. -- **Continue (`continue` or `c`)**: Continue execution until hitting a breakpoint or completing execution. - - -Using the _console`continue`_ command, the breakpoint you set in the _clarity`double`_ function will trigger twice due to two _clarity`count-up`_ calls, which enables you to do variable and map analysis. - -## Next steps - - - } - href="/stacks/clarinet/guides/validate-a-contract" - title="Validate a contract" - description="Learn how to validate a contract." - tag='Clarinet' - /> - } - href="/stacks/clarinet/guides/estimate-costs" - title="Estimate costs for a contract" - description="Learn how to estimate costs for a contract." - tag='Clarinet' - /> - } - href="/stacks/clarinet-js-sdk/quickstart" - title="Write tests for your smart contracts" - description="Learn how to write unit tests using the Clarinet JS SDK." - tag='Clarinet JS SDK' - /> - \ No newline at end of file diff --git a/content/docs/stacks/clarinet/guides/deploy-a-contract.mdx b/content/docs/stacks/clarinet/guides/deploy-a-contract.mdx deleted file mode 100644 index e5242dcc5..000000000 --- a/content/docs/stacks/clarinet/guides/deploy-a-contract.mdx +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: Deploy a contract -description: Use Clarinet to publish your contracts to the devnet, testnet, or mainnet networks. ---- - -Generate a deployment plan: - -```terminal -$ clarinet deployments generate -- -``` -Supported networks: console`devnet`_, console`testnet`_, console`mainnet`_ - -Deploy contracts: - -```terminal -$ clarinet deployments apply -- -``` - -## Add Contract Requirements -Add external contract dependencies: - -```terminal -$ clarinet requirements add -``` - -Example: -```terminal -$ clarinet requirements add SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait -``` - -## Deployment Plan Transactions - -Your deployment plans can include various transaction types: - -### Contract Operations -```yaml -- contract-publish: - contract-name: my-contract - expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM - cost: 5960 - path: contracts/my-contract.clar - clarity-version: 2 - -- contract-call: - contract-id: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.my-contract - expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM - method: my-function - parameters: [] - cost: 5960 -``` - -### Asset Transfers -```yaml -- stx-transfer: - expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM - recipient: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.my-contract - mstx-amount: 1000 - memo: '0x01' - cost: 10000 - -- btc-transfer: - expected-sender: mjSrB3wS4xab3kYqFktwBzfTdPg367ZJ2d - recipient: bcrt1qnxknq3wqtphv7sfwy07m7e4sr6ut9yt6ed99jg - sats-amount: 100000000 - sats-per-byte: 10 -``` - -### Simnet Operations -```yaml -- emulated-contract-publish: - contract-name: my-contract - emulated-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM - path: contracts/my-contract.clar - clarity-version: 2 - -- emulated-contract-call: - contract-id: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.my-contract - emulated-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM - method: my-function - parameters: [] -``` - - -For functions that take no arguments or read-only functions, use an empty parameters list: `parameters: []` - \ No newline at end of file diff --git a/content/docs/stacks/clarinet/guides/estimate-costs.mdx b/content/docs/stacks/clarinet/guides/estimate-costs.mdx deleted file mode 100644 index 2505b58f3..000000000 --- a/content/docs/stacks/clarinet/guides/estimate-costs.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Estimating contract costs -description: Analyze execution costs pertaining to your contract. ---- - -import { API, Clarinet, Js } from '@/components/ui/icon'; -import { File, Folder, Files } from "fumadocs-ui/components/files" - -Transactions on the Stacks blockchain comes with execution costs that can dictate transaction fees for your users. To analyze the execution costs of your contract's functions, let's continue with the simple `counter` contract from the [Clarinet quickstart](/stacks/clarinet/quickstart) as an example. - -```clarity -(define-map Counters principal uint) - -(define-read-only (get-count (who principal)) - (default-to u0 (map-get? Counters who)) -) - -(define-public (count-up) - (ok (map-set Counters tx-sender (+ (get-count tx-sender) u1))) -) -``` - -To start analyzing execution costs, first run the `clarinet console` command inside your project. - -```terminal -$ clarinet console -``` - -## Get Costs - -The `::get_costs ` command in the Clarinet console will display the cost analysis of the given expression as well as the return value of the given expression. The `::get_costs` command expects an expression, so make a `contract-call?` with our `count-up` function and see what happens. - -```terminal -$ ::get_costs (contract-call? .counter count-up) -+----------------------+-------------+----------------+-----------------+ -| | Consumed | Limit | Percentage | -+----------------------+-------------+----------------+-----------------+ -| Runtime | 4752 | 5000000000 | 0.00 % | -+----------------------+-------------+----------------+-----------------+ -| Read count | 5 | 15000 | 0.03 % | -+----------------------+-------------+----------------+-----------------+ -| Read length (bytes) | 245 | 100000000 | 0.00 % | -+----------------------+-------------+----------------+-----------------+ -| Write count | 1 | 15000 | 0.01 % | -+----------------------+-------------+----------------+-----------------+ -| Write length (bytes) | 41 | 15000000 | 0.00 % | -+----------------------+-------------+----------------+-----------------+ - - -(ok true) -``` - -As you can see from the chart, execution costs are broken into 5 different categories, each with its own limit. The limit is pertaining to what each Stacks block is limited to. - - -The below lists out each of the 5 different categories of Clarity execution costs. ([source](https://book.clarity-lang.org/ch12-00-runtime-cost-analysis.html)) - -- **Runtime** costs limits overall complexity of the code that can be executed. For example, negating a boolean value is less complex than calculating SHA512 hash, therefore (not false) will consume less runtime costs than (sha512 "hello world"). This category is also affected by contract size. -- **Read count** limits how many times we can read from memory or chain state to a extract piece of information. It is affected by reading constants, variables, intermediate variables created with let, maps, but also by some functions that needs to save intermediate results during execution. -- **Read length (bytes)** limits how much data we can read from memory or the chain. It is also affected by contract size. Calling into a contract using contract-call? Increases the read length by an amount equal to the contract size in bytes, every time. If you call into a contract with a length of 2,000 bytes twice, the read length is increased twice. -- **Write count** limits how many times we can write data into chain. It increments when writing to variables and maps. -- **Write length (bytes)** limits how much data we can write to the chain. - - - -The percentage column shows what percentage of the execution costs your expression consumed out of the block limit given. - -## Toggle costs - -You can toggle the cost analysis to always be displayed after every expression execution in the console by toggling this feature on with the command `::toggle_costs`. - -```terminal -$ ::toggle_costs -``` - -To turn it off, just run the `::toggle_costs` command again. - -Check out the Clarity Book section on [runtime cost analysis](https://book.clarity-lang.org/ch12-00-runtime-cost-analysis.html) to read up on cost optimization techniques and recommendations. - -To see how you can run automated cost analysis on your unit tests, check out our [quickstart](/stacks/clarinet-js-sdk/quickstart#run-your-tests-with-code-coverage-and-cost-analysis) section for the Clarinet JS SDK. - - - } - href="/stacks/clarinet/guides/validate-a-contract" - title="Validate a contract" - description="Learn how to validate a contract." - tag='Clarinet' - /> - } - href="/stacks/rpc-api/fees/estimate" - title="Get fee estimates for a transaction" - description="Learn how to fetch transaction costs." - tag='API' - /> - } - href="/stacks/clarinet-js-sdk/quickstart" - title="Write tests for your smart contracts" - description="Learn how to write unit tests using the Clarinet JS SDK." - tag='Clarinet JS SDK' - /> - \ No newline at end of file diff --git a/content/docs/stacks/clarinet/guides/run-a-local-devnet.mdx b/content/docs/stacks/clarinet/guides/run-a-local-devnet.mdx deleted file mode 100644 index 970a558c0..000000000 --- a/content/docs/stacks/clarinet/guides/run-a-local-devnet.mdx +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Run a local devnet -description: Integrate your contracts with a local development environment. ---- - -Launch a local development network with all required services: - -```terminal -$ clarinet devnet start -``` - -Requires Docker to be running locally. See [installing Docker](/guides/install-docker) guide for more information. - - -

If you are getting `error: clarinet was unable to create network`, make sure you have a container service running locally.

-
\ No newline at end of file diff --git a/content/docs/stacks/clarinet/guides/start-a-development-console.mdx b/content/docs/stacks/clarinet/guides/start-a-development-console.mdx deleted file mode 100644 index 76f0b3405..000000000 --- a/content/docs/stacks/clarinet/guides/start-a-development-console.mdx +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Start development console -description: Launch the Clarinet console for interactive development. ---- - -import { File, Folder, Files } from 'fumadocs-ui/components/files'; - -Launch the Clarinet console for interactive development: - -```terminal -$ clarinet console -``` - -This commands starts a new interactive REPL session so you can interact with your contracts. \ No newline at end of file diff --git a/content/docs/stacks/clarinet/guides/validate-a-contract.mdx b/content/docs/stacks/clarinet/guides/validate-a-contract.mdx deleted file mode 100644 index a7a152f4d..000000000 --- a/content/docs/stacks/clarinet/guides/validate-a-contract.mdx +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Validate a contract -description: Clarinet provides syntax and semantics checkers for the smart contract language Clarity. ---- - -import { File, Folder, Files } from 'fumadocs-ui/components/files'; - -Validate the syntax and semantics of your contracts: - -```terminal -$ clarinet check -✔ 1 contract checked -$ clarinet check path/to/my-contract.clar -✔ 1 contract checked -``` - -This command uses the _txt`Clarinet.toml`_ file to locate and analyze all the contracts in the project. If the Clarity code is valid, the command will indicate success with the response below. - - -The _console`clarinet check`_ command may also report warnings indicating the code is valid. - \ No newline at end of file diff --git a/content/docs/stacks/clarinet/guides/working-with-sbtc.mdx b/content/docs/stacks/clarinet/guides/working-with-sbtc.mdx deleted file mode 100644 index 60be62aae..000000000 --- a/content/docs/stacks/clarinet/guides/working-with-sbtc.mdx +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: Working with sBTC -description: Clarinet helps with building, testing, and deploying contracts that use sBTC. ---- - -To take advantage of these features, make sure to use Clarinet 2.15.0 or later. - -## About sBTC - -sBTC is a fungible token on the Stacks blockchain. It follows the -[SIP-010 standard](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) -for fungible tokens. - -Even though it's *just* a fungible token, Clarinet has some helpers to make it easier to work with. - -## Using sBTC in your contract - -To use sBTC in your contract, you need to add the `sbtc-deposit` smart contract to your requirements. - -In a Clarinet project, run the following command: - -```terminal -$ clarinet requirements add SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-deposit -``` - -This will add the [`sbtc-deposit`](https://explorer.hiro.so/txid/SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-deposit) -smart contract to your project, along with it's dependencies: -- [`sbtc-token`](https://explorer.hiro.so/txid/SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token) -- [`sbtc-registry`](https://explorer.hiro.so/txid/SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-registry) - -When Clarinet detects the `sbtc-deposit` contract, it will automatically fund your test wallets with -sBTC that you can use to test your contract in Clarinet simnet and devnet. - -## Using sBTC in your contract - -As a SIP-010 token, sBTC let you call the `transfer` function to transfer tokens from one address to another. - -Let's say we have an NFT contract that allows users to mint an NFT by spending sBTC. - - -```clarity -;; this code is for demo purposes -;; it doesn't implement SIP-009 NFT standard -(define-non-fungible-token nft-name uint) - -;; mint for 100 sats -(define-data-var sats-sbtc-mint-price uint u100) -(define-data-var next-id uint u0) - -(define-public (mint-one-with-sbtc) - (begin - ;; call the sbtc-token contract to transfer the sbtcs - (try! (contract-call? 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token transfer - (var-get sats-sbtc-mint-price) - tx-sender - (as-contract tx-sender) - none - )) - - (try! (nft-mint? nft-name (var-get next-id) tx-sender)) - - (ok (var-set next-id (+ (var-get next-id) u1))) - ) -) -``` - -Because Clarinet already took care of funding the test wallets with sBTC, you can call the -`mint-one-with-sbtc` function with one of your test wallets. - -In simnet (unit tests or `clarinet console`), the deployer address of the contract will remain -`SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4`, but in devnet, like every other requirements, the contract will -be deployed by the default deployer address. You don't have to worry about this—Clarinet always make -sure that your contracts call the right address. - -## Deploying your contract on testnet - -On testnet, the official Hiro sBTC contract is -[ST1F7QA2MDF17S807EPA36TSS8AMEFY4KA9TVGWXT.sbtc-token](https://explorer.hiro.so/txid/ST1F7QA2MDF17S807EPA36TSS8AMEFY4KA9TVGWXT.sbtc-token?chain=testnet). -This is the contract that is linked to the sBTC faucet: `ST1F7QA2MDF17S807EPA36TSS8AMEFY4KA9TVGWXT.sbtc-deposit`. - -Again, Clarinet will make sure that your contracts call this address when being deployed on mainnet. -You can see the address of the sbtc-contract being re-mapped in the testnet deployment plan. - -## Deploying your contract on mainnet - -On mainnet, your contract will remain unchanged and call the one and only sBTC contract. diff --git a/content/docs/stacks/clarinet/index.mdx b/content/docs/stacks/clarinet/index.mdx deleted file mode 100644 index 1a644d1a0..000000000 --- a/content/docs/stacks/clarinet/index.mdx +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: Overview -description: Clarinet is a local development environment that offers everything you need to create, test, and deploy smart contracts on Stacks. ---- - -import { ArrowUpRight } from "lucide-react"; -import { - Tooltip, - TooltipContent, - TooltipProvider, - TooltipTrigger, -} from "@/components/ui/tooltip" -import { SecondaryCard } from "@/components/card"; - -Using a simple command line interface, Clarinet enables you to build and iterate on your contracts locally before moving into production on the `mainnet` network. - -You can code with Clarity syntax supportUsing the [Clarity VSCode extension](https://marketplace.visualstudio.com/items?itemName=HiroSystems.clarity-lsp#:~:text=This%20VS%20Code%20extension%20brings,safety%20checks%2C%20debugger%20and%20more), run tests, debug your code line by line, and deploy your contracts to a local Stacks blockchain environment to rapidly iterate on your code. - -## Installation - - - -```terminal !! macOS -$ brew install clarinet -``` - -```terminal !! Windows -$ winget install clarinet -``` - -```terminal !! Cargo -$ sudo apt install build-essential pkg-config libssl-dev -``` - -```terminal !! Pre-built binary -$ wget -nv https://github.com/hirosystems/clarinet/releases/download/v0.27.0/clarinet-linux-x64-glibc.tar.gz -O clarinet-linux-x64.tar.gz -$ tar -xf clarinet-linux-x64.tar.gz -$ chmod +x ./clarinet -$ mv ./clarinet /usr/local/bin -``` - - - -## Set up shell completions - -Clarinet already has many different commands built in. Therefore, enabling tab completion in your shell may be useful. Using the command below, you can use `clarinet` to generate the shell completion scripts for many common shells. - -```terminal -$ clarinet completions (bash|elvish|fish|powershell|zsh) -``` - -After generating the file, you can refer to the documentation for your shell to determine where this file should be moved to and what other steps may be necessary to enable tab completion for `clarinet`. - -## Guides - - - - - - - - -## Related tools - -- **[Clarinet JS SDK](/stacks/clarinet-js-sdk)**: Simplify your testing with the Clarinet JS SDK. -- **[Hiro Platform](/stacks/platform)**: A developer platform for building, deploying and scaling Bitcoin apps. -- **[Stacks.js](/stacks/stacks.js)**: Leverage a JavaScript library that handles basic functions, such as user authentication and transaction signing. - -
- - -Reach out to us on the #clarinet channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET. - diff --git a/content/docs/stacks/clarinet/meta.json b/content/docs/stacks/clarinet/meta.json deleted file mode 100644 index 29705746d..000000000 --- a/content/docs/stacks/clarinet/meta.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "title": "Clarinet", - "root": true, - "pages": [ - "---Clarinet---", - "index", - "quickstart", - "concepts", - "clarity-formatter", - "---Guides---", - "...guides" - ] -} diff --git a/content/docs/stacks/clarinet/quickstart.mdx b/content/docs/stacks/clarinet/quickstart.mdx deleted file mode 100644 index b78e63eb2..000000000 --- a/content/docs/stacks/clarinet/quickstart.mdx +++ /dev/null @@ -1,152 +0,0 @@ ---- -title: Quickstart -description: Learn how to create a simple counter contract using Clarinet. ---- - -import { Clarinet, Js } from '@/components/ui/icon'; -import { File, Folder, Files } from 'fumadocs-ui/components/files'; -import { Steps, Step } from 'fumadocs-ui/components/steps'; - -In this quickstart guide, you will write a simple counter contract with Clarity. Throughout this tutorial, you'll learn how to generate a new project, create a smart contract, and validate your smart contract code using the Clarinet CLI. - -Check out the [create a new project](/stacks/clarinet/guides/create-a-new-project) and [validate a contract](/stacks/clarinet/guides/validate-a-contract) guides for a deeper look. - ---- - - - - ## Generate your counter project - - Start by creating a new Clarinet project. This command will create a new directory named _console`counter`_ and set up a basic Clarinet project inside it. - - ```terminal - $ clarinet new counter - Create directory counter - Create directory contracts - Create directory settings - Create directory tests - Create file Clarinet.toml - Create file settings/Mainnet.toml - Create file settings/Testnet.toml - Create file settings/Devnet.toml - Create directory .vscode - Create file .vscode/settings.json - Create file .vscode/tasks.json - Create file .gitignore - Create file .gitattributes - Create file package.json - Create file tsconfig.json - Create file vitest.config.js - ``` - - - - - - - - - - - - - - - - - - ## Create a counter contract - - Inside your project directory, run _console`clarinet contract new counter`_ to create your contract. This will generate and update the proper files for writing and testing your code. - - ```terminal - $ cd counter - $ clarinet contract new counter - Created file contracts/counter.clar - Created file tests/counter.test.ts - Updated Clarinet.toml with contract counter - ``` - - ```toml Clarinet.toml - [contracts.counter] - path = 'contracts/counter.clar' - clarity_version = 2 - epoch = 2.5 - ``` - - - ## Variables and functions - - Inside your _txt`contracts/counter.clar`_ file: - - 1. Define a map called _clarity`Counters`_ to store the count associated with each user. - 2. Define a public function called _clarity`count-up`_ that increments the count of the user who calls it. - 3. Add a read-only function called _clarity`get-count`_ that returns the count of the user who calls it. - - ```clarity counter.clar -c - (define-map Counters principal uint) - - (define-public (count-up) - (ok (map-set Counters tx-sender (+ (get-count tx-sender) u1))) - ) - - (define-read-only (get-count (who principal)) - (default-to u0 (map-get? Counters who)) - ) - ``` - - - ## Validate your contract - - Now it's time to validate your contract. This command will check your contract for errors and typos. - - ```terminal - $ clarinet check - ✔ 1 contract checked - ``` - - Once your contract is validated, you can interact with it locally with the _console`clarinet console`_ inside your project directory. - - ```terminal - $ clarinet console - ``` - - Here are some example interactions you can perform with your contract: - - 1. Call the _clarity`count-up`_ function on your contract to increment the count. - 2. Verify the count of the user has been incremented by calling the _clarity`get-count`_ function with the _clarity`tx-sender`_ as the argument. - - ```terminal - $ (contract-call? .counter count-up) - (ok true) - $ (contract-call? .counter get-count tx-sender) - u1 - ``` - - - -## Next steps - - - } - href="/stacks/clarinet/guides/add-a-contract" - title="Add a contract to your project" - description="Learn how to add a contract to your project." - tag='Clarinet' - /> - } - href="/stacks/clarinet/guides/run-a-local-devnet" - title="Run a local devnet" - description="Learn how to set up and run a local development network for your project." - tag='Clarinet' - /> - } - href="/stacks/clarinet-js-sdk/quickstart" - title="Write tests for your smart contracts" - description="Learn how to write unit tests using the Clarinet JS SDK." - tag='Clarinet JS SDK' - /> - \ No newline at end of file diff --git a/content/docs/stacks/clarity/functions/add.mdx b/content/docs/stacks/clarity/functions/add.mdx deleted file mode 100644 index 62dfa5f96..000000000 --- a/content/docs/stacks/clarity/functions/add.mdx +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: add -description: Use the addition function for arithmetic operations in Clarity smart contracts. ---- - -The addition function (`+`) in Clarity performs addition on a variable number of integer inputs. It's a fundamental arithmetic operation used in many smart contract calculations. - -## Function Signature - -```clarity -(+ i1 i2...) -``` - -- Input: Two or more integers (int or uint) -- Output: A single integer (int or uint) - -## Why it matters - -The addition function is crucial for: - -1. Performing basic arithmetic calculations within smart contracts. -2. Incrementing counters or values. -3. Combining multiple quantities or balances. -4. Implementing mathematical formulas that involve addition. - -## When to use it - -Use the addition function when you need to: - -- Perform basic addition in your contract logic. -- Increment values or counters. -- Sum up multiple values. -- Implement mathematical formulas that involve addition. - -## Best Practices - -- Always consider the possibility of overflow when adding large numbers. -- Use appropriate types (int or uint) based on your needs and expected value ranges. -- Be aware that adding negative numbers to positive numbers can result in subtraction. -- Consider using checked arithmetic functions if overflow detection is critical. - -## Practical Example: Simple Counter - -Let's implement a simple counter that uses the addition function to increment its value: - -```clarity -(define-data-var counter int 0) - -(define-public (increment-counter (amount int)) - (begin - (var-set counter (+ (var-get counter) amount)) - (ok (var-get counter)) - ) -) - -;; Usage -(increment-counter 1) ;; Increments the counter by 1 -(increment-counter 5) ;; Increments the counter by 5 -``` - -This example demonstrates: -1. Using addition to increment the value of a counter. -2. Implementing a public function to handle the increment operation. -3. Returning the updated counter value. - -## Common Pitfalls - -1. Overlooking potential overflow when adding large numbers. -2. Not considering the effect of adding negative numbers (for int types). -3. Forgetting to update related variables or state when incrementing values. - -## Related Functions - -- `-`: Used for subtraction operations. -- `*`: Used for multiplication operations. -- `/`: Used for division operations. - -## Conclusion - -The addition function is a fundamental tool for performing arithmetic operations in Clarity smart contracts. By understanding its behavior with different types of inputs and potential edge cases, you can use it effectively to implement various mathematical operations in your contracts, from simple increments to more complex calculations. diff --git a/content/docs/stacks/clarity/functions/and.mdx b/content/docs/stacks/clarity/functions/and.mdx deleted file mode 100644 index b5a180b9f..000000000 --- a/content/docs/stacks/clarity/functions/and.mdx +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: and -description: Use the and function for logical operations in Clarity smart contracts. ---- - -The `and` function in Clarity performs a logical AND operation on two or more boolean inputs. It's a fundamental logical operation used in many smart contract conditions and control flows. - -## Function Signature - -```clarity -(and b1 b2 ...) -``` - -- Input: Two or more boolean values -- Output: A single boolean value - -## Why it matters - -The `and` function is crucial for: - -1. Implementing complex conditional logic in smart contracts. -2. Combining multiple conditions that all need to be true. -3. Short-circuiting evaluations for efficiency. -4. Creating sophisticated access control mechanisms. - -## When to use it - -Use the `and` function when you need to: - -- Check if multiple conditions are all true. -- Implement multi-factor authentication or permissions. -- Optimize condition checking by short-circuiting. -- Combine the results of multiple comparison operations. - -## Best Practices - -- Leverage the short-circuiting behavior for efficiency. -- Order conditions from most likely to fail to least likely for better performance. -- Use parentheses to group complex logical expressions for clarity. -- Consider breaking very complex `and` expressions into separate functions or variables for readability. - -## Practical Example: Simple Access Control - -Let's implement a simple access control function that uses the `and` function to check multiple conditions: - -```clarity -(define-constant CONTRACT_OWNER tx-sender) -(define-data-var isAdmin bool false) -(define-data-var isActive bool true) - -(define-public (set-admin (enabled bool)) - (begin - (asserts! (is-eq tx-sender CONTRACT_OWNER) (err u1)) - (ok (var-set isAdmin enabled)) - ) -) - -(define-public (perform-sensitive-action) - (begin - (asserts! (and (var-get isAdmin) (var-get isActive)) (err u2)) - ;; Perform the sensitive action here - (ok true) - ) -) - -;; Usage -(perform-sensitive-action) ;; Returns (err u2) -(set-admin true) ;; Returns (ok true) -(perform-sensitive-action) ;; Returns (ok true) -``` - -This example demonstrates: -1. Using `and` to check if the sender is an admin and if the contract is active. -2. Combining multiple conditions in a single `and` expression. -3. Leveraging short-circuiting to avoid unnecessary computations if the first condition fails. - -## Common Pitfalls - -1. Forgetting that `and` short-circuits, which might lead to unexpected behavior if side effects are intended in later conditions. -2. Over-complicating logical expressions, making them hard to read and maintain. -3. Not considering the order of conditions for optimal performance. - -## Related Functions - -- `or`: Used for logical OR operations. -- `not`: Used to negate boolean values. -- `asserts!`: Often used in combination with `and` for multiple condition checks. - -## Conclusion - -The `and` function is a powerful tool for creating complex logical conditions in Clarity smart contracts. By understanding its short-circuiting behavior and using it effectively, you can create efficient and sophisticated contract logic, especially for scenarios requiring multiple conditions to be true simultaneously. diff --git a/content/docs/stacks/clarity/functions/append.mdx b/content/docs/stacks/clarity/functions/append.mdx deleted file mode 100644 index efe202230..000000000 --- a/content/docs/stacks/clarity/functions/append.mdx +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: append -description: Use the append function to add elements to lists in Clarity smart contracts, with considerations for maximum list length. ---- - -## Function Signature - -```clarity -(append (list A) A) -``` - -- Input: A list of type A, and a single element of type A -- Output: A new list of type A with the element appended - -## Why it matters - -The `append` function is crucial for: - -1. Dynamically growing lists within smart contracts. -2. Adding new elements to existing data structures. -3. Implementing queue-like behaviors in contract logic. -4. Constructing lists incrementally during contract execution. - -## When to use it - -Use the `append` function when you need to: - -- Add a new element to the end of an existing list. -- Construct a list by adding elements one at a time. -- Implement data structures that require adding elements in order. -- Combine existing lists with single elements. - -## Best Practices - -- Always use `as-max-len?` before appending to ensure the list doesn't exceed its maximum length. -- Be mindful of the maximum list length specified when defining the list. -- Consider using `concat` for joining two lists instead of repeatedly using `append`. -- Remember that `append` creates a new list; it doesn't modify the original list in-place. -- Use type-appropriate elements that match the list's declared type. - -## Practical Example: Event Log with Max Length Check - -Let's implement a simple event log system using `append` with a maximum length check: - -```clarity -(define-data-var eventLog (list 50 (string-ascii 50)) (list)) - -(define-public (log-event (event (string-ascii 50))) - (let - ( - (current-log (var-get eventLog)) - ) - (match (as-max-len? (append current-log event) u2) success - (ok (var-set eventLog success)) - (err u1) - ) - ) -) - -(define-read-only (get-eventLog) - (ok (var-get eventLog)) -) - -;; Usage -(log-event "Contract initialized") -(log-event "User registered") -(get-eventLog) ;; Returns (ok ("Contract initialized" "User registered")) -``` - -This example demonstrates: -1. Using `append` to add new events to an existing log. -2. Using `as-max-len?` to check if appending would exceed the maximum list length. -3. Handling the case where the list would exceed its maximum length. -4. Combining `append` with other Clarity functions like `var-set` and `var-get`. - -## Common Pitfalls - -1. Forgetting to use `as-max-len?` when appending to a list with a maximum length. -2. Attempting to append an element of the wrong type to a typed list. -3. Assuming `append` will always succeed without checking the list's current length. -4. Inefficiently using `append` in a loop when `concat` might be more appropriate. - -## Related Functions - -- `as-max-len?`: Used to check if a sequence exceeds a maximum length. -- `concat`: Used for joining two lists together. -- `list`: Used for creating new lists. -- `len`: Used for getting the current length of a list. - -## Conclusion - -The `append` function is a powerful tool for manipulating lists in Clarity smart contracts. By understanding its behavior, limitations, and the necessity of using `as-max-len?` with lists that have a maximum length, you can effectively manage dynamic data structures within your contracts. This enables more flexible and responsive smart contract designs while maintaining safeguards against exceeding predefined list size limits. diff --git a/content/docs/stacks/clarity/functions/as-contract.mdx b/content/docs/stacks/clarity/functions/as-contract.mdx deleted file mode 100644 index 19bad0282..000000000 --- a/content/docs/stacks/clarity/functions/as-contract.mdx +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: as-contract -description: Use the as-contract function to execute expressions as the contract principal in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(as-contract expr) -``` - -- Input: An expression `expr` -- Output: The result of `expr` - -## Why it matters - -The `as-contract` function is crucial for: - -1. Executing operations with the contract's authority. -2. Allowing the contract to send assets or perform privileged actions. -3. Implementing contract-owned resources or funds. -4. Enabling more complex contract interactions and architectures. - -## When to use it - -Use the `as-contract` function when you need to: - -- Perform actions that require the contract's principal. -- Send assets (like STX or tokens) from the contract's balance. -- Execute privileged operations that should only be done by the contract itself. -- Implement contract-owned resources or escrow-like functionality. - -## Best Practices - -- Use `as-contract` sparingly and only when necessary to minimize potential security risks. -- Ensure that the logic leading to `as-contract` calls is properly secured and access-controlled. -- Be aware that `as-contract` changes the `tx-sender` context for the duration of the expression. -- Combine `as-contract` with other security measures like `contract-caller` checks for robust security. - -## Practical Example: Contract-Managed Treasury - -Let's implement a simple treasury system where the contract can distribute funds: - -```clarity -(define-constant CONTRACT_OWNER tx-sender) -(define-data-var treasuryBalance uint u0) - -(define-public (deposit (amount uint)) - (begin - (try! (stx-transfer? amount tx-sender (as-contract tx-sender))) - (var-set treasuryBalance (+ (var-get treasuryBalance) amount)) - (ok true) - ) -) - -(define-public (withdraw (recipient principal) (amount uint)) - (begin - (asserts! (is-eq tx-sender CONTRACT_OWNER) (err u403)) - (asserts! (<= amount (var-get treasuryBalance)) (err u401)) - (try! (as-contract (stx-transfer? amount tx-sender recipient))) - (var-set treasuryBalance (- (var-get treasuryBalance) amount)) - (ok true) - ) -) -``` - -This example demonstrates: -1. Using `as-contract` in the `deposit` function to receive funds as the contract. -2. Using `as-contract` in the `withdraw` function to send funds from the contract's balance. -3. Combining `as-contract` with access control (`is-eq tx-sender CONTRACT_OWNER`) for security. - -## Common Pitfalls - -1. Using `as-contract` unnecessarily, which can lead to unexpected behavior. -2. Forgetting that `as-contract` changes the `tx-sender` context, potentially affecting other parts of the code. -3. Not implementing proper access controls around `as-contract` calls, which could lead to unauthorized actions. - -## Related Functions - -- `contract-caller`: Used to get the original caller of a contract function. -- `tx-sender`: Represents the current sender (changes within `as-contract`). -- `stx-transfer?`: Often used with `as-contract` for token transfers. - -## Conclusion - -The `as-contract` function is a powerful tool in Clarity that allows contracts to perform actions with their own authority. While it enables complex contract architectures and functionalities, it should be used judiciously and with proper security measures to prevent potential vulnerabilities or unintended behaviors in smart contracts. diff --git a/content/docs/stacks/clarity/functions/as-max-len.mdx b/content/docs/stacks/clarity/functions/as-max-len.mdx deleted file mode 100644 index db9325893..000000000 --- a/content/docs/stacks/clarity/functions/as-max-len.mdx +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: as-max-len? -description: Use the as-max-len? function to check and limit sequence lengths in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(as-max-len? sequence max_length) -``` - -- Input: - - `sequence`: A sequence of type A (list, buff, string-ascii, or string-utf8) - - `max_length`: A uint literal representing the maximum allowed length -- Output: `(optional sequence_A)` - -## Why it matters - -The `as-max-len?` function is crucial for: - -1. Enforcing length limits on sequences in smart contracts. -2. Safely appending to lists or other sequences with maximum lengths. -3. Validating input data before processing. -4. Preventing potential overflow or excessive resource consumption. - -## When to use it - -Use the `as-max-len?` function when you need to: - -- Check if a sequence is within a specified maximum length. -- Safely append to a list or other sequence with a known maximum length. -- Validate user input or data from external sources. -- Implement logic that depends on sequence length constraints. - -## Best Practices - -- Always use `as-max-len?` before appending to lists or other sequences with maximum lengths. -- Combine with `unwrap!` or `unwrap-panic` when you're certain the length should be within limits. -- Use meaningful error handling when the length check fails. -- Consider the performance impact of frequent length checks in your contract logic. - -## Practical Example: Safe List Append - -Let's implement a function that safely appends to a list with a maximum length: - -```clarity -(define-data-var myList (list 5 uint) (list)) - -(define-public (safe-append (item uint)) - (let - ( - (newList (unwrap! (as-max-len? (append (var-get myList) item) u5) (err u1))) - ) - (ok (var-set myList newList)) - ) -) - -(define-read-only (get-list) - (var-get myList) -) - -;; Usage -(safe-append u1) ;; Returns (ok true) -(safe-append u2) ;; Returns (ok true) -(safe-append u3) ;; Returns (ok true) -(safe-append u4) ;; Returns (ok true) -(safe-append u5) ;; Returns (ok true) -(safe-append u6) ;; Returns (err u1) - -(get-list) ;; Returns (list u1 u2 u3 u4 u5) -``` - -This example demonstrates: -1. Using `as-max-len?` to check if appending to the list would exceed the maximum length. -2. Combining `as-max-len?` with `unwrap!` for concise error handling. -3. Safely updating a list variable only if the length check passes. - -## Common Pitfalls - -1. Forgetting to use `as-max-len?` when appending to sequences with maximum lengths. -2. Using a variable for the `max_length` parameter, which is not allowed (it must be a uint literal). -3. Not handling the `none` case when `as-max-len?` returns an optional. - -## Related Functions - -- `append`: Used to add elements to lists. -- `concat`: Used to join two sequences together. -- `len`: Used to get the current length of a sequence. - -## Conclusion - -The `as-max-len?` function is a critical tool for managing sequence lengths in Clarity smart contracts. By using it consistently, you can create more robust and secure contracts that properly handle length constraints, preventing potential vulnerabilities related to unbounded data growth or unexpected input sizes. diff --git a/content/docs/stacks/clarity/functions/asserts.mdx b/content/docs/stacks/clarity/functions/asserts.mdx deleted file mode 100644 index 0570b6587..000000000 --- a/content/docs/stacks/clarity/functions/asserts.mdx +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: asserts! -description: Use the asserts! function for conditional assertions in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(asserts! bool-expr thrown-value) -``` - -- Input: - - `bool-expr`: A boolean expression - - `thrown-value`: The value to be returned if the assertion fails -- Output: `bool` or `thrown-value` - -## Why it matters - -The `asserts!` function is crucial for: - -1. Implementing conditional checks in smart contracts. -2. Enforcing preconditions before executing critical operations. -3. Providing meaningful error responses when conditions are not met. -4. Improving contract security by validating inputs and state. - -## When to use it - -Use the `asserts!` function when you need to: - -- Validate conditions before proceeding with contract execution. -- Ensure certain requirements are met before performing sensitive operations. -- Provide clear error messages or codes when conditions are not satisfied. -- Implement guard clauses to protect against invalid inputs or states. - -## Best Practices - -- Use `asserts!` early in functions to validate preconditions. -- Provide meaningful error values that can be easily interpreted by users or other contracts. -- Combine multiple conditions using `and` or `or` for complex assertions. -- Consider using `asserts!` in combination with `unwrap!` for handling optional values. - -## Practical Example: Token Transfer with Balance Check - -Let's implement a simple token transfer function that uses `asserts!` to check the sender's balance: - -```clarity -(define-map Balances principal uint) - -(define-public (transfer (amount uint) (recipient principal)) - (let - ( - (senderBalance (default-to u0 (map-get? Balances tx-sender))) - ) - (asserts! (>= senderBalance amount) (err u1)) ;; Insufficient balance - (asserts! (not (is-eq tx-sender recipient)) (err u2)) ;; Can't send to self - - (map-set Balances tx-sender (- senderBalance amount)) - (map-set Balances recipient (+ (default-to u0 (map-get? Balances recipient)) amount)) - (ok true) - ) -) - -(map-set Balances tx-sender u1000) ;; Set the sender's balance to 1000 - -;; Usage -(transfer u100 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5) ;; Returns (ok true) -(transfer u100 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM) ;; Returns (err u2) Can't send to self -(transfer u1000 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5) ;; Returns (err u1) Insufficient balance -``` - -This example demonstrates: -1. Using `asserts!` to check if the sender has sufficient balance before transferring. -2. Using `asserts!` to prevent sending tokens to oneself. -3. Providing different error codes for different types of failures. - -## Common Pitfalls - -1. Forgetting to handle the error case when calling functions that use `asserts!`. -2. Using `asserts!` excessively, which can make code harder to read and maintain. -3. Providing vague or unhelpful error values when assertions fail. - -## Related Functions - -- `unwrap!`: Used to extract values from optionals with a fallback error. -- `unwrap-panic`: Similar to `unwrap!` but causes a panic instead of returning an error. -- `try!`: Used for propagating errors in a chain of operations. - -## Conclusion - -The `asserts!` function is a powerful tool for implementing conditional checks and enforcing invariants in Clarity smart contracts. By using it effectively, you can create more robust and secure contracts that gracefully handle edge cases and provide meaningful feedback when conditions are not met. diff --git a/content/docs/stacks/clarity/functions/at-block.mdx b/content/docs/stacks/clarity/functions/at-block.mdx deleted file mode 100644 index d2d8c19fe..000000000 --- a/content/docs/stacks/clarity/functions/at-block.mdx +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: at-block -description: Use the at-block function to evaluate expressions at a specific block in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(at-block id-block-hash expr) -``` - - -- Input: - - `id-block-hash`: A 32-byte buffer representing a block hash - - `expr`: An expression to be evaluated -- Output: The result of evaluating `expr` - -## Why it matters - -The `at-block` function is crucial for: - -1. Accessing historical contract state at a specific block. -2. Implementing time-dependent logic based on blockchain state. -3. Verifying past conditions or values in the contract. -4. Creating mechanisms that depend on specific blockchain checkpoints. - -## When to use it - -Use the `at-block` function when you need to: - -- Evaluate contract state or expressions as they were at a specific past block. -- Implement logic that depends on historical blockchain data. -- Verify past conditions without relying on stored state. -- Create time-locked or checkpoint-based features in your contract. - -## Best Practices - -- Only use `at-block` when historical data is necessary, as it can be computationally expensive. -- Ensure the block hash used is from the `id-header-hash` property, not `header-hash`. -- Use read-only expressions within `at-block` to maintain determinism. -- Be aware of the potential for chain reorganizations when using recent block hashes. - -## Practical Example: Historical Price Check - -Let's implement a simple function that checks if a price was above a certain threshold at a specific block: - -```clarity -(define-map AssetPrices uint uint) - -(define-public (set-price (price uint)) - (ok (map-set AssetPrices block-height price)) -) - -(define-read-only (was-price-above-at-block (threshold uint) (blockHash (buff 32))) - (at-block blockHash - (let - ( - (pastPrice (default-to u0 (map-get? AssetPrices block-height))) - ) - (> pastPrice threshold) - ) - ) -) - -;; Usage -(set-price u100) -;; ... several blocks later -(was-price-above-at-block u50 0x123456...) ;; Returns true if the price was above 50 at the specified block -``` - - -This example demonstrates: -1. Using `at-block` to evaluate a condition based on historical data. -2. Combining `at-block` with map lookups to access past state. -3. Implementing a read-only function that depends on blockchain history. - -## Common Pitfalls - -1. Using `header-hash` instead of `id-header-hash`, which can lead to inconsistencies across forks. -2. Attempting to modify state within an `at-block` expression, which is not allowed. -3. Overusing `at-block`, which can lead to performance issues due to the cost of historical lookups. - -## Related Functions - -- `get-block-info?`: Used to retrieve information about specific blocks. -- `block-height`: Often used in conjunction with `at-block` for time-based logic. -- `id-header-hash`: Provides the correct hash to use with `at-block`. - -## Conclusion - -The `at-block` function is a powerful tool for implementing history-dependent logic in Clarity smart contracts. By allowing contracts to evaluate expressions as they would have at a specific past block, it enables sophisticated time-based mechanisms and historical verifications. However, this function should be used judiciously due to its potential performance impact and the complexities of working with blockchain history. diff --git a/content/docs/stacks/clarity/functions/begin.mdx b/content/docs/stacks/clarity/functions/begin.mdx deleted file mode 100644 index dfaeabeb1..000000000 --- a/content/docs/stacks/clarity/functions/begin.mdx +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: begin -description: Use the begin function to evaluate multiple expressions in sequence in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(begin expr1 expr2 expr3 ... expr-last) -``` - - -- Input: Two or more expressions of any type -- Output: The value of the last expression - -## Why it matters - -The `begin` function is crucial for: - -1. Grouping multiple expressions into a single expression. -2. Executing a series of operations in a specific order. -3. Creating complex logic flows within functions or conditions. -4. Allowing side effects while returning a specific value. - -## When to use it - -Use the `begin` function when you need to: - -- Perform multiple operations in sequence within a single expression. -- Execute side effects before returning a final value. -- Group multiple expressions where only one is allowed (e.g., in function bodies or condition branches). -- Create more complex, multi-step logic within your smart contract functions. - -## Best Practices - -- Use `begin` to keep related operations together for better readability. -- Ensure that any expressions that return a response type (ok or err) are properly checked. -- Be mindful of the order of expressions, as they are evaluated sequentially. -- Use `begin` to make your code more expressive and easier to understand. - -## Practical Example: User Registration with Logging - -Let's implement a simple user registration function that performs multiple actions: - -```clarity -(define-map Users principal bool) -(define-data-var userCount uint u0) - -(define-public (register-user) - (begin - (asserts! (is-none (map-get? Users tx-sender)) (err u1)) - (map-set Users tx-sender true) - (var-set userCount (+ (var-get userCount) u1)) - (print { registered: true, user: tx-sender }) - (ok true) - ) -) - -;; Usage -(register-user) ;; Returns (ok true) and logs the new user -``` - - -This example demonstrates: -1. Using `begin` to group multiple operations in a single function. -2. Performing checks, updates, and logging in a specific order. -3. Executing side effects (printing) before returning the final value. - -## Common Pitfalls - -1. Forgetting to return a value in the last expression of a `begin` block. -2. Not properly handling responses from functions that return (ok) or (err) within the `begin` block. -3. Relying on side effects of earlier expressions without considering their order of execution. - -## Related Functions - -- `let`: Used for creating local bindings within a limited scope. -- `asserts!`: Often used within `begin` blocks for condition checking. -- `print`: Useful for logging within `begin` blocks during development. - -## Conclusion - -The `begin` function is a fundamental tool in Clarity for grouping multiple expressions and creating more complex logic flows. By allowing you to execute a series of operations in a specific order while returning a single value, `begin` enhances the expressiveness and capability of Clarity smart contracts. When used judiciously, this function can significantly improve code readability and organization. diff --git a/content/docs/stacks/clarity/functions/bit-and.mdx b/content/docs/stacks/clarity/functions/bit-and.mdx deleted file mode 100644 index b377a0afb..000000000 --- a/content/docs/stacks/clarity/functions/bit-and.mdx +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: bit-and -description: Use the bit-and function for bitwise operations in Clarity smart contracts. ---- - -The `bit-and` function in Clarity performs a bitwise AND operation on two or more integer inputs. It's a powerful tool for working with compact data representations and flag systems in smart contracts. - -## Function Signature - -```clarity -(bit-and i1 i2...) -``` - -- Input: Two or more integers (int or uint) -- Output: A single integer (int or uint) - -## Why it matters - -The `bit-and` function is crucial for: - -1. Efficient data storage: Allows packing multiple boolean flags into a single integer. -2. Permission systems: Enables checking for specific permissions in a compact format. -3. Bitmasking: Useful for isolating specific bits in a larger integer. -4. Low-level optimizations: Can be used for certain mathematical operations. - -## When to use it - -Use `bit-and` when you need to: - -- Check if specific bits are set in a bitfield -- Implement compact permission or flag systems -- Clear specific bits while leaving others unchanged -- Perform certain low-level optimizations - -## Best Practices - -- Always use constants for bit flags to improve readability and maintainability. -- Be cautious when using with signed integers, as the sign bit can affect results. -- Combine with other bitwise operations like `bit-or` and `bit-not` for more complex manipulations. -- Document your bit flag meanings clearly in your contract. - -## Practical Example: Role-Based Access Control - -Let's implement a simple role-based access control system using `bit-and`: - -```clarity -;; Define role constants -(define-constant ROLE_ADMIN u1) ;; 0001 -(define-constant ROLE_MODERATOR u2) ;; 0010 -(define-constant ROLE_USER u4) ;; 0100 - -;; Map to store user roles -(define-map UserRoles principal uint) - -;; Function to check if a user has a specific role -(define-read-only (has-role? (user principal) (role uint)) - (let - ((userRole (default-to u0 (map-get? UserRoles user)))) - (is-eq (bit-and userRole role) role) - ) -) - -;; Function to add a role to a user -(define-public (add-role (user principal) (role uint)) - (let - ((currentRole (default-to u0 (map-get? UserRoles user)))) - (ok (map-set UserRoles user (bit-or currentRole role))) - ) -) - -;; Function to remove a role from a user -(define-public (remove-role (user principal) (role uint)) - (let - ((currentRole (default-to u0 (map-get? UserRoles user)))) - (ok (map-set UserRoles user (bit-and currentRole (bit-not role)))) - ) -) - -;; Example usage -(add-role tx-sender (bit-or ROLE_MODERATOR ROLE_USER)) -(has-role? tx-sender ROLE_MODERATOR) ;; Returns true -(has-role? tx-sender ROLE_ADMIN) ;; Returns false -(remove-role tx-sender ROLE_USER) -(has-role? tx-sender ROLE_USER) ;; Returns false -``` - -This example demonstrates: -1. Using `bit-and` to check for specific roles. -2. Combining `bit-and` with `bit-or` and `bit-not` for role management. -3. Efficient storage of multiple roles in a single integer. - -## Common Pitfalls - -1. Forgetting that `bit-and` with 0 always results in 0. -2. Not accounting for the sign bit when using signed integers. -3. Overcomplicating bit flag systems, making them hard to maintain. - -## Related Functions - -- `bit-or`: Used to set bits or combine flags. -- `bit-not`: Used to invert bits, often in combination with `bit-and` for clearing specific bits. -- `bit-xor`: Used for toggling specific bits. - -## Conclusion - -The `bit-and` function is a powerful tool for working with compact data representations in Clarity. By mastering this function along with other bitwise operations, you can create efficient and sophisticated smart contracts that make optimal use of storage and perform complex flag-based logic. diff --git a/content/docs/stacks/clarity/functions/bit-not.mdx b/content/docs/stacks/clarity/functions/bit-not.mdx deleted file mode 100644 index e4ebc43ce..000000000 --- a/content/docs/stacks/clarity/functions/bit-not.mdx +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: bit-not -description: Use the bit-not function for bitwise complement operations in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(bit-not i1) -``` - -- Input: An integer (`int` or `uint`) -- Output: An integer of the same type as the input (`int` or `uint`) - -## Why it matters - -The `bit-not` function is crucial for: - -1. Performing bitwise complement operations in smart contracts. -2. Implementing certain logical operations and algorithms. -3. Manipulating binary data at the bit level. -4. Creating bitmasks for various purposes. - -## When to use it - -Use the `bit-not` function when you need to: - -- Invert all bits in an integer value. -- Create a bitmask for bitwise operations. -- Implement certain cryptographic or hashing algorithms. -- Perform low-level data manipulations. - -## Best Practices - -- Be aware of the differences between signed (`int`) and unsigned (`uint`) integers when using `bit-not`. -- Remember that `bit-not` on a `uint` will result in a large positive number due to two's complement representation. -- Use `bit-not` in combination with other bitwise operations (`bit-and`, `bit-or`, `bit-xor`) for complex bit manipulations. -- Consider the readability of your code when using bitwise operations extensively. - -## Practical Example: Simple Flag System - -Let's implement a simple flag system using `bit-not` and other bitwise operations: - -```clarity -(define-constant FLAG_A u1) ;; 0001 -(define-constant FLAG_B u2) ;; 0010 -(define-constant FLAG_C u4) ;; 0100 -(define-constant FLAG_D u8) ;; 1000 - -(define-data-var userFlags uint u0) - -(define-public (toggle-flag (flag uint)) - (ok (var-set userFlags (bit-xor (var-get userFlags) flag))) -) - -(define-public (clear-all-flags-except (flag uint)) - (ok (var-set userFlags (bit-and (var-get userFlags) flag))) -) - -(define-public (set-all-flags-except (flag uint)) - (ok (var-set userFlags (bit-and (bit-not (var-get userFlags)) flag))) -) - -(define-read-only (has-flag (flag uint)) - (is-eq flag (bit-and (var-get userFlags) flag)) -) -``` - -This example demonstrates: -1. Using `bit-not` in combination with `bit-and` to set all flags except a specific one. -2. Implementing a flag system using bitwise operations for efficient storage and manipulation. -3. Combining `bit-not` with other bitwise operations for complex flag manipulations. - -## Common Pitfalls - -1. Forgetting that `bit-not` on a `uint` results in a large positive number, not a negative number. -2. Overlooking the sign bit when using `bit-not` with signed integers. -3. Not considering the full range of bits when applying `bit-not` to smaller integer values. - -## Related Functions - -- `bit-and`: Used for bitwise AND operations. -- `bit-or`: Used for bitwise OR operations. -- `bit-xor`: Used for bitwise XOR operations. -- `bit-shift-left`: Used for left-shifting bits. -- `bit-shift-right`: Used for right-shifting bits. - -## Conclusion - -The `bit-not` function is a powerful tool for bitwise operations in Clarity smart contracts. When used in combination with other bitwise functions, this function enables efficient implementation of flags, bitmasks, and low-level data manipulations. However, you should be mindful of the differences between signed and unsigned integers and the potential for unexpected results when not used carefully. diff --git a/content/docs/stacks/clarity/functions/bit-or.mdx b/content/docs/stacks/clarity/functions/bit-or.mdx deleted file mode 100644 index 81c6427f4..000000000 --- a/content/docs/stacks/clarity/functions/bit-or.mdx +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: bit-or -description: Use the bit-or function for bitwise OR operations in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(bit-or i1 i2...) -``` - -- Input: Two or more integers (`int` or `uint`) -- Output: An integer of the same type as the inputs (`int` or `uint`) - -## Why it matters - -The `bit-or` function is crucial for: - -1. Performing bitwise OR operations in smart contracts. -2. Combining flags or bitmasks efficiently. -3. Implementing certain logical operations and algorithms. -4. Manipulating binary data at the bit level. - -## When to use it - -Use the `bit-or` function when you need to: - -- Combine multiple flags or bitmasks into a single value. -- Set specific bits in an integer without affecting others. -- Implement certain bitwise algorithms or data structures. -- Perform low-level data manipulations involving binary operations. - -## Best Practices - -- Ensure all input values are of the same type (either all `int` or all `uint`). -- Remember that `bit-or` with `0` has no effect, which can be useful for conditional operations. -- Use `bit-or` in combination with other bitwise operations for complex bit manipulations. -- Consider readability when using bitwise operations extensively; add comments to explain the purpose. - -## Practical Example: Permission System - -Let's implement a simple permission system using `bit-or` and other bitwise operations: - -```clarity -(define-constant PERMISSION_READ u1) ;; 0001 -(define-constant PERMISSION_WRITE u2) ;; 0010 -(define-constant PERMISSION_EXECUTE u4) ;; 0100 -(define-constant PERMISSION_ADMIN u8) ;; 1000 - -(define-map UserPermissions principal uint) - -(define-public (grant-permission (user principal) (permission uint)) - (let - ( - (currentPermissions (default-to u0 (map-get? UserPermissions user))) - ) - (ok (map-set UserPermissions user (bit-or currentPermissions permission))) - ) -) - -(define-public (revoke-permission (user principal) (permission uint)) - (let - ( - (currentPermissions (default-to u0 (map-get? UserPermissions user))) - ) - (ok (map-set UserPermissions user (bit-and currentPermissions (bit-not permission)))) - ) -) - -(define-read-only (has-permission (user principal) (permission uint)) - (let - ( - (userPermission (default-to u0 (map-get? UserPermissions user))) - ) - (is-eq permission (bit-and userPermission permission)) - ) -) - -;; Usage -(grant-permission tx-sender (bit-or PERMISSION_READ PERMISSION_WRITE)) -(has-permission tx-sender PERMISSION_READ) ;; Returns true -(has-permission tx-sender PERMISSION_EXECUTE) ;; Returns false -``` - - - -This example demonstrates: -1. Using `bit-or` to combine multiple permissions into a single value. -2. Implementing a permission system using bitwise operations for efficient storage and checks. -3. Combining `bit-or` with other bitwise operations like `bit-and` and `bit-not` for complex permission management. - -## Common Pitfalls - -1. Mixing signed (`int`) and unsigned (`uint`) integers in a single `bit-or` operation. -2. Forgetting that `bit-or` with all bits set (`-1` for `int`, maximum value for `uint`) always results in all bits set. -3. Not considering the full range of bits when using `bit-or` with smaller integer values. - -## Related Functions - -- `bit-and`: Used for bitwise AND operations. -- `bit-xor`: Used for bitwise XOR operations. -- `bit-not`: Used for bitwise NOT operations. -- `bit-shift-left`: Used for left-shifting bits. -- `bit-shift-right`: Used for right-shifting bits. - -## Conclusion - -The `bit-or` function is a powerful tool for bitwise operations in Clarity smart contracts. When used in combination with other bitwise functions, this function enables efficient implementation of flags, permissions, and other bit-level data manipulations. However, be mindful of the types of integers used and the effects of the operation on the full range of bits to avoid unexpected results. diff --git a/content/docs/stacks/clarity/functions/bit-shift-left.mdx b/content/docs/stacks/clarity/functions/bit-shift-left.mdx deleted file mode 100644 index 31636c79d..000000000 --- a/content/docs/stacks/clarity/functions/bit-shift-left.mdx +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: bit-shift-left -description: Use the bit-shift-left function for bitwise left shift operations in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(bit-shift-left i1 shamt) -``` - -- Input: - - `i1`: An integer (`int` or `uint`) - - `shamt`: A `uint` representing the number of places to shift -- Output: An integer of the same type as `i1` (`int` or `uint`) - -## Why it matters - -The `bit-shift-left` function is crucial for: - -1. Implementing certain bitwise algorithms and data structures. -2. Manipulating binary data at the bit level. -3. Creating bitmasks for various purposes. -4. Low-level optimizations in specific scenarios. - -## When to use it - -Use the `bit-shift-left` function when you need to: - -- Implement certain cryptographic or hashing algorithms. -- Perform low-level data manipulations involving binary operations. -- Create specific bit patterns or masks. -- Optimize certain bitwise operations. - -## Best Practices - -- Remember that shifting beyond the bit width of the integer (128 bits in Clarity) will result in zero. -- Use `uint` for `shamt` to avoid potential issues with negative shift amounts. -- Be aware of the potential for overflow when shifting left, especially with large numbers or shift amounts. -- For multiplication by powers of 2, use the `pow` function instead, as it provides built-in overflow protection. - -## Practical Example: Flag Management - -Let's implement a simple flag management system using `bit-shift-left`: - -```clarity -(define-constant FLAG_READ u1) -(define-constant FLAG_WRITE u2) -(define-constant FLAG_EXECUTE u4) - -(define-read-only (create-flag (flagPosition uint)) - (bit-shift-left u1 flagPosition) -) - -(define-read-only (set-flag (currentFlags uint) (flag uint)) - (bit-or currentFlags flag) -) - -(define-read-only (check-flag (flags uint) (flag uint)) - (is-eq (bit-and flags flag) flag) -) - -;; Usage -(set-flag (bit-or FLAG_READ FLAG_WRITE) FLAG_EXECUTE) ;; Returns u7 (READ | WRITE | EXECUTE) -(check-flag u7 FLAG_WRITE) ;; Returns true -(check-flag u7 (create-flag u3)) ;; Returns false -``` - -This example demonstrates: -1. Using `bit-shift-left` to create individual flags. -2. Combining `bit-shift-left` with `bit-or` to set flags. -3. Using `bit-and` to check if a specific flag is set. - -## Common Pitfalls - -1. Using `bit-shift-left` for multiplication without considering overflow risks. -2. Not considering the modulo behavior when shifting by amounts greater than or equal to 128. -3. Using a negative or non-uint value for the shift amount, which is not allowed. - -## Related Functions - -- `bit-shift-right`: Used for right-shifting bits. -- `bit-and`: Often used in combination with `bit-shift-left` for masking operations. -- `bit-or`: Used for combining flags or masks created with `bit-shift-left`. -- `pow`: Preferred for safe multiplication by powers of 2. - -## Conclusion - -The `bit-shift-left` function is a powerful tool for bitwise operations in Clarity smart contracts. This function is essential for creating bitmasks, implementing various bitwise algorithms, and performing low-level optimizations. However, you should be cautious about potential overflows and avoid using it for general multiplication tasks, where the `pow` function is more appropriate due to its built-in overflow protection. diff --git a/content/docs/stacks/clarity/functions/bit-shift-right.mdx b/content/docs/stacks/clarity/functions/bit-shift-right.mdx deleted file mode 100644 index 9a291de4d..000000000 --- a/content/docs/stacks/clarity/functions/bit-shift-right.mdx +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: bit-shift-right -description: Use the bit-shift-right function for bitwise right shift operations in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(bit-shift-right i1 shamt) -``` - -- Input: - - `i1`: An integer (`int` or `uint`) - - `shamt`: A `uint` representing the number of places to shift -- Output: An integer of the same type as `i1` (`int` or `uint`) - -## Why it matters - -The `bit-shift-right` function is crucial for: - -1. Performing efficient division by powers of 2. -2. Implementing certain bitwise algorithms and data structures. -3. Manipulating binary data at the bit level. -4. Extracting specific bit patterns from integers. - -## When to use it - -Use the `bit-shift-right` function when you need to: - -- Divide a number by a power of 2 efficiently. -- Implement certain cryptographic or hashing algorithms. -- Perform low-level data manipulations involving binary operations. -- Extract specific bits or bit patterns from integers. - -## Best Practices - -- Be aware that shifting right by `n` bits is equivalent to integer division by 2^n. -- Remember that for signed integers (`int`), the sign bit is preserved during right shifts. -- Use `uint` for `shamt` to avoid potential issues with negative shift amounts. -- Consider the differences in behavior between signed and unsigned integers when right-shifting. - -## Practical Example: Efficient Power of 2 Division - -Let's implement a function that efficiently divides by powers of 2 using `bit-shift-right`: - -```clarity -(define-read-only (divide-by-power-of-2 (value int) (power uint)) - (bit-shift-right value power) -) - -(define-read-only (extract-lowest-bits (value uint) (numBits uint)) - (bit-and value (- (bit-shift-left u1 numBits) u1)) -) - -;; Usage -(divide-by-power-of-2 128 u3) ;; Returns 16 (128 / 2^3) -(divide-by-power-of-2 -128 u3) ;; Returns -16 (-128 / 2^3) -(extract-lowest-bits u171 u4) ;; Returns u11 (binary: 1011) -``` - -This example demonstrates: -1. Using `bit-shift-right` for efficient division by powers of 2. -2. Handling both positive and negative numbers in division. -3. Combining `bit-shift-right` with other bitwise operations to extract specific bit patterns. - -## Common Pitfalls - -1. Forgetting that right-shifting signed integers preserves the sign bit. -2. Not considering the modulo behavior when shifting by amounts greater than or equal to 128. -3. Using a negative or non-uint value for the shift amount, which is not allowed. - -## Related Functions - -- `bit-shift-left`: Used for left-shifting bits. -- `bit-and`: Often used in combination with `bit-shift-right` for masking operations. -- `/`: Used for general division, but less efficient for powers of 2 compared to bit shifting. - -## Conclusion - -The `bit-shift-right` function is a powerful tool for bitwise operations in Clarity smart contracts. This function enables efficient division by powers of 2 and is essential for extracting specific bit patterns and implementing various bitwise algorithms. However, be mindful of the differences between signed and unsigned integers when using this function, as well as its behavior with large shift amounts. diff --git a/content/docs/stacks/clarity/functions/bit-xor.mdx b/content/docs/stacks/clarity/functions/bit-xor.mdx deleted file mode 100644 index 62de90a08..000000000 --- a/content/docs/stacks/clarity/functions/bit-xor.mdx +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: bit-xor -description: Use the bit-xor function for bitwise exclusive OR operations in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(bit-xor i1 i2...) -``` - -- Input: Two or more integers (`int` or `uint`) -- Output: An integer of the same type as the inputs (`int` or `uint`) - -## Why it matters - -The `bit-xor` function is crucial for: - -1. Performing bitwise exclusive OR operations in smart contracts. -2. Implementing certain cryptographic algorithms and hash functions. -3. Creating toggle mechanisms for binary flags. -4. Detecting changes between two bit patterns. - -## When to use it - -Use the `bit-xor` function when you need to: - -- Implement exclusive OR logic on binary data. -- Toggle specific bits in a value without affecting others. -- Compare two bit patterns to find differences. -- Create simple encryption or hashing mechanisms. - -## Best Practices - -- Ensure all input values are of the same type (either all `int` or all `uint`). -- Remember that `bit-xor` with 0 returns the original value, which can be useful for conditional operations. -- Use `bit-xor` in combination with other bitwise operations for complex bit manipulations. -- Consider the readability of your code when using bitwise operations extensively; add comments to explain the purpose. - -## Practical Example: Simple Toggle Mechanism - -Let's implement a simple toggle mechanism using `bit-xor`: - -```clarity -(define-data-var flags uint u0) - -(define-read-only (get-flag (flagPosition uint)) - (is-eq (bit-and (var-get flags) (bit-shift-left u1 flagPosition)) u0) -) - -(define-public (toggle-flag (flagPosition uint)) - (begin - (asserts! (< flagPosition u8) (err u1)) ;; Ensure flag position is valid - (ok (var-set flags (bit-xor (var-get flags) (bit-shift-left u1 flagPosition)))) - ) -) - -;; Usage -(toggle-flag u2) ;; Toggles the 3rd bit (position 2) -(get-flag u2) ;; Returns false -(toggle-flag u2) ;; Toggles the 3rd bit again (position 2) -(get-flag u2) ;; Returns true -``` - -This example demonstrates: -1. Using `bit-xor` to toggle individual bits in a flags variable. -2. Combining `bit-xor` with other bitwise operations like `bit-and` and `bit-shift-left`. -3. Implementing a simple flag system using bitwise operations for efficient storage and manipulation. - -## Common Pitfalls - -1. Mixing signed (`int`) and unsigned (`uint`) integers in a single `bit-xor` operation. -2. Forgetting that `bit-xor` of a value with itself always results in 0. -3. Not considering the full range of bits when using `bit-xor` with smaller integer values. - -## Related Functions - -- `bit-and`: Used for bitwise AND operations. -- `bit-or`: Used for bitwise OR operations. -- `bit-not`: Used for bitwise NOT operations. -- `bit-shift-left`: Often used in combination with `bit-xor` for flag operations. -- `bit-shift-right`: Used for right-shifting bits. - -## Conclusion - -The `bit-xor` function is a powerful tool for bitwise operations in Clarity smart contracts. When used in combination with other bitwise functions, it enables efficient implementation of toggles, flags, and other bit-level data manipulations. To avoid unexpected results, be mindful of the types of integers used and the effects of the operation on the full range of bits. diff --git a/content/docs/stacks/clarity/functions/buff-to-int-be.mdx b/content/docs/stacks/clarity/functions/buff-to-int-be.mdx deleted file mode 100644 index 1ba1d779b..000000000 --- a/content/docs/stacks/clarity/functions/buff-to-int-be.mdx +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: buff-to-int-be -description: Convert a byte buffer to a signed integer using big-endian encoding in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(buff-to-int-be (buff 16)) -``` - -- Input: A byte buffer of up to 16 bytes -- Output: A signed integer (`int`) - -## Why it matters - -The `buff-to-int-be` function is crucial for: - -1. Converting byte data to signed integers in smart contracts. -2. Handling data from external sources or other contracts that use big-endian encoding. -3. Implementing protocols or algorithms that require big-endian integer representation. -4. Interoperating with systems that use big-endian byte order. - -## When to use it - -Use the `buff-to-int-be` function when you need to: - -- Convert a big-endian encoded byte buffer to a signed integer. -- Process input data that represents signed integers in big-endian format. -- Implement cryptographic or mathematical operations that expect big-endian integer inputs. -- Ensure compatibility with external systems using big-endian encoding. - -## Best Practices - -- Ensure the input buffer is no larger than 16 bytes to avoid errors. -- Be aware that smaller buffers are zero-padded on the left, affecting the resulting integer value. -- Consider using `buff-to-uint-be` for unsigned integers if the sign is not needed. -- Handle potential errors when the input buffer might be invalid or empty. - -## Practical Example: Decoding a Signed Integer from External Data - -Let's implement a function that processes external data containing a big-endian encoded signed integer: - -```clarity -(define-read-only (process-external-data (data (buff 16))) - (let - ( - (value (buff-to-int-be data)) - ) - (if (< value 0) - (err "Negative value not allowed") - (ok value) - ) - ) -) - -;; Usage -(process-external-data 0x0000000000000001) ;; Returns (ok 1) -(process-external-data 0xffffffffffffffff) ;; Returns (err "Negative value not allowed") -(process-external-data 0x7fffffffffffffff) ;; Returns (ok 9223372036854775807) -``` - -This example demonstrates: -1. Using `buff-to-int-be` to convert external data to a signed integer. -2. Handling both positive and negative values resulting from the conversion. -3. Implementing input validation based on the converted integer value. - -## Common Pitfalls - -1. Forgetting that the function interprets the input as big-endian, which might lead to unexpected values if the data is actually little-endian. -2. Not handling potential negative values when working with signed integers. -3. Assuming a specific buffer length, which could lead to unexpected results with shorter inputs due to left-padding. - -## Related Functions - -- `buff-to-int-le`: Converts a byte buffer to a signed integer using little-endian encoding. -- `buff-to-uint-be`: Converts a byte buffer to an unsigned integer using big-endian encoding. -- `int-to-ascii`: Converts an integer to its ASCII string representation. - -## Conclusion - -The `buff-to-int-be` function is a powerful tool for working with big-endian encoded signed integers in Clarity smart contracts. By understanding its behavior with different input sizes and potential sign issues, you can effectively process and validate external data, implement complex algorithms, and ensure compatibility with big-endian systems in your smart contract applications. diff --git a/content/docs/stacks/clarity/functions/buff-to-int-le.mdx b/content/docs/stacks/clarity/functions/buff-to-int-le.mdx deleted file mode 100644 index 9d65df65d..000000000 --- a/content/docs/stacks/clarity/functions/buff-to-int-le.mdx +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: buff-to-int-le -description: Convert a byte buffer to a signed integer using little-endian encoding in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(buff-to-int-le (buff 16)) -``` - -- Input: A byte buffer of up to 16 bytes -- Output: A signed integer (`int`) - -## Why it matters - -The `buff-to-int-le` function is crucial for: - -1. Converting byte data to signed integers using little-endian encoding. -2. Handling data from external sources or other contracts that use little-endian encoding. -3. Implementing protocols or algorithms that require little-endian integer representation. -4. Interoperating with systems that use little-endian byte order. - -## When to use it - -Use the `buff-to-int-le` function when you need to: - -- Convert a little-endian encoded byte buffer to a signed integer. -- Process input data that represents signed integers in little-endian format. -- Implement cryptographic or mathematical operations that expect little-endian integer inputs. -- Ensure compatibility with external systems using little-endian encoding. - -## Best Practices - -- Ensure the input buffer is no larger than 16 bytes to avoid errors. -- Be aware that smaller buffers are zero-padded on the right, affecting the resulting integer value. -- Consider using `buff-to-uint-le` for unsigned integers if the sign is not needed. -- Handle potential errors when the input buffer might be invalid or empty. - -## Practical Example: Decoding a Signed Integer from External Data - -Let's implement a function that processes external data containing a little-endian encoded signed integer: - -```clarity -(define-read-only (process-external-data-le (data (buff 16))) - (let - ( - (value (buff-to-int-le data)) - ) - (if (< value 0) - (err "Negative value not allowed") - (ok value) - ) - ) -) - -;; Usage -(process-external-data-le 0x01000000000000000000000000000000) ;; Returns (ok 1) -(process-external-data-le 0xffffffffffffffffffffffffffffffff) ;; Returns (err "Negative value not allowed") -(process-external-data-le 0xffffffffffffffffffffffffffffff7f) ;; Returns (ok 9223372036854775807) -``` - -This example demonstrates: -1. Using `buff-to-int-le` to convert external data to a signed integer. -2. Handling both positive and negative values resulting from the conversion. -3. Implementing input validation based on the converted integer value. - -## Common Pitfalls - -1. Confusing little-endian with big-endian encoding, leading to incorrect integer values. -2. Not handling potential negative values when working with signed integers. -3. Assuming a specific buffer length, which could lead to unexpected results with shorter inputs due to right-padding. - -## Related Functions - -- `buff-to-int-be`: Converts a byte buffer to a signed integer using big-endian encoding. -- `buff-to-uint-le`: Converts a byte buffer to an unsigned integer using little-endian encoding. -- `int-to-ascii`: Converts an integer to its ASCII string representation. - -## Conclusion - -The `buff-to-int-le` function is a powerful tool for working with little-endian encoded signed integers in Clarity smart contracts. By understanding its behavior with different input sizes and potential sign issues, you can effectively process and validate external data, implement complex algorithms, and ensure compatibility with little-endian systems in your smart contract applications. diff --git a/content/docs/stacks/clarity/functions/buff-to-uint-be.mdx b/content/docs/stacks/clarity/functions/buff-to-uint-be.mdx deleted file mode 100644 index ba1075dc5..000000000 --- a/content/docs/stacks/clarity/functions/buff-to-uint-be.mdx +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: buff-to-uint-be -description: Convert a byte buffer to an unsigned integer using big-endian encoding in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(buff-to-uint-be (buff 16)) -``` - -- Input: A byte buffer of up to 16 bytes -- Output: An unsigned integer (`uint`) - -## Why it matters - -The `buff-to-uint-be` function is crucial for: - -1. Converting byte data to unsigned integers using big-endian encoding. -2. Handling data from external sources or other contracts that use big-endian encoding. -3. Implementing protocols or algorithms that require big-endian integer representation. -4. Interoperating with systems that use big-endian byte order. - -## When to use it - -Use the `buff-to-uint-be` function when you need to: - -- Convert a big-endian encoded byte buffer to an unsigned integer. -- Process input data that represents unsigned integers in big-endian format. -- Implement cryptographic or mathematical operations that expect big-endian integer inputs. -- Ensure compatibility with external systems using big-endian encoding. - -## Best Practices - -- Ensure the input buffer is no larger than 16 bytes to avoid errors. -- Be aware that smaller buffers are zero-padded on the left, affecting the resulting integer value. -- Use `buff-to-int-be` if you need to handle signed integers instead. -- Handle potential errors when the input buffer might be invalid or empty. - -## Practical Example: Decoding an Unsigned Integer from External Data - -Let's implement a function that processes external data containing a big-endian encoded unsigned integer: - -```clarity -(define-read-only (process-external-data (data (buff 16))) - (let - ( - (value (buff-to-uint-be data)) - ) - (if (> value u1000000) - (err "Value too large") - (ok value) - ) - ) -) - -;; Usage -(process-external-data 0x00000001) ;; Returns (ok u1) -(process-external-data 0x000f4240) ;; Returns (ok u1000000) -(process-external-data 0x00989680) ;; Returns (err "Value too large") -``` - -This example demonstrates: -1. Using `buff-to-uint-be` to convert external data to an unsigned integer. -2. Implementing input validation based on the converted integer value. -3. Handling different input sizes and values. - -## Common Pitfalls - -1. Forgetting that the function interprets the input as big-endian, which might lead to unexpected values if the data is actually little-endian. -2. Not considering the full range of possible uint values when processing the result. -3. Assuming a specific buffer length, which could lead to unexpected results with shorter inputs due to left-padding. - -## Related Functions - -- `buff-to-uint-le`: Converts a byte buffer to an unsigned integer using little-endian encoding. -- `buff-to-int-be`: Converts a byte buffer to a signed integer using big-endian encoding. -- `uint-to-buff`: Converts an unsigned integer to a byte buffer. - -## Conclusion - -The `buff-to-uint-be` function is a powerful tool for working with big-endian encoded unsigned integers in Clarity smart contracts. By understanding its behavior with different input sizes and potential edge cases, you can effectively process and validate external data, implement complex algorithms, and ensure compatibility with big-endian systems in your smart contract applications. diff --git a/content/docs/stacks/clarity/functions/buff-to-uint-le.mdx b/content/docs/stacks/clarity/functions/buff-to-uint-le.mdx deleted file mode 100644 index 9b804fc42..000000000 --- a/content/docs/stacks/clarity/functions/buff-to-uint-le.mdx +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: buff-to-uint-le -description: Convert a byte buffer to an unsigned integer using little-endian encoding in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(buff-to-uint-le (buff 16)) -``` - -- Input: A byte buffer of up to 16 bytes -- Output: An unsigned integer (`uint`) - -## Why it matters - -The `buff-to-uint-le` function is crucial for: - -1. Converting byte data to unsigned integers using little-endian encoding. -2. Handling data from external sources or other contracts that use little-endian encoding. -3. Implementing protocols or algorithms that require little-endian integer representation. -4. Interoperating with systems that use little-endian byte order. - -## When to use it - -Use the `buff-to-uint-le` function when you need to: - -- Convert a little-endian encoded byte buffer to an unsigned integer. -- Process input data that represents unsigned integers in little-endian format. -- Implement cryptographic or mathematical operations that expect little-endian integer inputs. -- Ensure compatibility with external systems using little-endian encoding. - -## Best Practices - -- Ensure the input buffer is no larger than 16 bytes to avoid errors. -- Be aware that smaller buffers are zero-padded on the right, affecting the resulting integer value. -- Use `buff-to-int-le` if you need to handle signed integers instead. -- Handle potential errors when the input buffer might be invalid or empty. - -## Practical Example: Decoding an Unsigned Integer from External Data - -Let's implement a function that processes external data containing a little-endian encoded unsigned integer: - -```clarity -(define-read-only (process-external-data-le (data (buff 16))) - (let - ( - (value (buff-to-uint-le data)) - ) - (if (> value u1000000) - (err "Value too large") - (ok value) - ) - ) -) - -;; Usage -(process-external-data-le 0x01000000) ;; Returns (ok u1) -(process-external-data-le 0x40420f00) ;; Returns (ok u1000000) -(process-external-data-le 0x80969800) ;; Returns (err "Value too large") -``` - -This example demonstrates: -1. Using `buff-to-uint-le` to convert external data to an unsigned integer. -2. Implementing input validation based on the converted integer value. -3. Handling different input sizes and values. - -## Common Pitfalls - -1. Confusing little-endian with big-endian encoding, leading to incorrect integer values. -2. Not considering the full range of possible uint values when processing the result. -3. Assuming a specific buffer length, which could lead to unexpected results with shorter inputs due to right-padding. - -## Related Functions - -- `buff-to-uint-be`: Converts a byte buffer to an unsigned integer using big-endian encoding. -- `buff-to-int-le`: Converts a byte buffer to a signed integer using little-endian encoding. -- `uint-to-buff`: Converts an unsigned integer to a byte buffer. - -## Conclusion - -The `buff-to-uint-le` function is a powerful tool for working with little-endian encoded unsigned integers in Clarity smart contracts. By understanding its behavior with different input sizes and potential edge cases, you can effectively process and validate external data, implement complex algorithms, and ensure compatibility with little-endian systems in your smart contract applications. diff --git a/content/docs/stacks/clarity/functions/concat.mdx b/content/docs/stacks/clarity/functions/concat.mdx deleted file mode 100644 index 657a7329d..000000000 --- a/content/docs/stacks/clarity/functions/concat.mdx +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: concat -description: Concatenate sequences in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(concat sequence1 sequence2) -``` - -- Input: Two sequences of the same type (`sequence_A`, `sequence_A`) -- Output: A concatenated sequence of the same type (`sequence_A`) - -## Why it matters - -The `concat` function is crucial for: - -1. Combining two sequences of the same type into a single sequence. -2. Building longer strings, buffers, or lists from smaller components. -3. Dynamically constructing data structures in smart contracts. -4. Implementing string or data manipulation operations. - -## When to use it - -Use the `concat` function when you need to: - -- Join two strings together. -- Combine two byte buffers into a single buffer. -- Merge two lists into a single list. -- Build complex data structures from simpler components. - -## Best Practices - -- Ensure that both input sequences are of the same type (e.g., both strings, both buffers, or both lists). -- Be aware of the maximum length limitations for the resulting sequence type. -- Consider using `concat` in combination with other sequence manipulation functions for more complex operations. -- When working with strings, remember that Clarity distinguishes between ASCII and UTF-8 strings. - -## Practical Example: Dynamic Message Construction - -Let's implement a function that constructs a personalized message: - -```clarity -(define-public (create-greeting (name (string-ascii 20))) - (ok (concat (concat "Hello, " name) "! Welcome to our dApp.")) -) - -;; Usage -(create-greeting "Alice") ;; Returns (ok "Hello, Alice! Welcome to our dApp.") -``` - -This example demonstrates: -1. Using `concat` to join multiple string components. -2. Nesting `concat` calls to build a more complex string. -3. Combining static and dynamic parts of a message. - -## Common Pitfalls - -1. Attempting to concatenate sequences of different types, which will result in an error. -2. Not considering the maximum length of the resulting sequence, potentially leading to truncation. -3. Forgetting that `concat` only works with two sequences at a time, requiring nested calls for multiple concatenations. - -## Related Functions - -- `len`: Used to get the length of a sequence. -- `slice?`: Can be used to extract parts of a sequence before concatenation. -- `append`: Used to add elements to the end of a list (similar to `concat` for lists). - -## Conclusion - -The `concat` function is a versatile tool for combining sequences in Clarity smart contracts. Whether you're working with strings, byte buffers, or lists, `concat` provides a straightforward way to join sequences together. By understanding its behavior and limitations, you can effectively use `concat` to build dynamic data structures and implement various string and data manipulation operations in your smart contracts. diff --git a/content/docs/stacks/clarity/functions/contract-call.mdx b/content/docs/stacks/clarity/functions/contract-call.mdx deleted file mode 100644 index 2ace34a30..000000000 --- a/content/docs/stacks/clarity/functions/contract-call.mdx +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: contract-call? -description: Execute public functions in other smart contracts from within a Clarity smart contract. ---- - -## Function Signature - -```clarity -(contract-call? .contract-name function-name arg0 arg1 ...) -``` - -- Input: - - `.contract-name`: The name of the contract to call - - `function-name`: The name of the public function to execute - - `arg0, arg1, ...`: Arguments to pass to the function -- Output: `(response A B)` where A and B are the types returned by the called function - -## Why it matters - -The `contract-call?` function is crucial for: - -1. Enabling inter-contract communication and composability. -2. Allowing contracts to leverage functionality from other contracts. -3. Building complex systems of interacting smart contracts. -4. Implementing upgradeable contract patterns. - -## When to use it - -Use the `contract-call?` function when you need to: - -- Call a public function in another contract. -- Interact with standardized contracts (e.g., token contracts). -- Split complex logic across multiple contracts for better organization. -- Implement upgradeable systems by calling into newer contract versions. - -## Best Practices - -- Always check the return value of `contract-call?` as it returns a response type. -- Be aware that `contract-call?` cannot be used to call functions within the same contract. -- Consider the gas costs of external contract calls in your overall transaction budget. -- Use `as-contract` when appropriate to make calls with the contract's own principal. - -## Practical Example: Interacting with a Token Contract - -Let's implement a function that transfers tokens using a standard token contract: - -```clarity -(define-public (transfer-tokens (amount uint) (recipient principal)) - (contract-call? .token-contract transfer amount tx-sender recipient) -) - -;; Usage -(transfer-tokens u100 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM) -``` - -This example demonstrates: -1. Using `contract-call?` to interact with another contract (`.token-contract`). -2. Passing arguments to the called function, including the current `tx-sender`. -3. Returning the response from the called function directly. - -## Common Pitfalls - -1. Forgetting to handle the response from `contract-call?`, which can lead to unexpected behavior. -2. Attempting to use `contract-call?` to call functions within the same contract, which is not allowed. -3. Not considering the possibility of the called contract changing or being upgraded. - -## Related Functions - -- `as-contract`: Often used in combination with `contract-call?` to make calls as the contract principal. -- `try!`: Useful for handling the response from `contract-call?` and propagating errors. -- `unwrap!`: Can be used to extract the success value from a `contract-call?` response or return an error. - -## Conclusion - -The `contract-call?` function is a fundamental building block for creating complex, interacting systems of smart contracts on the Stacks blockchain. By enabling contracts to call functions in other contracts, this function promotes code reuse, modularity, and upgradability. However, you must be careful to handle responses correctly and consider the implications of external calls on your contract's behavior and gas usage. diff --git a/content/docs/stacks/clarity/functions/contract-of.mdx b/content/docs/stacks/clarity/functions/contract-of.mdx deleted file mode 100644 index a625ab426..000000000 --- a/content/docs/stacks/clarity/functions/contract-of.mdx +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: contract-of -description: Retrieve the principal of a contract implementing a trait in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(contract-of ) -``` - -- Input: A trait reference -- Output: The principal of the contract implementing the trait - -## Why it matters - -The `contract-of` function is crucial for: - -1. Retrieving the principal (address) of a contract implementing a specific trait. -2. Enabling dynamic interactions with contracts based on traits. -3. Implementing contract-agnostic functions that work with any contract adhering to a specific interface. -4. Enhancing interoperability between contracts in a composable ecosystem. - -## When to use it - -Use the `contract-of` function when you need to: - -- Get the actual contract address from a trait reference. -- Perform operations that require the contract's principal, such as authorization checks. -- Implement functions that can work with multiple contracts implementing the same trait. -- Debug or log information about which contract is being interacted with. -- Manage routing logic between different versions of contracts for upgradeable smart contracts. -- Implement access control mechanisms to restrict function calls to designated contracts. - -## Best Practices - -- Use `contract-of` in combination with traits to create more flexible and composable smart contracts. -- Remember that `contract-of` returns a principal, which can be used in other Clarity functions expecting a contract address. -- Consider using `contract-of` when implementing proxy or router contracts that work with multiple similar contracts. -- Be aware that `contract-of` can only be used with trait references, not with direct contract references. - -## Practical Example: Modular Approach to Extension Contracts - -Let's implement a system where specific functions can only be called by designated extension contracts: - -### Define the Extension Trait - -First, define a trait for the extension contract: - -```clarity -(define-trait extension-trait - ( - (callback (principal (buff 34)) (response bool uint)) - ) -) -``` - -### Implement the Main Contract - -Next, implement the main contract with the `request-extension-callback` function: - -```clarity -(use-trait extensionTrait .extension-trait.extension-trait) -(define-map Extensions principal bool) - -(define-public (set-extension (extension principal) (enabled bool)) - (ok (map-set Extensions extension enabled)) -) - -(define-public (request-extension-callback (extension ) (memo (buff 34))) - (let - ( - (sender tx-sender) - ) - (asserts! (and (is-extension contract-caller) (is-eq contract-caller (contract-of extension))) (err u1)) - (as-contract (contract-call? extension callback sender memo)) - ) -) - -(define-read-only (is-extension (extension principal)) - (default-to false (map-get? Extensions extension)) -) -``` - -### Explanation - -1. **Define the Extension Trait**: The `extensionTrait` defines a `callback` function that the extension contract must implement. -2. **Data Map for Valid Extensions**: `Extensions` is a map that stores the status (enabled/disabled) of extension contracts. -3. **Public Function `set-extension`**: This function allows adding or removing an extension contract from the `Extensions` map. -4. **Public Function `request-extension-callback`**: This function: - - Retrieves the principal of the extension contract using `contract-of`. - - Asserts that the caller is a valid extension and matches the extension principal. - - Calls the `callback` function on the extension contract using `contract-call?`. -5. **Read-Only Function `is-extension`**: This function checks if a given contract principal is in the `Extensions` map and is enabled. - -### Usage - -1. **Set an Extension**: - ```clarity - (set-extension 'SP2J4ZQ6ZQ6ZQ6ZQ6ZQ6ZQ6ZQ6ZQ6ZQ6ZQ6ZQ6ZQ6 true) - ``` - -2. **Request Extension Callback**: - ```clarity - (request-extension-callback .extension-contract (buff 34 "example memo")) - ``` - -This example demonstrates: -1. Using `contract-of` to get the principal of the extension contract implementing the extension trait. -2. Implementing a read-only function to check if the caller is a valid extension. -3. Restricting access to certain functions based on the authorized extension contracts. -4. Allowing the authorized extension contracts to call specific functions. - -## Common Pitfalls - -1. Attempting to use `contract-of` with a direct contract reference instead of a trait reference. -2. Forgetting that `contract-of` returns a principal, not a contract reference itself. -3. Not handling potential errors when working with trait references that might not be properly initialized. - -## Related Functions - -- `use-trait`: Used to define trait references that can be used with `contract-of`. -- `contract-call?`: Often used in combination with `contract-of` to call functions on the retrieved contract. -- `is-eq`: Can be used to compare the returned principal with known contract addresses. - -## Conclusion - -The `contract-of` function is a powerful tool for creating flexible and interoperable smart contracts in Clarity. By allowing contracts to dynamically retrieve the principal of trait-implementing contracts, this function enables the creation of more generic and reusable code. When used effectively, `contract-of` can significantly enhance the composability and modularity of your smart contract ecosystem, especially in scenarios like access control management where restricting function calls to designated contracts is essential. diff --git a/content/docs/stacks/clarity/functions/default-to.mdx b/content/docs/stacks/clarity/functions/default-to.mdx deleted file mode 100644 index 377590f0e..000000000 --- a/content/docs/stacks/clarity/functions/default-to.mdx +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: default-to -description: Provide a default value for optional types in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(default-to default-value option-value) -``` - -- Input: - - `default-value`: A value of type A - - `option-value`: An optional value of type (optional A) -- Output: A value of type A - -## Why it matters - -The `default-to` function is crucial for: - -1. Safely handling optional values in smart contracts. -2. Providing fallback values when dealing with potentially missing data. -3. Simplifying code that works with map lookups or other operations that may return `none`. -4. Improving readability by reducing nested conditionals for optional handling. - -## When to use it - -Use the `default-to` function when you need to: - -- Provide a default value for a map lookup that might return `none`. -- Handle optional function parameters or return values. -- Set a fallback value for potentially missing data in your contract logic. -- Simplify error handling for operations that might not return a value. - -## Best Practices - -- Choose meaningful default values that make sense in the context of your contract logic. -- Use `default-to` to make your code more concise and readable when dealing with optionals. -- Consider the implications of using the default value in your contract's logic. -- Combine `default-to` with other Clarity functions like `map-get?` for efficient data handling. - -## Practical Example: User Profile Lookup - -Let's implement a function that retrieves a user's profile information with default values: - -```clarity -(define-map UserProfiles principal { name: (string-ascii 50), age: uint }) - -(define-read-only (get-user-profile (user principal)) - (let - ( - (profile (map-get? UserProfiles user)) - ) - { - name: (default-to "Anonymous" (get name profile)), - age: (default-to u0 (get age profile)) - } - ) -) - -;; Usage -(map-set UserProfiles tx-sender { name: "Alice", age: u30 }) -(get-user-profile tx-sender) ;; Returns { name: "Alice", age: u30 } -(get-user-profile 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5) ;; Returns { name: "Anonymous", age: u0 } -``` - -This example demonstrates: -1. Using `default-to` with `map-get?` to handle potentially missing user profiles. -2. Providing default values for individual fields within the profile. -3. Creating a safe way to retrieve user information without explicit null checks. - -## Common Pitfalls - -1. Forgetting that `default-to` only works with optional types, not with general error handling. -2. Using default values that might be indistinguishable from valid data, leading to confusion. -3. Overusing `default-to` where explicit error handling might be more appropriate. - -## Related Functions - -- `map-get?`: Often used in combination with `default-to` for safe map lookups. -- `get`: Can return optional values that are then handled by `default-to`. -- `some`: Used to create optional values that can be handled by `default-to`. - -## Conclusion - -The `default-to` function is a powerful tool for handling optional values in Clarity smart contracts. By providing a clean way to specify fallback values, this function enhances code readability and safety when dealing with potentially missing data. When used judiciously, `default-to` can significantly simplify your contract logic and make it more robust against unexpected inputs or states. diff --git a/content/docs/stacks/clarity/functions/define-constant.mdx b/content/docs/stacks/clarity/functions/define-constant.mdx deleted file mode 100644 index 63e475945..000000000 --- a/content/docs/stacks/clarity/functions/define-constant.mdx +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: define-constant -description: Define immutable constants in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(define-constant name expression) -``` - -- Input: - - `name`: The name of the constant - - `expression`: The value to be assigned to the constant -- Output: Not applicable (definition statement) - -## Why it matters - -The `define-constant` function is crucial for: - -1. Declaring immutable values that can be reused throughout the contract. -2. Improving code readability by giving meaningful names to fixed values. -3. Optimizing gas costs by avoiding repeated computations of fixed values. -4. Ensuring certain values remain unchanged throughout the contract's lifecycle. - -## When to use it - -Use `define-constant` when you need to: - -- Define fixed values that won't change during contract execution. -- Create named constants for magic numbers or frequently used values. -- Declare contract-wide configuration parameters. -- Optimize gas usage for values that are computed but never change. - -## Best Practices - -- Use uppercase names for constants to distinguish them from variables. -- Place constant definitions at the top of your contract for better visibility. -- Use constants for values that are used multiple times in your contract. -- Consider using constants for contract configuration that might need to change between deployments. - -## Practical Example: Token Configuration - -Let's implement a simple token contract using constants for configuration: - -```clarity -(define-constant TOKEN_NAME "DOG-GO-TO-THE-MOON") -(define-constant TOKEN_SYMBOL "DOG") -(define-constant TOKEN_DECIMALS u6) -(define-constant TOKEN_SUPPLY u1000000000000) ;; 1 million tokens with 6 decimals - -(define-fungible-token DOG-GO-TO-THE-MOON TOKEN_SUPPLY) - -(define-read-only (get-name) - TOKEN_NAME -) - -(define-read-only (get-symbol) - TOKEN_SYMBOL -) - -(define-read-only (get-decimals) - TOKEN_DECIMALS -) - -(define-read-only (get-balance (who principal)) - (ok (ft-get-balance DOG-GO-TO-THE-MOON who)) -) -``` - -This example demonstrates: -1. Using `define-constant` to set up token configuration parameters. -2. Referencing these constants in various parts of the contract. -3. Improving readability and maintainability of the contract. - -## Common Pitfalls - -1. Attempting to modify a constant after it's defined, which is not allowed. -2. Using `define-constant` for values that need to change during contract execution (use `define-data-var` instead). -3. Overusing constants for values used only once, which can decrease readability. - -## Related Functions - -- `define-data-var`: Used for defining mutable variables. -- `define-map`: Used for defining data maps. -- `var-get`: Used to retrieve the value of a data variable (not needed for constants). - -## Conclusion - -The `define-constant` function is a powerful tool for creating immutable, named values in Clarity smart contracts. By using constants effectively, you can improve code readability, optimize gas usage, and ensure certain values remain fixed throughout your contract's lifecycle. When designing your contract, consider which values should be constants and which might need to be mutable variables. diff --git a/content/docs/stacks/clarity/functions/define-data-var.mdx b/content/docs/stacks/clarity/functions/define-data-var.mdx deleted file mode 100644 index 63b330ee5..000000000 --- a/content/docs/stacks/clarity/functions/define-data-var.mdx +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: define-data-var -description: Define mutable variables in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(define-data-var name type value) -``` - -- Input: - - `name`: The name of the variable - - `type`: The type of the variable - - `value`: The initial value of the variable -- Output: Not applicable (definition statement) - -## Why it matters - -The `define-data-var` function is crucial for: - -1. Creating mutable state variables that can be updated throughout the contract's lifecycle. -2. Storing and managing changeable data within the smart contract. -3. Implementing counters, flags, or other dynamic values that need to be modified. -4. Maintaining contract-wide state that can be accessed and modified by multiple functions. - -## When to use it - -Use `define-data-var` when you need to: - -- Create a variable that will change its value during contract execution. -- Implement a counter or accumulator that needs to be updated. -- Store temporary or intermediate state that may be modified by contract functions. -- Maintain configurable parameters that can be updated by authorized parties. - -## Best Practices - -- Use `define-data-var` for values that need to change; for immutable values, use `define-constant` instead. -- Initialize variables with meaningful default values. -- Consider access control for functions that modify important data variables. -- Use clear and descriptive names for your variables to enhance readability. - -## Practical Example: Simple Counter - -Let's implement a basic counter using `define-data-var`: - -```clarity -(define-data-var counter uint u0) - -(define-public (increment) - (begin - (var-set counter (+ (var-get counter) u1)) - (ok (var-get counter)) - ) -) - -(define-public (decrement) - (begin - (asserts! (> (var-get counter) u0) (err u"Counter cannot be negative")) - (var-set counter (- (var-get counter) u1)) - (ok (var-get counter)) - ) -) - -(define-read-only (get-counter) - (ok (var-get counter)) -) -``` - -This example demonstrates: -1. Using `define-data-var` to create a mutable counter. -2. Implementing functions to increment and decrement the counter. -3. Using `var-get` and `var-set` to read and modify the variable's value. -4. Adding a safety check to prevent the counter from becoming negative. - -## Common Pitfalls - -1. Forgetting that `define-data-var` creates mutable state, which can lead to unexpected behavior if not managed carefully. -2. Not considering the initial value's impact on contract logic, especially if the contract relies on the variable's state. -3. Overusing mutable variables when constants or maps might be more appropriate for the use case. - -## Related Functions - -- `var-get`: Used to retrieve the current value of a data variable. -- `var-set`: Used to update the value of a data variable. -- `define-constant`: Used for defining immutable values. -- `define-map`: Used for defining key-value stores when more complex data structures are needed. - -## Conclusion - -The `define-data-var` function is essential for creating mutable state in Clarity smart contracts. It allows you to implement dynamic behavior and maintain changeable data throughout your contract's lifecycle. When used judiciously, data variables can greatly enhance the functionality and flexibility of smart contracts. However, you should be mindful of the implications of mutable state and ensure proper access control and error handling when modifying these variables. diff --git a/content/docs/stacks/clarity/functions/define-fungible-token.mdx b/content/docs/stacks/clarity/functions/define-fungible-token.mdx deleted file mode 100644 index fed47037b..000000000 --- a/content/docs/stacks/clarity/functions/define-fungible-token.mdx +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: define-fungible-token -description: Define a new fungible token in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(define-fungible-token token-name ) -``` - -- Input: - - `token-name`: The name of the fungible token - - ``: (Optional) An unsigned integer representing the total supply of tokens -- Output: Not applicable (definition statement) - -## Why it matters - -The `define-fungible-token` function is crucial for: - -1. Creating new fungible tokens within a smart contract. -2. Establishing a token economy or system within your dApp. -3. Implementing custom tokens with specific supply constraints. -4. Enabling token-related operations like minting, transferring, and burning. - -## When to use it - -Use `define-fungible-token` when you need to: - -- Create a new fungible token for your smart contract or dApp. -- Implement a token with a fixed total supply. -- Establish a foundation for token-based features in your contract. -- Create utility tokens, governance tokens, or other custom fungible assets. - -## Best Practices - -- Place `define-fungible-token` at the top level of your contract, as it's a definition statement. -- Consider carefully whether to specify a total supply or leave it unlimited. -- Use meaningful and descriptive names for your tokens. -- Implement proper access controls for minting and burning operations if required. - -## Practical Example: Simple Token Creation - -Let's implement a basic fungible token with a fixed supply: - -```clarity -(define-fungible-token DOG-GO-TO-THE-MOON u1000000) - -(define-data-var tokenAdmin principal tx-sender) - -(define-public (transfer (amount uint) (sender principal) (recipient principal)) - (begin - (asserts! (is-eq tx-sender sender) (err u1)) - (ft-transfer? DOG-GO-TO-THE-MOON amount sender recipient) - ) -) - -(define-read-only (get-balance (account principal)) - (ok (ft-get-balance DOG-GO-TO-THE-MOON account)) -) - -(define-public (mint (amount uint) (recipient principal)) - (begin - (asserts! (is-eq tx-sender (var-get tokenAdmin)) (err u3)) - (ft-mint? DOG-GO-TO-THE-MOON amount recipient) - ) -) -``` - -This example demonstrates: -1. Using `define-fungible-token` to create a new token with a fixed supply of 1,000,000. -2. Implementing basic token operations like transfer and balance checking. -3. Adding a mint function with admin-only access control. - -## Common Pitfalls - -1. Forgetting that omitting the total supply parameter allows unlimited minting, if not handled manually. -2. Not implementing proper access controls for sensitive operations like minting. -3. Overlooking the need for additional functionality like burning or pausing. - -## Related Functions - -- `ft-transfer?`: Used to transfer tokens between principals. -- `ft-mint?`: Used to create new tokens (if allowed by the token definition). -- `ft-burn?`: Used to destroy tokens, reducing the circulating supply. -- `ft-get-balance`: Used to check the token balance of a principal. -- `ft-get-supply`: Used to get the current total supply of tokens. - -## Conclusion - -The `define-fungible-token` function is a fundamental building block for creating token-based systems in Clarity smart contracts. It allows you to define custom fungible tokens with or without supply constraints. When combined with other token-related functions, it enables the implementation of sophisticated token economies and financial instruments on the Stacks blockchain. diff --git a/content/docs/stacks/clarity/functions/define-map.mdx b/content/docs/stacks/clarity/functions/define-map.mdx deleted file mode 100644 index 33eca19c2..000000000 --- a/content/docs/stacks/clarity/functions/define-map.mdx +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: define-map -description: Define a data map in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(define-map map-name key-type value-type) -``` - -- Input: - - `map-name`: The name of the map - - `key-type`: The type of the map's keys - - `value-type`: The type of the map's values -- Output: Not applicable (definition statement) - -## Why it matters - -The `define-map` function is crucial for: - -1. Creating key-value stores within smart contracts. -2. Efficiently organizing and accessing structured data. -3. Implementing complex data structures like mappings or dictionaries. -4. Storing and retrieving contract-specific data associated with unique keys. - -## When to use it - -Use `define-map` when you need to: - -- Store and retrieve data associated with unique keys. -- Implement lookup tables or dictionaries in your contract. -- Organize data that needs to be accessed by a specific identifier. -- Create data structures that can be efficiently updated and queried. - -## Best Practices - -- Choose appropriate types for keys and values to ensure efficient storage and retrieval. -- Use meaningful names for your maps that reflect their purpose in the contract. -- Consider using composite keys (tuples) for more complex data relationships. -- Be mindful of the gas costs associated with map operations, especially for large datasets. - -## Practical Example: Simple User Profile System - -Let's implement a basic user profile system using `define-map`: - -```clarity -(define-map UserProfiles principal { name: (string-ascii 50), age: uint, isActive: bool }) - -(define-public (set-profile (name (string-ascii 50)) (age uint)) - (ok (map-set UserProfiles tx-sender { name: name, age: age, isActive: true })) -) - -(define-read-only (get-profile (user principal)) - (default-to { name: "", age: u0, isActive: false } (map-get? UserProfiles user)) -) - -(define-public (deactivate-profile) - (match (map-get? UserProfiles tx-sender) profile - (ok (map-set UserProfiles tx-sender (merge profile { isActive: false }))) - (err u404) - ) -) - -;; Usage -(set-profile "Ryan" u38) -(get-profile tx-sender) -(deactivate-profile) -``` - -This example demonstrates: -1. Using `define-map` to create a user profile storage system. -2. Implementing functions to set, get, and update profile data. -3. Using map operations like `map-set`, `map-get?`, and `merge` to manipulate map data. -4. Handling cases where a profile might not exist using `default-to`. - -## Common Pitfalls - -1. Forgetting that maps are not iterable in Clarity; you can't loop through all entries. -2. Not handling cases where a key might not exist in the map. -3. Overusing maps for data that might be better suited for other data structures. -4. Not considering the gas costs of map operations in complex contracts. - -## Related Functions - -- `map-get?`: Used to retrieve a value from a map, returns an optional. -- `map-set`: Used to set or update a value in a map. -- `map-delete`: Used to remove a key-value pair from a map. -- `map-insert`: Used to insert a new key-value pair only if the key doesn't already exist. -- `merge`: Used to merge two maps, combining their key-value pairs. - -## Conclusion - -The `define-map` function is a powerful tool for creating structured data storage in Clarity smart contracts. It allows you to implement efficient key-value stores, enabling complex data relationships and lookups. When used effectively, maps can significantly enhance the functionality and organization of data within your smart contracts. diff --git a/content/docs/stacks/clarity/functions/define-non-fungible-token.mdx b/content/docs/stacks/clarity/functions/define-non-fungible-token.mdx deleted file mode 100644 index 83c64bed2..000000000 --- a/content/docs/stacks/clarity/functions/define-non-fungible-token.mdx +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: define-non-fungible-token -description: Define a new non-fungible token class in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(define-non-fungible-token asset-name asset-identifier-type) -``` - -- Input: - - `asset-name`: The name of the non-fungible token class - - `asset-identifier-type`: The type of the unique identifier for each token -- Output: Not applicable (definition statement) - -## Why it matters - -The `define-non-fungible-token` function is crucial for: - -1. Creating new non-fungible token (NFT) classes within a smart contract. -2. Establishing unique digital assets with individual identifiers. -3. Implementing collectibles, digital art, or other unique token-based systems. -4. Enabling NFT-related operations like minting, transferring, and ownership checks. - -## When to use it - -Use `define-non-fungible-token` when you need to: - -- Create a new NFT class for your smart contract or dApp. -- Implement unique digital assets with distinct identifiers. -- Establish a foundation for NFT-based features in your contract. -- Create collectibles, digital art tokens, or other unique digital assets. - -## Best Practices - -- Place `define-non-fungible-token` at the top level of your contract, as it's a definition statement. -- Choose an appropriate asset identifier type that ensures uniqueness for each token. -- Use meaningful and descriptive names for your NFT classes. -- Consider the scalability and gas costs associated with your chosen identifier type. - -## Practical Example: Simple Digital Art NFT - -Let's implement a basic digital art NFT system: - -```clarity -(define-non-fungible-token SharkoBarko uint) - -(define-data-var index uint u0) - -(define-public (mint (who principal) (artwork-uri (string-utf8 256))) - (let - ( - (tokenId (var-get index)) - ) - (try! (nft-mint? SharkoBarko tokenId who)) - (var-set index (+ tokenId u1)) - (ok tokenId) - ) -) - -(define-read-only (get-owner (tokenId uint)) - (ok (nft-get-owner? SharkoBarko tokenId)) -) - -(define-public (transfer (tokenId uint) (sender principal) (recipient principal)) - (begin - (asserts! (is-eq tx-sender sender) (err u403)) - (nft-transfer? SharkoBarko tokenId sender recipient) - ) -) -``` - -This example demonstrates: -1. Using `define-non-fungible-token` to create a new NFT class for digital artwork. -2. Implementing basic NFT operations like minting, checking ownership, and transferring. -3. Using a simple incrementing integer as the token identifier. - -## Common Pitfalls - -1. Forgetting that each token in an NFT class must have a unique identifier. -2. Not implementing proper access controls for minting and transferring operations. -3. Choosing an identifier type that may lead to collisions or scalability issues. - -## Related Functions - -- `nft-mint?`: Used to create new tokens within the NFT class. -- `nft-transfer?`: Used to transfer ownership of an NFT. -- `nft-get-owner?`: Used to check the current owner of an NFT. -- `nft-burn?`: Used to destroy an existing NFT. - -## Conclusion - -The `define-non-fungible-token` function is a fundamental building block for creating NFT-based systems in Clarity smart contracts. It allows you to define custom non-fungible token classes with unique identifiers. When combined with other NFT-related functions, it enables the implementation of sophisticated systems for digital collectibles, art, and other unique digital assets on the Stacks blockchain. diff --git a/content/docs/stacks/clarity/functions/define-private.mdx b/content/docs/stacks/clarity/functions/define-private.mdx deleted file mode 100644 index b130fcabc..000000000 --- a/content/docs/stacks/clarity/functions/define-private.mdx +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: define-private -description: Define private functions in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(define-private (function-name (arg-name-0 arg-type-0) ...) function-body) -``` - -- Input: - - `function-name`: The name of the private function - - `arg-name-N`: The name of each argument - - `arg-type-N`: The type of each argument - - `function-body`: The code to be executed when the function is called -- Output: Not applicable (definition statement) - -## Why it matters - -The `define-private` function is crucial for: - -1. Creating internal helper functions that are only accessible within the contract. -2. Encapsulating logic that shouldn't be directly callable from outside the contract. -3. Improving code organization and reusability within a contract. -4. Implementing complex operations that are used by multiple public functions. - -## When to use it - -Use `define-private` when you need to: - -- Create utility functions that are used by multiple public functions. -- Implement complex logic that needs to be hidden from external callers. -- Break down large functions into smaller, more manageable pieces. -- Improve the readability and maintainability of your contract. - -## Best Practices - -- Use descriptive names for private functions to clearly indicate their purpose. -- Keep private functions focused on a single task or operation. -- Use private functions to avoid code duplication within your contract. -- Remember that private functions can return any type, not just response types. - -## Practical Example: Helper Function for Validation - -Let's implement a private function for input validation: - -```clarity -(define-private (validate-amount (amount uint)) - (and (> amount u0) (<= amount u1000000)) -) - -(define-public (transfer (recipient principal) (amount uint)) - (if (validate-amount amount) - (begin - ;; Perform transfer logic here - (ok true) - ) - (err u1) - ) -) -``` - -This example demonstrates: -1. Using `define-private` to create a helper function for input validation. -2. Calling the private function from within a public function. -3. Improving code readability by separating validation logic. - -## Common Pitfalls - -1. Attempting to call private functions from outside the contract, which is not allowed. -2. Overusing private functions, leading to overly complex contract structure. -3. Forgetting that private functions can modify contract state, which may lead to unexpected behavior if not carefully managed. - -## Related Functions - -- `define-public`: Used to define public functions that can be called from outside the contract. -- `define-read-only`: Used to define public read-only functions that don't modify contract state. - -## Conclusion - -The `define-private` function is a powerful tool for creating internal helper functions and encapsulating logic within Clarity smart contracts. By using private functions effectively, you can improve code organization, reduce duplication, and create more maintainable and secure smart contracts. diff --git a/content/docs/stacks/clarity/functions/define-public.mdx b/content/docs/stacks/clarity/functions/define-public.mdx deleted file mode 100644 index 0be045687..000000000 --- a/content/docs/stacks/clarity/functions/define-public.mdx +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: define-public -description: Define public functions in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(define-public (function-name (arg-name-0 arg-type-0) ...) function-body) -``` - -- Input: - - `function-name`: The name of the public function - - `arg-name-N`: The name of each argument - - `arg-type-N`: The type of each argument - - `function-body`: The code to be executed when the function is called -- Output: A ResponseType (using `ok` or `err`) - -## Why it matters - -The `define-public` function is crucial for: - -1. Creating functions that can be called from outside the contract. -2. Enabling interaction with the contract through transactions. -3. Implementing the main entry points for contract functionality. -4. Allowing other contracts to call this contract's functions. - -## When to use it - -Use `define-public` when you need to: - -- Create functions that users can directly interact with. -- Implement core contract functionality that should be accessible externally. -- Define functions that other contracts can call via `contract-call?`. -- Create functions that modify contract state and need to be invoked through transactions. - -## Best Practices - -- Always return a response type (`(response T E)`) from public functions. -- Use descriptive names for public functions to clearly indicate their purpose. -- Implement proper access control for sensitive operations. -- Handle potential errors and edge cases within the function. -- Consider gas costs when designing public functions. - -## Practical Examples - -### Example 1: Simple Counter - -Let's implement a simple counter that can be incremented by users: - -```clarity -(define-data-var counter int 0) - -(define-public (increment-counter) - (begin - (var-set counter (+ (var-get counter) 1)) - (ok (var-get counter)) - ) -) -``` - -This example demonstrates: -1. Using `define-public` to create a function that can be called externally. -2. Incrementing a counter and returning the new value. -3. Returning a response type to indicate success. - -### Example 2: Setting a Value - -Let's implement a function that sets a value if it meets certain conditions: - -```clarity -(define-data-var storedValue uint u0) - -(define-public (set-value (value uint)) - (if (> value u0) - (begin - (var-set storedValue value) - (ok value) - ) - (err u1) - ) -) -``` - -This example demonstrates: -1. Using `define-public` to create a function that can be called externally. -2. Setting a value only if it meets a condition. -3. Returning a response type to indicate success or failure. - -## Common Pitfalls - -1. Forgetting to return a response type, which will cause a contract to be invalid. -2. Not implementing proper access controls, potentially allowing unauthorized actions. -3. Overlooking potential error conditions or edge cases. -4. Creating functions that are too complex or gas-intensive for practical use. - -## Related Functions - -- `define-private`: Used to define private functions that can only be called within the contract. -- `define-read-only`: Used to define public read-only functions that don't modify contract state. -- `contract-call?`: Used by other contracts to call public functions defined with `define-public`. - -## Conclusion - -The `define-public` function is a fundamental building block for creating interactive and composable smart contracts in Clarity. By defining public functions, you can create contracts that users and other contracts can interact with, enabling complex decentralized applications. However, it's crucial to design these functions with security, efficiency, and usability in mind. diff --git a/content/docs/stacks/clarity/functions/define-read-only.mdx b/content/docs/stacks/clarity/functions/define-read-only.mdx deleted file mode 100644 index 120d3063a..000000000 --- a/content/docs/stacks/clarity/functions/define-read-only.mdx +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: define-read-only -description: Define public read-only functions in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(define-read-only (function-name (arg-name-0 arg-type-0) ...) function-body) -``` - -- Input: - - `function-name`: The name of the read-only function - - `arg-name-N`: The name of each argument - - `arg-type-N`: The type of each argument - - `function-body`: The code to be executed when the function is called -- Output: Not applicable (definition statement) - -## Why it matters - -The `define-read-only` function is crucial for: - -1. Creating public functions that can query contract state without modifying it. -2. Enabling efficient and gas-optimized read operations on the contract. -3. Implementing view functions that other contracts or off-chain applications can call. -4. Providing a safe way to expose contract data without risking state changes. - -## When to use it - -Use `define-read-only` when you need to: - -- Create functions that return contract state or computed values. -- Implement getter functions for contract variables or complex data structures. -- Provide public interfaces for querying contract data without modifying state. -- Create helper functions that other contracts can call without incurring state change costs. - -## Best Practices - -- Use descriptive names for read-only functions to clearly indicate their purpose. -- Ensure that read-only functions do not attempt to modify contract state. -- Utilize read-only functions for complex calculations that don't require state changes. -- Consider using read-only functions in combination with public functions to separate read and write operations. - -## Practical Example: Token Balance Checker - -Let's implement a read-only function for checking token balances: - -```clarity -(define-map Balances principal uint) - -(define-read-only (get-balance (account principal)) - (default-to u0 (map-get? Balances account)) -) -``` - -This example demonstrates: -1. Using `define-read-only` to create functions for querying token balances. -2. Implementing a getter function for individual account balances. - -## Common Pitfalls - -1. Attempting to modify contract state within a read-only function, which will cause an error. -2. Overusing read-only functions for complex calculations that might be better suited for off-chain computation. -3. Forgetting that read-only functions can still consume gas when called, even though they don't modify state. - -## Related Functions - -- `define-public`: Used to define public functions that can modify contract state. -- `define-private`: Used to define private functions that can only be called within the contract. -- `map-get?`: Often used within read-only functions to retrieve data from maps. - -## Conclusion - -The `define-read-only` function is an essential tool for creating efficient and safe query interfaces in Clarity smart contracts. By providing a way to expose contract data and perform calculations without modifying state, read-only functions enable you to create more transparent and gas-efficient contracts. When used effectively, this function can significantly enhance the usability and accessibility of smart contract data for both on-chain and off-chain applications. diff --git a/content/docs/stacks/clarity/functions/define-trait.mdx b/content/docs/stacks/clarity/functions/define-trait.mdx deleted file mode 100644 index 6fa0a4226..000000000 --- a/content/docs/stacks/clarity/functions/define-trait.mdx +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: define-trait -description: Define traits for interface-like behavior in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(define-trait trait-name ((func1-name (arg1-type arg2-type ...) (return-type)) ...)) -``` - -- Input: - - `trait-name`: The name of the trait being defined - - `func1-name`: The name of a function in the trait - - `arg1-type, arg2-type, ...`: The types of the function's arguments - - `return-type`: The return type of the function -- Output: Not applicable (definition statement) - -## Why it matters - -The `define-trait` function is crucial for: - -1. Creating standardized interfaces for contracts to implement. -2. Enabling polymorphic behavior in smart contract interactions. -3. Facilitating contract composability and interoperability. -4. Allowing for dynamic dispatch of contract calls based on traits. - -## When to use it - -Use `define-trait` when you need to: - -- Define a common interface that multiple contracts should adhere to. -- Create a contract that can interact with any other contract implementing a specific trait. -- Establish standards for token contracts or other common smart contract patterns. -- Enable more flexible and modular smart contract architectures. - -## Best Practices - -- Use clear and descriptive names for traits and their functions. -- Keep traits focused on a single responsibility or concept. -- Consider creating traits for common patterns like token standards. -- Use traits in combination with `use-trait` and `contract-call?` for dynamic contract interactions. - -## Practical Example: Token Trait - -Let's define a simple trait for a token contract: - -```clarity -(define-trait token-trait - ( - (transfer? (principal principal uint) (response bool uint)) - (get-balance (principal) (response uint uint)) - (get-token-uri () (response (optional (string-utf8 256)) uint)) - ) -) -``` - -This example demonstrates: -1. Defining a trait with multiple functions. -2. Specifying function signatures with argument types and return types. -3. Using response types to handle success and failure cases. - -## Common Pitfalls - -1. Defining overly complex traits that are difficult for other contracts to implement. -2. Forgetting that traits are not implementations, just interface definitions. -3. Not considering backwards compatibility when updating traits in newer contract versions. - -## Related Functions - -- `use-trait`: Used to import trait definitions from other contracts. -- `impl-trait`: Used to declare that a contract implements a specific trait. -- `contract-call?`: Often used in combination with traits for dynamic contract calls. -- `contract-of`: Used to get the principal of a contract implementing a trait. - -## Conclusion - -The `define-trait` function is a powerful tool for creating standardized interfaces in Clarity smart contracts. By defining traits, you can create more modular, interoperable, and flexible smart contract ecosystems. Traits enable contracts to interact with each other in a predictable way, fostering the development of complex decentralized applications and standards within the Stacks ecosystem. diff --git a/content/docs/stacks/clarity/functions/divide.mdx b/content/docs/stacks/clarity/functions/divide.mdx deleted file mode 100644 index 080243bb8..000000000 --- a/content/docs/stacks/clarity/functions/divide.mdx +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: divide -description: Use the division function for arithmetic operations in Clarity smart contracts. ---- - -The division function (`/`) in Clarity performs integer division on a variable number of integer inputs. It's a fundamental arithmetic operation used in many smart contract calculations. - -## Function Signature - -```clarity -(/ i1 i2...) -``` - -- Input: Two or more integers (int or uint) -- Output: A single integer (int or uint) - -## Why it matters - -The division function is crucial for: - -1. Performing basic arithmetic calculations within smart contracts. -2. Calculating rates, percentages, or proportions. -3. Distributing resources or tokens evenly. -4. Implementing mathematical formulas that involve division. - -## When to use it - -Use the division function when you need to: - -- Perform basic division in your contract logic. -- Calculate rates or percentages. -- Distribute resources evenly among participants. -- Implement mathematical formulas that involve division. - -## Best Practices - -- Always consider the possibility of division by zero, which throws a runtime error. -- Be aware that Clarity uses integer division, so results are always rounded down. -- Use appropriate types (int or uint) based on your needs and expected value ranges. -- Consider using multiplication by fractions instead of division for more precise calculations. - -## Practical Example: Token Distribution Contract - -Let's implement a simple token distribution contract that uses division to allocate tokens evenly: - -```clarity -;; Define constants -(define-constant TOTAL_TOKENS u1000000) -(define-constant DISTRIBUTION_ROUNDS u10) - -;; Define data variables -(define-map ParticipantShares principal uint) -(define-data-var currentRound uint u0) -(define-data-var participantsCount uint u0) - -;; Function to register as a participant -(define-public (register-participant) - (let - ( - (currentParticipants (var-get participantsCount)) - ) - (asserts! (< currentParticipants DISTRIBUTION_ROUNDS) (err u1)) - (map-set ParticipantShares tx-sender u0) - (var-set participantsCount (+ currentParticipants u1)) - (ok true) - ) -) - -;; Function to distribute tokens -(define-public (distribute-tokens) - (let - ( - (currentParticipants (var-get participantsCount)) - (tokensPerParticipant (/ TOTAL_TOKENS currentParticipants)) - ) - (asserts! (> currentParticipants u0) (err u2)) - (asserts! (< (var-get currentRound) DISTRIBUTION_ROUNDS) (err u3)) - (map-set ParticipantShares tx-sender tokensPerParticipant) - (var-set currentRound (+ (var-get currentRound) u1)) - (ok tokensPerParticipant) - ) -) - -;; Function to check participant's share -(define-read-only (get-participant-share (participant principal)) - (default-to u0 (map-get? ParticipantShares participant)) -) -``` - -This example demonstrates: -1. Using division to calculate the number of tokens each participant should receive. -2. Handling potential division by zero by checking the number of participants. -3. Using integer division to evenly distribute tokens among participants. - -## Common Pitfalls - -1. Forgetting to handle division by zero, which causes a runtime error. -2. Not accounting for integer division rounding down, which can lead to unexpected results. -3. Dividing before multiplying in complex calculations, potentially losing precision. - -## Related Functions - -- `*`: Used for multiplication operations. -- `+`: Used for addition operations. -- `-`: Used for subtraction operations. - -## Conclusion - -The division function is a fundamental tool for performing arithmetic operations in Clarity smart contracts. By understanding its behavior with integer division and potential edge cases, you can use it effectively to implement various mathematical operations in their contracts, from simple divisions to more complex token distribution algorithms. diff --git a/content/docs/stacks/clarity/functions/element-at.mdx b/content/docs/stacks/clarity/functions/element-at.mdx deleted file mode 100644 index 9d676be64..000000000 --- a/content/docs/stacks/clarity/functions/element-at.mdx +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: element-at? -description: Retrieve an element from a list at a specific index in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(element-at? list-expr uint) -``` - -- Input: - - `list-expr`: A list expression - - `uint`: An unsigned integer representing the index -- Output: `(optional A)` where A is the type of elements in the list - -## Why it matters - -The `element-at?` function is crucial for: - -1. Safely accessing elements in a list at a specific index. -2. Handling potential out-of-bounds access without causing errors. -3. Implementing logic that depends on retrieving specific elements from lists. -4. Providing a way to work with lists in a more flexible manner. - -## When to use it - -Use `element-at?` when you need to: - -- Retrieve a specific element from a list by its position. -- Implement algorithms that require access to list elements by index. -- Safely handle potential out-of-bounds access in list operations. -- Work with lists in a way that may involve accessing elements at varying positions. - -## Best Practices - -- Always check the returned optional value to handle cases where the index is out of bounds. -- Use in combination with `len` to ensure you're not attempting to access beyond the list's length. -- Consider using `map` or `fold` for operations that need to process all elements instead of accessing by index. -- Be mindful of the zero-based indexing when using `element-at?`. - -## Practical Example: Retrieving a Specific Item - -Let's implement a function that retrieves an item from a todo list: - -```clarity -(define-data-var todoList (list 10 (string-ascii 50)) (list)) - -(define-public (add-todo (item (string-ascii 50))) - (let - ( - (currentList (var-get todoList)) - (newList (as-max-len? (append currentList item) u10)) - ) - (match newList - newListValue (ok (var-set todoList newListValue)) - (err u1) - ) - ) -) - -(define-read-only (get-todo (index uint)) - (match (element-at? (var-get todoList) index) item - (ok item) - (err u404) - ) -) - -;; Usage -(add-todo "Buy milk") -(add-todo "Walk the dog") -(get-todo u1) ;; Returns (ok "Walk the dog") -(get-todo u5) ;; Returns (err u404) -``` - -This example demonstrates: -1. Using `element-at?` to retrieve an item from a list stored in a data variable. -2. Handling the optional return value with `match` to provide meaningful responses. -3. Safely accessing list elements without risking out-of-bounds errors. - -## Common Pitfalls - -1. Forgetting that list indices are zero-based in Clarity. -2. Not handling the case where `element-at?` returns `none` for out-of-bounds access. -3. Using `element-at?` in a loop to process all elements, which is less efficient than using `map` or `fold`. - -## Related Functions - -- `list`: Used to create lists that can be accessed with `element-at?`. -- `len`: Often used in conjunction with `element-at?` to check list bounds. -- `map`: An alternative for processing all elements in a list. -- `fold`: Another alternative for reducing a list to a single value. - -## Clarity 1 Version: element-at - -In Clarity 1, this function was named `element-at` (without the question mark) and had a slightly different behavior: - -```clarity -(element-at list-expr uint) -``` - -The key differences are: -1. It returns the element directly, not wrapped in an optional. -2. It throws a runtime error if the index is out of bounds. - -When migrating from Clarity 1 to newer versions, replace `element-at` with `element-at?` and add appropriate error handling for out-of-bounds cases. - -## Conclusion - -The `element-at?` function is a safer and more flexible way to access list elements in Clarity smart contracts compared to its predecessor. By returning an optional value, this function allows you to handle out-of-bounds access gracefully, leading to more robust and error-resistant code. When working with lists in Clarity, `element-at?` is an essential tool for accessing specific elements while maintaining the integrity and safety of your contract operations. diff --git a/content/docs/stacks/clarity/functions/err.mdx b/content/docs/stacks/clarity/functions/err.mdx deleted file mode 100644 index 0b4828910..000000000 --- a/content/docs/stacks/clarity/functions/err.mdx +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: err -description: Construct error responses in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(err value) -``` - -- Input: `value` - Any type A -- Output: `(response A B)` where A is the type of the input value - -## Why it matters - -The `err` function is crucial for: - -1. Creating standardized error responses in public functions. -2. Indicating that a function execution has failed. -3. Providing meaningful error information to callers. -4. Triggering automatic rollback of any database changes during function execution. - -## When to use it - -Use `err` when you need to: - -- Return an error state from a public function. -- Indicate that a condition or operation has failed. -- Provide specific error information or codes to the caller. -- Ensure that any state changes are reverted due to a failure condition. - -## Best Practices - -- Use descriptive error values that help diagnose the issue. -- Consider using standardized error codes across your contract. -- Pair `err` with `ok` to create comprehensive response handling. -- Remember that returning an `err` will cause all state changes in the current function to be rolled back. - -## Practical Example: Token Transfer with Error Handling - -Let's implement a simple token transfer function with error handling: - -```clarity -(define-map Balances principal uint) - -(define-public (transfer (amount uint) (recipient principal)) - (let - ( - (senderBalance (default-to u0 (map-get? Balances tx-sender))) - ) - (if (>= senderBalance amount) - (begin - (map-set Balances tx-sender (- senderBalance amount)) - (map-set Balances recipient (+ (default-to u0 (map-get? Balances recipient)) amount)) - (ok true) - ) - (err u1) - ) - ) -) - -;; Usage -(transfer u100 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM) ;; Returns (err u1) if balance is insufficient -``` - -This example demonstrates: -1. Using `err` to return an error when the sender has insufficient balance. -2. Pairing `err` with `ok` to handle both success and failure cases. -3. Using a simple error code (u1) to indicate the type of error. - -## Common Pitfalls - -1. Forgetting that returning an `err` will revert all state changes in the current function. -2. Using non-descriptive error values that make debugging difficult. -3. Inconsistent error handling across different functions in the contract. - -## Related Functions - -- `ok`: Used to construct successful responses in public functions. -- `asserts!`: Often used with `err` for condition checking and error reporting. -- `try!`: Used to propagate errors up the call stack. - -## Conclusion - -The `err` function is a fundamental tool for error handling and response construction in Clarity smart contracts. By providing a standardized way to indicate and communicate errors, this function enables robust and predictable contract behavior. When used effectively in combination with `ok` and other error-handling mechanisms, `err` contributes to creating more reliable and maintainable smart contracts. diff --git a/content/docs/stacks/clarity/functions/filter.mdx b/content/docs/stacks/clarity/functions/filter.mdx deleted file mode 100644 index f045fb24c..000000000 --- a/content/docs/stacks/clarity/functions/filter.mdx +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: filter -description: Filter elements from a list based on a predicate function in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(filter ) -``` - -- Input: - - ``: A function that takes one argument and returns a boolean - - ``: A list, buffer, or string to iterate over -- Output: A new list containing only the elements for which the function returned true - -## Why it matters - -The `filter` function is crucial for: - -1. Selectively processing elements from a list based on specific criteria. -2. Removing unwanted elements from a list without modifying the original. -3. Implementing complex data filtering logic within smart contracts. -4. Enhancing data manipulation capabilities in list processing. - -## When to use it - -Use `filter` when you need to: - -- Create a subset of a list based on certain conditions. -- Remove elements from a list that don't meet specific criteria. -- Implement data validation or selection logic on lists. -- Prepare data for further processing by removing irrelevant elements. - -## Best Practices - -- Ensure the predicate function is efficient, especially for large lists. -- Use `filter` in combination with other list functions like `map` or `fold` for complex list operations. -- Be mindful of gas costs when filtering large lists. -- Consider using `filter` with `define-private` functions for reusable filtering logic. - -## Practical Example: Filtering Even Numbers - -Let's implement a function that filters even numbers from a list: - -```clarity -(define-private (is-even (num int)) - (is-eq (mod num 2) 0) -) - -(define-read-only (get-even-numbers (numbers (list 10 int))) - (filter is-even numbers) -) - -;; Usage -(get-even-numbers (list 1 2 3 4 5 6 7 8 9 10)) ;; Returns (2 4 6 8 10) -``` - -This example demonstrates: -1. Defining a private helper function `is-even` to check if a number is even. -2. Using `filter` with the `is-even` function to create a new list of even numbers. -3. Applying the filter operation to a list of integers. - -## Common Pitfalls - -1. Forgetting that `filter` creates a new list and does not modify the original. -2. Using a computationally expensive predicate function, which could lead to high gas costs. -3. Not considering the potential for an empty result list if no elements match the predicate. - -## Related Functions - -- `map`: Applies a function to each element in a list, transforming the elements. -- `fold`: Reduces a list to a single value by applying a function to each element. -- `len`: Can be used to check the length of the resulting filtered list. - -## Conclusion - -The `filter` function is a powerful tool for list manipulation in Clarity smart contracts. It allows you to create refined subsets of data based on specific criteria, enhancing the contract's ability to process and analyze list-based information. When used effectively, `filter` can significantly improve the efficiency and clarity of list operations in smart contracts. diff --git a/content/docs/stacks/clarity/functions/fold.mdx b/content/docs/stacks/clarity/functions/fold.mdx deleted file mode 100644 index 74bfeace8..000000000 --- a/content/docs/stacks/clarity/functions/fold.mdx +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: fold -description: Reduce a sequence to a single value in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(fold ) -``` - -- Input: - - ``: A function that takes two arguments and returns a single value - - ``: A list, buffer, or string to iterate over - - ``: The starting value for the accumulation -- Output: The final accumulated value - -## Why it matters - -The `fold` function is crucial for: - -1. Aggregating values from a sequence into a single result. -2. Performing complex computations on list elements. -3. Transforming data structures efficiently. -4. Implementing recursive-like operations without explicit recursion. - -## When to use it - -Use `fold` when you need to: - -- Calculate a sum, product, or other aggregate value from a list. -- Transform a list into a single value or different data structure. -- Apply a function to each element of a sequence while maintaining state. -- Implement algorithms that would typically require recursion. - -## Best Practices - -- Ensure the function passed to `fold` is commutative if the order of operations doesn't matter. -- Use meaningful initial values that make sense for your aggregation. -- Consider using `fold` instead of explicit loops for cleaner, more functional code. -- Be mindful of the performance implications when folding over large sequences. - -## Practical Example: Summing a List of Numbers - -Let's implement a function that sums all numbers in a list: - -```clarity -(define-read-only (sum-list (numbers (list 10 uint))) - (fold + numbers u0) -) - -;; Usage -(sum-list (list u1 u2 u3 u4 u5)) ;; Returns u15 -``` - -This example demonstrates: -1. Using `fold` with the built-in `+` function to sum numbers. -2. Starting with an initial value of `u0`. -3. Applying the operation to each element in the list. - -## Common Pitfalls - -1. Using an initial value of the wrong type or that doesn't make sense for the operation. -2. Forgetting that `fold` processes elements from left to right, which matters for non-commutative operations. -3. Overusing `fold` for operations that might be more clearly expressed with other functions like `map` or `filter`. - -## Related Functions - -- `map`: Applies a function to each element in a sequence, returning a new sequence. -- `filter`: Selects elements from a sequence based on a predicate function. -- `reduce`: Similar to `fold` in other languages, but Clarity uses `fold` for this operation. - -## Conclusion - -The `fold` function is a powerful tool for aggregating and transforming data in Clarity smart contracts. It allows you to express complex computations on sequences in a concise and functional manner. When used effectively, `fold` can simplify code, improve readability, and provide an efficient way to process collections of data within smart contracts. diff --git a/content/docs/stacks/clarity/functions/from-consensus-buff.mdx b/content/docs/stacks/clarity/functions/from-consensus-buff.mdx deleted file mode 100644 index cd39bedc6..000000000 --- a/content/docs/stacks/clarity/functions/from-consensus-buff.mdx +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: from-consensus-buff? -description: Deserialize a buffer into a Clarity value in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(from-consensus-buff? type-signature buffer) -``` - -- Input: - - `type-signature`: The type to deserialize into - - `buffer`: A buffer containing the serialized data -- Output: `(optional t)` where t is the type specified in the type signature - -## Why it matters - -The `from-consensus-buff?` function is crucial for: - -1. Deserializing data that has been serialized using the SIP-005 standard. -2. Enabling interoperability between different contracts or systems. -3. Handling complex data structures that have been serialized for storage or transmission. -4. Safely converting buffers back into Clarity values with type checking. - -## When to use it - -Use `from-consensus-buff?` when you need to: - -- Convert serialized data back into Clarity values. -- Interact with data that has been serialized by other contracts or off-chain systems. -- Implement cross-contract communication protocols involving serialized data. -- Deserialize stored data that was previously serialized for efficiency. - -## Best Practices - -- Always specify the correct type signature to ensure proper deserialization. -- Handle the `none` case when the deserialization fails. -- Use in conjunction with `to-consensus-buff?` for serialization-deserialization workflows. -- Be aware of the gas costs associated with deserializing large or complex data structures. - -## Practical Example: Deserializing a Tuple - -Let's implement a function that deserializes a buffer into a tuple: - -```clarity -(define-read-only (deserialize-user-data (serializedData (buff 128))) - (match (from-consensus-buff? { name: (string-ascii 50), age: uint } serializedData) - success success - (err u1) - ) -) - -;; Usage -(deserialize-user-data 0x0c00000002036167650100000000000000000000000000000005046e616d650d0000000a48617270657220446f67) -;; Returns (ok (tuple (name "Harper Dog") (age u5))) -``` - -This example demonstrates: -1. Using `from-consensus-buff?` to deserialize a buffer into a tuple. -2. Specifying the expected type structure for the deserialization. -3. Handling both successful and failed deserialization attempts. - -## Common Pitfalls - -1. Specifying an incorrect type signature, leading to deserialization failures. -2. Not handling the `none` case when deserialization fails. -3. Attempting to deserialize data that wasn't properly serialized using the SIP-005 standard. -4. Overlooking potential out-of-memory errors when deserializing very large structures. - -## Related Functions - -- `to-consensus-buff?`: Used to serialize Clarity values into buffers. -- `unwrap-panic`: Often used to forcibly unwrap the optional result (use with caution). -- `match`: Commonly used to handle both success and failure cases of deserialization. - -## Conclusion - -The `from-consensus-buff?` function is a powerful tool for working with serialized data in Clarity smart contracts. It enables contracts to safely deserialize complex data structures, facilitating interoperability and efficient data handling. When used correctly, this function provides a robust way to convert buffers back into typed Clarity values, enhancing the contract's ability to process and validate external data. diff --git a/content/docs/stacks/clarity/functions/ft-burn.mdx b/content/docs/stacks/clarity/functions/ft-burn.mdx deleted file mode 100644 index 386821146..000000000 --- a/content/docs/stacks/clarity/functions/ft-burn.mdx +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: ft-burn? -description: Burn fungible tokens in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(ft-burn? token-name amount sender) -``` - -- Input: - - `token-name`: The name of the fungible token - - `amount`: The amount of tokens to burn (uint) - - `sender`: The principal from whose balance the tokens will be burned -- Output: `(response bool uint)` - -## Why it matters - -The `ft-burn?` function is crucial for: - -1. Decreasing the total supply of a fungible token. -2. Implementing token burning mechanisms in tokenomics models. -3. Allowing users to destroy their own tokens. -4. Managing token supply in deflationary token systems. - -## When to use it - -Use `ft-burn?` when you need to: - -- Implement a token burning feature in your contract. -- Reduce the circulating supply of a token. -- Allow users to voluntarily destroy their tokens. -- Execute deflationary mechanisms in your token economy. - -## Best Practices - -- Ensure that the `sender` has sufficient balance before attempting to burn. -- Use `ft-burn?` in conjunction with proper access controls. -- Consider emitting events or logging burns for transparency. -- Be cautious when burning tokens from a different principal than `tx-sender`. - -## Practical Example: Token Burning Mechanism - -Let's implement a simple token burning function: - -```clarity -(define-fungible-token cBtc) - -(define-data-var tokenAdmin principal tx-sender) - -(define-public (burn-tokens (amount uint)) - (ft-burn? cBtc amount tx-sender) -) - -(define-public (burn-tokens-from (amount uint) (owner principal)) - (begin - (asserts! (is-eq tx-sender (var-get tokenAdmin)) (err u3)) - (ft-burn? cBtc amount owner) - ) -) -``` - -This example demonstrates: -1. Using `ft-burn?` to burn tokens from the transaction sender. -2. Implementing an admin function to burn tokens from any account. -3. Using assertions to ensure only the admin can burn tokens from other accounts. - -## Common Pitfalls - -1. Attempting to burn more tokens than the `sender` has in their balance. -2. Not checking the return value of `ft-burn?` to handle potential errors. -3. Allowing unauthorized burning of tokens from other accounts. -4. Forgetting that burned tokens are permanently destroyed and cannot be recovered. - -## Related Functions - -- `ft-mint?`: Used to create new tokens, increasing the total supply. -- `ft-transfer?`: Used to transfer tokens between principals. -- `ft-get-balance`: Used to check the token balance of a principal. -- `ft-get-supply`: Used to get the current total supply of tokens. - -## Conclusion - -The `ft-burn?` function is a powerful tool for managing the supply of fungible tokens in Clarity smart contracts. It allows for the implementation of deflationary mechanisms and gives users the ability to destroy their own tokens. When used correctly, this function can be a key component in sophisticated tokenomics models. However, it should be used with caution and with proper checks to ensure the integrity of your token system. diff --git a/content/docs/stacks/clarity/functions/ft-get-balance.mdx b/content/docs/stacks/clarity/functions/ft-get-balance.mdx deleted file mode 100644 index 89aff3aa0..000000000 --- a/content/docs/stacks/clarity/functions/ft-get-balance.mdx +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: ft-get-balance -description: Retrieve the balance of a fungible token for a principal in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(ft-get-balance token-name principal) -``` - -- Input: - - `token-name`: The name of the fungible token - - `principal`: The principal whose balance to check -- Output: `uint` - -## Why it matters - -The `ft-get-balance` function is crucial for: - -1. Querying the current balance of a fungible token for any principal. -2. Implementing balance checks before transfers or other token operations. -3. Providing transparency and visibility into token holdings. -4. Enabling other contracts or off-chain applications to verify token balances. - -## When to use it - -Use `ft-get-balance` when you need to: - -- Check a user's token balance before performing operations. -- Implement balance-dependent logic in your contract. -- Provide balance information to users or other contracts. -- Verify sufficient funds for token transfers or burns. - -## Best Practices - -- Use `ft-get-balance` before attempting transfers to ensure sufficient balance. -- Consider caching balance results if queried frequently to optimize gas usage. -- Be aware that balances can change between checks and actual token operations. -- Use in combination with other ft-* functions for comprehensive token management. - -## Practical Example: Balance Check Before Transfer - -Let's implement a function that checks balance before transferring tokens: - -```clarity -(define-fungible-token cBtc) - -(define-public (transfer (amount uint) (recipient principal)) - (let - ( - (senderBalance (ft-get-balance cBtc tx-sender)) - ) - (if (>= senderBalance amount) - (ft-transfer? cBtc amount tx-sender recipient) - (err u1) - ) - ) -) - -;; Usage -(ft-mint? cBtc u100 tx-sender) -(transfer u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) -(ft-get-balance cBtc tx-sender) ;; Returns u50 -``` - -This example demonstrates: -1. Using `ft-get-balance` to check the sender's balance before attempting a transfer. -2. Implementing a conditional transfer based on the balance check. -3. Combining `ft-get-balance` with other ft-* functions for token management. - -## Common Pitfalls - -1. Assuming balances remain constant between checking and performing operations. -2. Not handling the case where a principal might not have any balance (returns 0). -3. Overusing `ft-get-balance` in loops, which can be inefficient for gas consumption. - -## Related Functions - -- `ft-transfer?`: Used to transfer tokens between principals. -- `ft-mint?`: Used to create new tokens, increasing the balance of a principal. -- `ft-burn?`: Used to destroy tokens, decreasing the balance of a principal. -- `ft-get-supply`: Used to get the current total supply of tokens. - -## Conclusion - -The `ft-get-balance` function is a fundamental tool for managing fungible tokens in Clarity smart contracts. It provides a straightforward way to query token balances, enabling you to implement robust token-based systems with proper balance checks and validations. When used effectively in combination with other token functions, this function ensures the integrity and accuracy of token operations within your smart contracts. diff --git a/content/docs/stacks/clarity/functions/ft-get-supply.mdx b/content/docs/stacks/clarity/functions/ft-get-supply.mdx deleted file mode 100644 index 32f4654b6..000000000 --- a/content/docs/stacks/clarity/functions/ft-get-supply.mdx +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: ft-get-supply -description: Retrieve the total supply of a fungible token in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(ft-get-supply token-name) -``` - -- Input: - - `token-name`: The name of the fungible token -- Output: `uint` - -## Why it matters - -The `ft-get-supply` function is crucial for: - -1. Querying the current total supply of a fungible token. -2. Implementing supply-dependent logic in token contracts. -3. Providing transparency about the token's circulating supply. -4. Enabling other contracts or off-chain applications to verify token supply. - -## When to use it - -Use `ft-get-supply` when you need to: - -- Check the current total supply of a token. -- Implement logic that depends on the token's supply (e.g., minting limits). -- Provide supply information to users or other contracts. -- Verify the integrity of token operations by checking supply changes. - -## Best Practices - -- Use `ft-get-supply` in combination with `ft-mint?` and `ft-burn?` to manage token supply. -- Consider caching the supply result if queried frequently to optimize gas usage. -- Be aware that the supply can change between checks due to minting or burning operations. -- Use in conjunction with `ft-get-balance` for comprehensive token management. - -## Practical Example: Supply-Limited Minting - -Let's implement a function that mints tokens only if it doesn't exceed a certain supply cap: - -```clarity -(define-fungible-token cBtc) -(define-constant MAX_SUPPLY u1000000) - -(define-public (mint (amount uint) (recipient principal)) - (let - ( - (currentSupply (ft-get-supply cBtc)) - ) - (if (<= (+ currentSupply amount) MAX_SUPPLY) - (ft-mint? cBtc amount recipient) - (err u1) - ) - ) -) - -;; Usage -(mint u500000 tx-sender) ;; Returns (ok true) -(ft-get-supply cBtc) ;; Returns u500000 -(mint u600000 tx-sender) ;; Returns (err u1) -``` - -This example demonstrates: -1. Using `ft-get-supply` to check the current token supply before minting. -2. Implementing a supply cap check to limit token minting. -3. Combining `ft-get-supply` with `ft-mint?` for supply management. - -## Common Pitfalls - -1. Assuming the supply remains constant between checks and operations. -2. Not considering the potential for overflow when adding to the supply. -3. Overusing `ft-get-supply` in loops, which can be inefficient for gas consumption. - -## Related Functions - -- `ft-mint?`: Used to create new tokens, increasing the total supply. -- `ft-burn?`: Used to destroy tokens, decreasing the total supply. -- `ft-get-balance`: Used to get the token balance of a specific principal. -- `define-fungible-token`: Used to define the fungible token initially. - -## Conclusion - -The `ft-get-supply` function is an essential tool for managing and querying the total supply of fungible tokens in Clarity smart contracts. It provides a straightforward way to access the current circulating supply, enabling you to implement supply-dependent logic and maintain transparency in token operations. When used effectively in combination with other token functions, this function ensures the integrity and accuracy of token supply management within your smart contracts. diff --git a/content/docs/stacks/clarity/functions/ft-mint.mdx b/content/docs/stacks/clarity/functions/ft-mint.mdx deleted file mode 100644 index 8dc2a4aeb..000000000 --- a/content/docs/stacks/clarity/functions/ft-mint.mdx +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: ft-mint? -description: Mint new fungible tokens in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(ft-mint? token-name amount recipient) -``` - -- Input: - - `token-name`: The name of the fungible token - - `amount`: The amount of tokens to mint (uint) - - `recipient`: The principal to receive the newly minted tokens -- Output: `(response bool uint)` - -## Why it matters - -The `ft-mint?` function is crucial for: - -1. Creating new tokens and increasing the total supply of a fungible token. -2. Implementing token issuance mechanisms in smart contracts. -3. Rewarding users or other contracts with newly created tokens. -4. Managing the token economy within a decentralized application. - -## When to use it - -Use `ft-mint?` when you need to: - -- Create new tokens as part of your contract's logic. -- Implement token distribution mechanisms (e.g., airdrops, rewards). -- Increase the balance of a specific principal with new tokens. -- Execute token minting operations based on certain conditions or events. - -## Best Practices - -- Implement proper access controls to restrict who can mint new tokens. -- Consider using a maximum supply cap to prevent unlimited minting. -- Emit events or use a logging mechanism to track minting operations for transparency. -- Be cautious of potential overflow when minting large amounts of tokens. - -## Practical Example: Reward Minting - -Let's implement a simple reward system that mints tokens: - -```clarity -(define-fungible-token RewardToken) - -(define-constant CONTRACT_OWNER tx-sender) - -(define-public (mint-reward (amount uint) (recipient principal)) - (begin - (asserts! (is-eq tx-sender CONTRACT_OWNER) (err u403)) - (ft-mint? RewardToken amount recipient) - ) -) - -;; Usage -(mint-reward u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) if called by CONTRACT_OWNER -``` - -This example demonstrates: -1. Using `ft-mint?` to create new tokens and assign them to a recipient. -2. Implementing a basic access control check before minting. -3. Returning the result of the minting operation. - -## Common Pitfalls - -1. Minting tokens without proper access controls, allowing unauthorized token creation. -2. Not considering the total supply limit, potentially leading to economic imbalances. -3. Forgetting to handle the error case when minting fails (e.g., due to supply cap). -4. Overlooking the gas costs associated with minting, especially for large amounts. - -## Related Functions - -- `ft-burn?`: Used to destroy tokens, decreasing the total supply. -- `ft-transfer?`: Used to transfer tokens between principals. -- `ft-get-balance`: Used to check the token balance of a principal. -- `ft-get-supply`: Used to get the current total supply of tokens. - -## Conclusion - -The `ft-mint?` function is a fundamental tool for managing fungible token creation in Clarity smart contracts. It allows for controlled increase of token supply and distribution to specified recipients. When used responsibly with proper access controls and supply management, this function enables the implementation of sophisticated token economies within decentralized applications on the Stacks blockchain. diff --git a/content/docs/stacks/clarity/functions/ft-transfer.mdx b/content/docs/stacks/clarity/functions/ft-transfer.mdx deleted file mode 100644 index 604bb7dd7..000000000 --- a/content/docs/stacks/clarity/functions/ft-transfer.mdx +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: ft-transfer? -description: Transfer fungible tokens between principals in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(ft-transfer? token-name amount sender recipient) -``` - -- Input: - - `token-name`: The name of the fungible token - - `amount`: The amount of tokens to transfer (uint) - - `sender`: The principal sending the tokens - - `recipient`: The principal receiving the tokens -- Output: `(response bool uint)` - -## Why it matters - -The `ft-transfer?` function is crucial for: - -1. Moving fungible tokens between different principals within a smart contract. -2. Implementing token transfer functionality in decentralized applications. -3. Enabling token-based transactions and interactions between users or contracts. -4. Facilitating token economy mechanisms within smart contracts. - -## When to use it - -Use `ft-transfer?` when you need to: - -- Transfer tokens from one account to another. -- Implement payment or reward systems using custom tokens. -- Allow users to send tokens to each other within your dApp. -- Move tokens as part of more complex contract operations. - -## Best Practices - -- Always check the return value to ensure the transfer was successful. -- Implement proper access controls to prevent unauthorized transfers. -- Consider using `asserts!` or `try!` to handle transfer failures gracefully. -- Be aware that any principal can call this function, so add necessary guards. -- Verify sender has sufficient balance before attempting a transfer. - -## Practical Example: Token Transfer Function - -Let's implement a public function for transferring tokens with some basic checks: - -```clarity -(define-fungible-token cBtc) - -(define-public (transfer-tokens (amount uint) (recipient principal)) - (let - ( - (sender tx-sender) - ) - (asserts! (not (is-eq sender recipient)) (err u2)) - (asserts! (> amount u0) (err u3)) - (match (ft-transfer? cBtc amount sender recipient) - success (ok success) - error (err error) - ) - ) -) - -;; Usage -(ft-mint? cBtc u100 tx-sender) -(transfer-tokens u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) -``` - -This example demonstrates: -1. Using `ft-transfer?` within a public function to transfer tokens. -2. Implementing basic checks for valid transfer conditions. -3. Handling the response from `ft-transfer?` and propagating it to the caller. - -## Common Pitfalls - -1. Forgetting that `ft-transfer?` can be called by any principal, potentially leading to unauthorized transfers. -2. Not handling all possible error cases returned by `ft-transfer?`. -3. Attempting to transfer more tokens than the sender's balance. -4. Using `ft-transfer?` with a token name that hasn't been defined in the contract. - -## Related Functions - -- `ft-mint?`: Used to create new tokens and assign them to a principal. -- `ft-burn?`: Used to destroy tokens, reducing the balance of a principal. -- `ft-get-balance`: Used to check the token balance of a principal. -- `ft-get-supply`: Used to get the current total supply of tokens. - -## Conclusion - -The `ft-transfer?` function is a fundamental component for implementing token transfers in Clarity smart contracts. It provides a straightforward way to move tokens between principals, enabling a wide range of token-based functionalities. When used with proper checks and balances, this function allows for the creation of secure and efficient token economies within decentralized applications on the Stacks blockchain. diff --git a/content/docs/stacks/clarity/functions/get-block-info.mdx b/content/docs/stacks/clarity/functions/get-block-info.mdx deleted file mode 100644 index 76464121b..000000000 --- a/content/docs/stacks/clarity/functions/get-block-info.mdx +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: get-block-info? -description: Fetch information about Stacks blocks in Clarity smart contracts. ---- - - -In Clarity 3, this function is being deprecated for [`get-stacks-block-info?`](/stacks/clarity/functions/get-stacks-block-info). - - -## Function Signature - -```clarity -(get-block-info? prop-name block-height) -``` - -- Input: - - `prop-name`: A BlockInfoPropertyName - - `block-height`: A uint representing the Stacks block height -- Output: `(optional buff) | (optional uint) | (optional principal)` depending on the property - -## Why it matters - -The `get-block-info?` function is crucial for: - -1. Accessing historical block data within smart contracts. -2. Implementing time-based logic using block information. -3. Verifying block-related properties for security or validation purposes. -4. Building applications that need to reference specific blockchain states. - -## When to use it - -Use `get-block-info?` when you need to: - -- Retrieve information about past Stacks blocks. -- Implement logic that depends on block times or miner information. -- Verify block hashes or other block-specific data. -- Access block rewards or miner spending data (in Stacks 2.1+). - -## Best Practices - -- Always check if the returned value is `none`, as it will be for non-existent or future blocks. -- Be aware of the potential for chain reorganizations when using recent block data. -- Use the appropriate property name for the data you need to retrieve. -- Consider caching results for frequently accessed block information to save on execution costs. - -## Practical Example: Block Time Verification - -Let's implement a function that checks if a given block was mined after a certain time: - -```clarity -(define-read-only (block-after-time? (blockHeight uint) (targetTime uint)) - (match (get-block-info? time blockHeight) time - (> time targetTime) - false - ) -) - -;; Usage -(block-after-time? u100 u1600000000) ;; Returns true if block 100 was mined after Unix timestamp 1600000000 -``` - -This example demonstrates: -1. Using `get-block-info?` to retrieve the `time` property of a block. -2. Handling the optional return value with `match`. -3. Comparing the block time to a target time. - -## Available Properties - -- `burnchain-header-hash`: Returns the burnchain block header hash (buff 32). -- `id-header-hash`: Returns the Stacks block's index block hash (buff 32). -- `header-hash`: Returns the Stacks block's header hash (buff 32). -- `miner-address`: Returns the block miner's principal. -- `time`: Returns the block time as a Unix epoch timestamp (uint). - -New in Stacks 2.1: -- `block-reward`: Returns the total block reward (uint). -- `miner-spend-total`: Returns the total spent by miners for this block (uint). - -## Common Pitfalls - -1. Assuming all properties are available for all blocks (e.g., `block-reward` is only available for mature blocks). -2. Not handling the `none` case when the block height is invalid or in the future. -3. Relying on exact block times, which can be inaccurate up to two hours. -4. Using `header-hash` when global uniqueness is required (use `id-header-hash` instead). - -## Related Functions - -- `get-burn-block-info?`: Used to get information about the underlying burn chain blocks. -- `block-height`: Keyword that returns the current block height. -- `burn-block-height`: Keyword that returns the current burn chain block height. - -## Conclusion - -The `get-block-info?` function is a powerful tool for accessing historical block data in Clarity smart contracts. It allows you to incorporate block-specific information into your contract logic, enabling a wide range of applications that can reference and utilize blockchain state. When used correctly, it provides valuable insights into the Stacks blockchain's history and can be used to implement sophisticated, time-aware contract behaviors. diff --git a/content/docs/stacks/clarity/functions/get-burn-block-info.mdx b/content/docs/stacks/clarity/functions/get-burn-block-info.mdx deleted file mode 100644 index 12f0d7598..000000000 --- a/content/docs/stacks/clarity/functions/get-burn-block-info.mdx +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: get-burn-block-info? -description: Fetch information about burnchain blocks in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(get-burn-block-info? prop-name block-height) -``` - -- Input: - - `prop-name`: A BurnBlockInfoPropertyName - - `block-height`: A uint representing the burnchain block height -- Output: `(optional buff) | (optional (tuple (addrs (list 2 (tuple (hashbytes (buff 32)) (version (buff 1))))) (payout uint)))` - -## Why it matters - -The `get-burn-block-info?` function is crucial for: - -1. Accessing historical data from the underlying burnchain (Bitcoin). -2. Implementing cross-chain verification or logic based on Bitcoin block information. -3. Retrieving PoX (Proof of Transfer) related data for advanced stacking operations. -4. Enabling contracts to react to or validate burnchain events. - -## When to use it - -Use `get-burn-block-info?` when you need to: - -- Verify Bitcoin block hashes within your Stacks contract. -- Access information about PoX payouts and addresses. -- Implement logic that depends on burnchain block data. -- Build cross-chain applications that reference Bitcoin state. - -## Best Practices - -- Always check if the returned value is `none`, as it will be for non-existent or future blocks. -- Be aware of the potential for chain reorganizations when using recent block data. -- Use the appropriate property name for the data you need to retrieve. -- Consider caching results for frequently accessed block information to save on execution costs. - -## Practical Example: Verifying a Bitcoin Block Hash - -Let's implement a function that verifies if a given Bitcoin block hash matches a specific height: - -```clarity -(define-read-only (verify-btc-block-hash (height uint) (expectedHash (buff 32))) - (match (get-burn-block-info? header-hash height) hash - (is-eq hash expectedHash) - false - ) -) - -;; Usage -(verify-btc-block-hash u700000 0x00000000000000000009a11b3972c8e532e964e262c196556bd958b7fd0c55c3) -``` - -This example demonstrates: -1. Using `get-burn-block-info?` to retrieve the `header-hash` of a burnchain block. -2. Handling the optional return value with `match`. -3. Comparing the retrieved hash with an expected value. - -## Available Properties - -- `header-hash`: Returns a 32-byte buffer representing the header hash of the burnchain block. -- `pox-addrs`: Returns a tuple containing PoX payout information: - - `addrs`: A list of up to two PoX addresses that received payouts. - - `payout`: The amount of burnchain tokens paid to each address. - -## Common Pitfalls - -1. Assuming all properties are available for all blocks. -2. Not handling the `none` case when the block height is invalid or in the future. -3. Misinterpreting the `pox-addrs` data, especially during different PoX phases. -4. Overlooking the fact that burn addresses may be included in the `pox-addrs` list. - -## Related Functions - -- `get-block-info?`: Used to get information about Stacks blocks. -- `burn-block-height`: Keyword that returns the current burn chain block height. - -## Conclusion - -The `get-burn-block-info?` function is a powerful tool for accessing burnchain data in Clarity smart contracts. It allows you to incorporate Bitcoin blockchain information into your contract logic, enabling cross-chain verification and advanced PoX-related functionalities. When used correctly, this function provides valuable insights into the underlying Bitcoin blockchain's state and can be used to implement sophisticated, cross-chain aware contract behavior. diff --git a/content/docs/stacks/clarity/functions/get-stacks-block-info.mdx b/content/docs/stacks/clarity/functions/get-stacks-block-info.mdx deleted file mode 100644 index a59cc3528..000000000 --- a/content/docs/stacks/clarity/functions/get-stacks-block-info.mdx +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: get-stacks-block-info? -description: Fetch information about Stacks blocks in Clarity smart contracts. ---- - - -In Clarity 3, this function replaces the deprecated `get-block-info?` function. - - -## Function Signature - -```clarity -(get-stacks-block-info? prop-name block-height) -``` - -- Input: - - `prop-name`: A StacksBlockInfoPropertyName - - `block-height`: A uint representing the Stacks block height -- Output: `(optional buff) | (optional uint)` depending on the property - -## Why it matters - -The `get-stacks-block-info?` function is crucial for: - -1. Accessing historical Stacks block data within smart contracts -2. Retrieving globally unique block identifiers -3. Implementing time-based logic using block information -4. Verifying block-related properties for security or validation purposes - -## When to use it - -Use `get-stacks-block-info?` when you need to: - -- Retrieve unique identifiers for Stacks blocks -- Access block timestamps for time-based logic -- Verify block hashes for validation purposes -- Implement logic that depends on block information - -## Best Practices - -- Always use `id-header-hash` when global uniqueness is required -- Handle the `none` case for non-existent or future blocks -- Be aware of the different timestamp sources before and after epoch 3.0 -- Consider caching frequently accessed block information - -## Practical Example: Block Hash Verification - -```clarity -(define-read-only (verify-block-hash (blockHeight uint) (expectedHash (buff 32))) - (match (get-stacks-block-info? id-header-hash blockHeight) - hash (is-eq hash expectedHash) - false - ) -) - -;; Usage -(verify-block-hash u100 0x374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb) -``` - -This example demonstrates: -1. Retrieving a block's unique identifier -2. Handling the optional return value -3. Comparing block hashes for verification - -## Available Properties - -- `id-header-hash`: Returns the globally unique index block hash (buff 32) -- `header-hash`: Returns the Stacks block's header hash (buff 32) -- `time`: Returns the block time as Unix epoch timestamp (uint) - -## Common Pitfalls - -1. Using `header-hash` when global uniqueness is required (use `id-header-hash` instead) -2. Not handling the `none` case for invalid or future block heights -3. Assuming block times are exact (accuracy varies by epoch): - - Pre-epoch 3.0: Accurate within two hours - - Post-epoch 3.0: Must be greater than previous block and at most 15 seconds in the future -4. Not considering the different timestamp sources across epochs - -## Related Functions - -- `get-tenure-info?`: Used to get information about block tenures -- `block-height`: Returns the current block height -- `at-block`: Used with `id-header-hash` for historical state access - -## Conclusion - -The `get-stacks-block-info?` function, introduced in Clarity 3, provides essential access to Stacks block data in smart contracts. This function offers reliable ways to access block identifiers and timestamps, with important considerations for global uniqueness and time accuracy across different epochs. Understanding its properties and limitations is crucial for building robust smart contracts that interact with historical blockchain state. - diff --git a/content/docs/stacks/clarity/functions/get-tenure-info.mdx b/content/docs/stacks/clarity/functions/get-tenure-info.mdx deleted file mode 100644 index b0050563b..000000000 --- a/content/docs/stacks/clarity/functions/get-tenure-info.mdx +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: get-tenure-info? -description: Fetch information about Stacks tenures in Clarity smart contracts. ---- - -## Function Signature - - -```clarity -(get-tenure-info? prop-name block-height) -``` - -- Input: - - `prop-name`: A TenureInfoPropertyName - - `block-height`: A uint representing the Stacks block height -- Output: `(optional buff) | (optional uint) | (optional principal)` depending on the property - -## Why it matters - -The `get-tenure-info?` function is essential for: - -1. Accessing historical tenure data within smart contracts -2. Retrieving information about block miners and rewards -3. Accessing VRF seeds for randomness-based applications -4. Analyzing miner participation and spending patterns - -## When to use it - -Use `get-tenure-info?` when you need to: - -- Access tenure-specific data like VRF seeds or miner addresses -- Verify tenure timestamps or burnchain information -- Analyze block rewards and miner spending patterns -- Implement logic that depends on historical tenure data - -## Best Practices - -- Always handle the `none` case, as it will be returned for non-existent or future blocks -- Be aware that block rewards are only available after maturity (101 blocks on mainnet) -- Consider the two-hour accuracy window when working with tenure timestamps -- Cache frequently accessed tenure information to optimize execution costs - -## Practical Example: Checking Miner Spending - -```clarity -(define-read-only (get-miner-spend-ratio (blockHeight uint))) -(let - ( - (winnerSpend (get-tenure-info? miner-spend-winner blockHeight)) - (totalSpend (get-tenure-info? miner-spend-total blockHeight)) - ) - (match (tuple (winner winnerSpend) (total totalSpend)) - success (some (/ (get success "winner") (get success "total"))) - error none - ) -) -``` - -## Available Properties - -- `burnchain-header-hash`: Returns the burnchain block header hash (buff 32) -- `miner-address`: Returns the tenure miner's principal -- `time`: Returns the tenure time as Unix epoch timestamp (uint) -- `vrf-seed`: Returns the VRF seed for the tenure (buff 32) -- `block-reward`: Returns the total block reward (uint) -- `miner-spend-total`: Returns total spent by all miners for this tenure (uint) -- `miner-spend-winner`: Returns amount spent by winning miner (uint) - -## Common Pitfalls - -1. Not accounting for block reward maturity period (101 blocks) -2. Relying on exact tenure times (accuracy window of two hours) -3. Not handling the `none` case for invalid or future block heights - -## Related Functions - -- `get-block-info?`: Used to get information about Stacks blocks -- `block-height`: Returns the current block height -- `burn-block-height`: Returns the current burn chain block height - -## Conclusion - -The `get-tenure-info?` function provides crucial access to historical tenure data in Clarity smart contracts. Introduced in Clarity 3, this function enables developers to access detailed information about past tenures, including miner participation, block rewards, and VRF seeds. When used properly, `get-tenure-info?` is a powerful tool for implementing sophisticated contract logic that depends on historical blockchain state. diff --git a/content/docs/stacks/clarity/functions/get.mdx b/content/docs/stacks/clarity/functions/get.mdx deleted file mode 100644 index 9a1632054..000000000 --- a/content/docs/stacks/clarity/functions/get.mdx +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: get -description: Retrieve a value from a tuple in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(get key-name tuple) -``` - -- Input: - - `key-name`: The name of the key in the tuple - - `tuple`: The tuple to retrieve the value from -- Output: The value associated with the key in the tuple - -## Why it matters - -The `get` function is crucial for: - -1. Accessing specific values within tuple data structures. -2. Extracting information from complex data types in contracts. -3. Enabling efficient data retrieval in contract logic. -4. Working with structured data returned by other functions or stored in variables. - -## When to use it - -Use `get` when you need to: - -- Access a specific field in a tuple. -- Extract values from structured data returned by other functions. -- Work with complex data types in your contract logic. -- Implement data processing that involves tuple manipulation. - -## Best Practices - -- Ensure the key exists in the tuple to avoid runtime errors. -- Use meaningful key names for better code readability. -- Consider using `get` in combination with `optional` for safer data access. -- Be aware of the performance implications when working with large tuples. - -## Practical Example: User Profile Management - -Let's implement a simple user profile system using tuples and the `get` function: - -```clarity -(define-map UserProfiles { userId: principal } { name: (string-ascii 50), age: uint }) - -(define-public (set-profile (name (string-ascii 50)) (age uint)) - (ok (map-set UserProfiles { userId: tx-sender } { name: name, age: age })) -) - -(define-read-only (get-profile-name (user principal)) - (match (map-get? UserProfiles { userId: user }) profile - (ok (get name profile)) - (err u404) - ) -) - -(define-read-only (get-profile-age (user principal)) - (match (map-get? UserProfiles { userId: user }) profile - (ok (get age profile)) - (err u404) - ) -) - -;; Usage -(set-profile "Alice" u30) -(get-profile-name tx-sender) ;; Returns (ok "Alice") -(get-profile-age tx-sender) ;; Returns (ok u30) -``` - -This example demonstrates: -1. Using `get` to retrieve specific fields from a tuple stored in a map. -2. Implementing getter functions that use `get` to access tuple data. -3. Handling cases where the profile might not exist. - -## Common Pitfalls - -1. Attempting to `get` a key that doesn't exist in the tuple, causing a runtime error. -2. Forgetting that `get` is case-sensitive for key names. -3. Not considering the performance impact of frequently accessing large tuples. - -## Related Functions - -- `merge`: Used to combine tuples, potentially creating new fields to `get`. -- `tuple`: Used to create tuples that can be accessed with `get`. -- `map-get?`: Often used in combination with `get` to retrieve data from maps. - -## Conclusion - -The `get` function is a fundamental tool for working with tuples in Clarity smart contracts. It provides a straightforward way to access structured data, enabling developers to work with complex data types efficiently. When used effectively, `get` enhances the contract's ability to manage and process structured information, leading to more organized and maintainable smart contract code. diff --git a/content/docs/stacks/clarity/functions/greater-than-or-equal.mdx b/content/docs/stacks/clarity/functions/greater-than-or-equal.mdx deleted file mode 100644 index 5d263f435..000000000 --- a/content/docs/stacks/clarity/functions/greater-than-or-equal.mdx +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: greater than or equal -description: Use the greater than or equal function for comparisons in Clarity smart contracts. ---- - -The greater than or equal function (`>=`) in Clarity compares two values and returns true if the first value is greater than or equal to the second. It's a fundamental comparison operation used in many smart contract conditions and logic flows. - -## Function Signature - -```clarity -(>= v1 v2) -``` - -- Input: Two values of the same type (int, uint, string-ascii, string-utf8, or buff) -- Output: A boolean (true or false) - -## Why it matters - -The greater than or equal function is crucial for: - -1. Implementing conditional logic in smart contracts. -2. Comparing numerical values for financial operations. -3. Ordering and sorting data. -4. Implementing minimum thresholds or limits in contract logic. -5. Checking for equality alongside greater than comparisons. - -## When to use it - -Use the greater than or equal function when you need to: - -- Compare two numerical values to determine if one is larger or equal. -- Implement minimum thresholds for certain operations, including the threshold value itself. -- Create conditional logic based on numerical comparisons, including equality. -- Sort or order data based on numerical or lexicographical order, including equal values. - -## Best Practices - -- Ensure that both inputs are of the same type to avoid runtime errors. -- Be aware of the differences in comparison between signed (int) and unsigned (uint) integers. -- When comparing strings or buffers, understand that the comparison is lexicographical. -- Consider edge cases, especially when dealing with the limits of integer ranges. -- Use `>=` instead of `>` when you want to include equality in your comparison. - -## Practical Example: Token Unlock Schedule - -Let's implement a simple token unlock schedule that uses the greater than or equal function to manage token releases: - -```clarity -;; Define constants -(define-constant UNLOCK_AMOUNT u1000000) ;; 1 million tokens per unlock -(define-constant UNLOCK_INTERVAL u17280) ;; Approximately 30 days in blocks -(define-constant TOTAL_UNLOCKS u10) ;; 10 total unlocks - -;; Define data variables -(define-data-var startBlock uint u0) -(define-data-var unlocksClaimed uint u0) - -;; Function to start the unlock schedule -(define-public (start-unlock-schedule) - (begin - (asserts! (is-eq (var-get startBlock) u0) (err u1)) - (var-set startBlock block-height) - (ok true) - ) -) - -;; Function to calculate claimable tokens -(define-read-only (get-claimable-tokens) - (let - ( - (elapsedBlocks (- block-height (var-get startBlock))) - (unlocksDue (/ elapsedBlocks UNLOCK_INTERVAL)) - ) - (if (>= unlocksDue TOTAL_UNLOCKS) - (* UNLOCK_AMOUNT (- TOTAL_UNLOCKS (var-get unlocksClaimed))) - (* UNLOCK_AMOUNT (- unlocksDue (var-get unlocksClaimed))) - ) - ) -) - -;; Function to claim tokens -(define-public (claim-tokens) - (let - ( - (claimableAmount (get-claimable-tokens)) - ) - (asserts! (> claimableAmount u0) (err u2)) - (var-set unlocksClaimed (+ (var-get unlocksClaimed) (/ claimableAmount UNLOCK_AMOUNT))) - ;; Here you would typically transfer tokens - ;; For simplicity, we're just returning the claimed amount - (ok claimableAmount) - ) -) -``` - -This example demonstrates: -1. Using `>=` to check if the number of unlocks due is greater than or equal to the total number of unlocks. -2. Combining the greater than or equal check with other contract logic for a token unlock system. -3. Implementing a minimum threshold (the unlock interval) that includes the exact unlock time. - -## Common Pitfalls - -1. Comparing values of different types, which will result in a runtime error. -2. Confusing `>=` with `>` when setting thresholds, potentially excluding valid values. -3. Overlooking the inclusive nature of `>=` in boundary conditions. - -## Related Functions - -- `>`: Used for strict greater than comparisons. -- `<`: Used for less than comparisons. -- `<=`: Used for less than or equal to comparisons. - -## Conclusion - -The greater than or equal function is a fundamental tool for implementing comparison logic in Clarity smart contracts. By understanding its behavior with different types and potential edge cases, you can create robust conditional logic and enforce important thresholds in your contracts, including scenarios where equality is a valid condition. diff --git a/content/docs/stacks/clarity/functions/greater-than.mdx b/content/docs/stacks/clarity/functions/greater-than.mdx deleted file mode 100644 index 61e9d621e..000000000 --- a/content/docs/stacks/clarity/functions/greater-than.mdx +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: greater than -description: Use the greater than function for comparisons in Clarity smart contracts. ---- - -The greater than function (`>`) in Clarity compares two values and returns true if the first value is greater than the second. It's a fundamental comparison operation used in many smart contract conditions and logic flows. - -## Function Signature - -```clarity -(> v1 v2) -``` - -- Input: Two values of the same type (int, uint, string-ascii, string-utf8, or buff) -- Output: A boolean (true or false) - -## Why it matters - -The greater than function is crucial for: - -1. Implementing conditional logic in smart contracts. -2. Comparing numerical values for financial operations. -3. Ordering and sorting data. -4. Implementing thresholds or limits in contract logic. - -## When to use it - -Use the greater than function when you need to: - -- Compare two numerical values to determine if one is larger. -- Implement minimum thresholds for certain operations. -- Create conditional logic based on numerical comparisons. -- Sort or order data based on numerical or lexicographical order. - -## Best Practices - -- Ensure that both inputs are of the same type to avoid runtime errors. -- Be aware of the differences in comparison between signed (int) and unsigned (uint) integers. -- When comparing strings or buffers, understand that the comparison is lexicographical. -- Consider edge cases, especially when dealing with the limits of integer ranges. - -## Practical Example: Token Sale with Minimum Purchase - -Let's implement a simple token sale contract that uses the greater than function to enforce a minimum purchase amount: - -```clarity -;; Define constants -(define-constant MIN_PURCHASE u100000000) ;; 1 STX -(define-constant TOKEN_PRICE u50000) ;; 0.0005 STX per token - -;; Define data variables -(define-data-var tokensSold uint u0) - -;; Function to purchase tokens -(define-public (purchase-tokens (amount uint)) - (let - ( - (tokensToMint (/ amount TOKEN_PRICE)) - (payment amount) - ) - ;; Check if the purchase amount is greater than the minimum - (asserts! (> payment MIN_PURCHASE) (err u1)) - ;; Perform the token purchase - (try! (stx-transfer? payment tx-sender (as-contract tx-sender))) - (var-set tokensSold (+ (var-get tokensSold) tokensToMint)) - ;; Here you would typically mint or transfer tokens to the buyer - (ok tokensToMint) - ) -) - -;; Function to check total tokens sold -(define-read-only (get-tokensSold) - (ok (var-get tokensSold)) -) -``` - -This example demonstrates: -1. Using `>` to check if the payment amount exceeds the minimum purchase threshold. -2. Combining the greater than check with other contract logic for a token sale. -3. Implementing a minimum purchase amount to prevent small, potentially spam transactions. - -## Common Pitfalls - -1. Comparing values of different types, which will result in a runtime error. -2. Not considering the inclusive nature of `>=` vs the exclusive nature of `>` when setting thresholds. -3. Overlooking potential integer overflow when working with very large numbers. - -## Related Functions - -- `<`: Used for less than comparisons. -- `>=`: Used for greater than or equal to comparisons. -- `<=`: Used for less than or equal to comparisons. - -## Conclusion - -The greater than function is a fundamental tool for implementing comparison logic in Clarity smart contracts. By understanding its behavior with different types and potential edge cases, you can create robust conditional logic and enforce important thresholds in your contracts. diff --git a/content/docs/stacks/clarity/functions/hash160.mdx b/content/docs/stacks/clarity/functions/hash160.mdx deleted file mode 100644 index da630249f..000000000 --- a/content/docs/stacks/clarity/functions/hash160.mdx +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: hash160 -description: Compute the RIPEMD160(SHA256(x)) hash in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(hash160 value) -``` - -- Input: `buff|uint|int` -- Output: `(buff 20)` - -## Why it matters - -The `hash160` function is crucial for: - -1. Creating compact, unique identifiers for data or addresses. -2. Implementing cryptographic operations commonly used in blockchain systems. -3. Generating Bitcoin-style addresses from public keys. -4. Providing a way to create short, collision-resistant hashes. - -## When to use it - -Use `hash160` when you need to: - -- Generate a compact hash of data, especially for address creation. -- Implement Bitcoin-style address generation within Clarity contracts. -- Create short, unique identifiers for data structures. -- Perform cryptographic operations that require RIPEMD160(SHA256(x)). - -## Best Practices - -- Use `hash160` when you need a shorter hash than SHA256 but still want strong collision resistance. -- Be aware that `hash160` is not reversible; it's a one-way function. -- When hashing sensitive data, consider using additional security measures like salting. -- Remember that for integers, the hash is computed over their little-endian representation. - -## Practical Example: Simple Address Generation - -Let's implement a function that generates a simple hash-based identifier: - -```clarity -(define-read-only (generate-identifier (input (buff 32))) - (hash160 input) -) - -;; Usage -(generate-identifier 0x000000000000000000000000000000000000000000000000000000000000000a) -;; Returns 0x3bf3d2e8f7a4d7c5f9e6d0d5c6b0f5c7d8e9f0a1 -``` - -This example demonstrates: -1. Using `hash160` to create a compact identifier from input data. -2. The function takes a 32-byte buffer and returns a 20-byte hash. - -## Common Pitfalls - -1. Assuming `hash160` output is the same length as `sha256` output (it's shorter at 20 bytes). -2. Using `hash160` where a longer hash might be more appropriate for security reasons. -3. Forgetting that integer inputs are hashed in their little-endian representation. -4. Not considering that `hash160` is computationally more expensive than a single `sha256`. - -## Related Functions - -- `sha256`: Computes the SHA256 hash of the input. -- `ripemd160`: Computes the RIPEMD160 hash of the input (not directly available in Clarity, but `hash160` combines SHA256 and RIPEMD160). -- `keccak256`: Another cryptographic hash function available in Clarity. - -## Conclusion - -The `hash160` function is a powerful tool for creating compact, unique identifiers in Clarity smart contracts. It combines the security of SHA256 with the compactness of RIPEMD160, making it particularly useful for address generation and creating short but collision-resistant hashes. When used appropriately, `hash160` can enhance the efficiency and security of your smart contract operations, especially in scenarios where space efficiency is a concern. diff --git a/content/docs/stacks/clarity/functions/if.mdx b/content/docs/stacks/clarity/functions/if.mdx deleted file mode 100644 index a4f6dce0c..000000000 --- a/content/docs/stacks/clarity/functions/if.mdx +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: if -description: Conditional evaluation in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(if bool expr1 expr2) -``` - -- Input: - - `bool`: A boolean expression - - `expr1`: An expression to evaluate if `bool` is true - - `expr2`: An expression to evaluate if `bool` is false -- Output: The result of `expr1` if `bool` is true, otherwise the result of `expr2` - -## Why it matters - -The `if` function is crucial for: - -1. Implementing conditional logic in smart contracts. -2. Making decisions based on dynamic conditions. -3. Controlling the flow of contract execution. -4. Simplifying complex logic by branching based on conditions. - -## When to use it - -Use `if` when you need to: - -- Execute different code paths based on a condition. -- Implement logic that depends on the state or input values. -- Control the flow of your contract based on dynamic conditions. -- Simplify complex decision-making processes. - -## Best Practices - -- Ensure that both `expr1` and `expr2` return the same type. -- Use clear and meaningful boolean expressions for readability. -- Avoid deeply nested `if` statements for better maintainability. -- Combine with other control flow functions like `match` for more complex logic. - -## Practical Example: Conditional Token Transfer - -```clarity -(define-map UserBalances { userId: principal } { balance: uint }) - -(define-public (transfer-tokens (amount uint) (recipient principal)) - (let - ( - (senderBalance (default-to u0 (map-get? UserBalances { userId: tx-sender }))) - ) - (if (>= senderBalance amount) - (begin - (map-set UserBalances { userId: tx-sender } { balance: (- senderBalance amount) }) - (map-set UserBalances { userId: recipient } { balance: (+ (default-to u0 (map-get? UserBalances { userId: recipient })) amount) }) - (ok true) - ) - (err u1) - ) - ) -) -``` - -This example demonstrates: -1. Using `if` to check if the sender has sufficient balance before transferring tokens. -2. Executing different code paths based on the result of the balance check. -3. Handling both the success and failure cases appropriately. - -## Common Pitfalls - -1. Forgetting that both `expr1` and `expr2` must return the same type. -2. Using overly complex boolean expressions, making the code hard to read. -3. Not handling all possible conditions, leading to unexpected behavior. -4. Overusing `if` for logic that could be simplified with other control flow functions. - -## Related Functions - -- `match`: Used for pattern matching and handling multiple conditions. -- `and`: Logical AND operator for combining boolean expressions. -- `or`: Logical OR operator for combining boolean expressions. - -## Conclusion - -The `if` function is a fundamental tool for implementing conditional logic in Clarity smart contracts. It allows you to control the flow of contract execution based on dynamic conditions, enabling more complex and responsive contract behavior. When used effectively, `if` simplifies decision-making processes and enhances the readability and maintainability of your smart contract code. diff --git a/content/docs/stacks/clarity/functions/impl-trait.mdx b/content/docs/stacks/clarity/functions/impl-trait.mdx deleted file mode 100644 index 8283e7dd3..000000000 --- a/content/docs/stacks/clarity/functions/impl-trait.mdx +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: impl-trait -description: Implement traits in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(impl-trait trait-name) -``` - -- Input: - - `trait-name`: The name of the trait to implement -- Output: Not applicable - -## Why it matters - -The `impl-trait` function is crucial for: - -1. Enabling contracts to conform to specific interfaces. -2. Allowing dynamic function calls between contracts. -3. Promoting code reuse and modularity in smart contract development. -4. Ensuring contracts adhere to predefined behaviors and standards. - -## When to use it - -Use `impl-trait` when you need to: - -- Implement a predefined interface in your contract. -- Allow other contracts to interact with your contract through a common interface. -- Ensure your contract adheres to specific standards or behaviors. -- Enable dynamic function calls using `contract-call?`. - -## Best Practices - -- Define traits at the top level of your contract for clarity and organization. -- Ensure all required functions in the trait are implemented in your contract. -- Use meaningful and descriptive names for traits and their functions. -- Document the purpose and usage of each trait in your contract. - -## Practical Example: Implementing a Token Trait - -Let's define a simple token trait and implement it in a contract: - -```clarity -(define-trait token-trait - ( - (transfer (principal principal uint) (response bool uint)) - (get-balance (principal) (response uint uint)) - ) -) - -(impl-trait token-trait) - -(define-map Balances { user: principal } { balance: uint }) - -(define-public (transfer (sender principal) (recipient principal) (amount uint)) - (let - ( - (senderBalance (default-to u0 (map-get? Balances { user: sender }))) - (recipientBalance (default-to u0 (map-get? Balances { user: recipient }))) - ) - (if (>= senderBalance amount) - (begin - (map-set Balances { user: sender } { balance: (- senderBalance amount) }) - (map-set Balances { user: recipient } { balance: (+ recipientBalance amount) }) - (ok true) - ) - (err u1) - ) - ) -) - -(define-read-only (get-balance (user principal)) - (ok (default-to u0 (map-get? Balances { user: user }))) -) -``` - -This example demonstrates: -1. Defining a `token-trait` with `transfer` and `get-balance` functions. -2. Implementing the `token-trait` in a contract using `impl-trait`. -3. Providing implementations for the `transfer` and `get-balance` functions. - -## Common Pitfalls - -1. Forgetting to implement all required functions in the trait, leading to deployment errors. -2. Using inconsistent function signatures between the trait and the implementation. -3. Not documenting the purpose and usage of traits, making the contract harder to understand. -4. Overlooking the need for proper error handling in trait functions. - -## Related Functions - -- `define-trait`: Used to define a new trait. -- `contract-call?`: Used to call functions dynamically on contracts that implement a trait. -- `define-public`: Used to define public functions that can be called from outside the contract. - -## Conclusion - -The `impl-trait` function is a powerful tool for promoting modularity and code reuse in Clarity smart contracts. By implementing predefined interfaces, contracts can interact dynamically and adhere to specific standards and behaviors. When used effectively, `impl-trait` enhances the flexibility and maintainability of your smart contract code, enabling more robust and interoperable decentralized applications. diff --git a/content/docs/stacks/clarity/functions/index-of.mdx b/content/docs/stacks/clarity/functions/index-of.mdx deleted file mode 100644 index 7fb8c5d73..000000000 --- a/content/docs/stacks/clarity/functions/index-of.mdx +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: index-of -description: Find the index of an element in a list in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(index-of list element) -``` - -- Input: - - `list`: A list of elements - - `element`: The element to find in the list -- Output: `(optional uint)` - -## Why it matters - -The `index-of` function is crucial for: - -1. Locating the position of an element within a list. -2. Implementing search functionality in smart contracts. -3. Enabling conditional logic based on the presence and position of elements. -4. Simplifying list operations by providing a built-in search mechanism. - -## When to use it - -Use `index-of` when you need to: - -- Determine the position of an element in a list. -- Check if an element exists in a list and retrieve its index. -- Implement logic that depends on the order or position of elements. -- Simplify list search operations without writing custom loops. - -## Best Practices - -- Ensure the list and element types are compatible. -- Handle the `none` case when the element is not found in the list. -- Use meaningful variable names for better readability. -- Consider the performance implications when searching large lists. - -## Practical Example: Finding an Element in a List - -Let's implement a function that finds the index of a given element in a list of integers: - -```clarity -(define-read-only (find-index (element int) (numbers (list 10 int))) - (index-of numbers element) -) - -;; Usage -(find-index 3 (list 1 2 3 4 5)) ;; Returns (some u2) -(find-index 6 (list 1 2 3 4 5)) ;; Returns none -``` - -This example demonstrates: -1. Using `index-of` to find the position of an element in a list. -2. Handling both the case where the element is found and where it is not found. - -## Common Pitfalls - -1. Assuming the element will always be found, leading to unhandled `none` cases. -2. Using `index-of` on lists with incompatible element types. -3. Overlooking the performance impact of searching very large lists. -4. Not considering that `index-of` returns a 0-based index. - -## Related Functions - -- `filter`: Used to create a new list containing only elements that match a condition. -- `map`: Applies a function to each element in a list, transforming the elements. -- `len`: Returns the length of a list. - -## Conclusion - -The `index-of` function is a powerful tool for locating elements within lists in Clarity smart contracts. It provides a straightforward way to search for elements and retrieve their positions, enabling more complex list operations and conditional logic. When used effectively, `index-of` simplifies list search operations and enhances the readability and maintainability of your smart contract code. diff --git a/content/docs/stacks/clarity/functions/int-to-ascii.mdx b/content/docs/stacks/clarity/functions/int-to-ascii.mdx deleted file mode 100644 index ebaece89b..000000000 --- a/content/docs/stacks/clarity/functions/int-to-ascii.mdx +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: int-to-ascii -description: Convert integers to ASCII string representations in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(int-to-ascii value) -``` - -- Input: `int | uint` -- Output: `(string-ascii 40)` - -## Why it matters - -The `int-to-ascii` function is crucial for: - -1. Converting integer values to their string representations. -2. Facilitating the display and logging of numeric data. -3. Enabling the use of numeric values in contexts that require strings. -4. Simplifying the process of creating human-readable outputs from numeric data. - -## When to use it - -Use `int-to-ascii` when you need to: - -- Convert an integer or unsigned integer to a string. -- Display numeric values in a human-readable format. -- Log or store numeric data as strings. -- Prepare numeric data for concatenation with other strings. - -## Best Practices - -- Ensure the integer value is within the range that can be represented as a string. -- Use meaningful variable names for better readability. -- Combine with other string functions for more complex string manipulations. -- Be aware of the maximum length of the resulting string (40 characters). - -## Practical Example: Logging a User's Balance - -Let's implement a function that logs a user's balance as a string: - -```clarity -(define-map UserBalances { userId: principal } { balance: uint }) - -(define-public (log-balance (user principal)) - (let - ( - (balance (default-to u0 (map-get? UserBalances { userId: user }))) - (balanceStr (int-to-ascii balance)) - ) - (print balanceStr) - ) -) - -;; Usage -(map-set UserBalances { userId: tx-sender } { balance: u100 }) -(log-balance tx-sender) ;; Logs "100" -``` - -This example demonstrates: -1. Using `int-to-ascii` to convert a user's balance to a string. -2. Logging the string representation of the balance using `print`. -3. Handling the case where the user has no balance set. - -## Common Pitfalls - -1. Assuming the resulting string will always fit within 40 characters. -2. Forgetting to handle cases where the integer value is not set or is zero. -3. Using `int-to-ascii` in performance-critical sections without considering the overhead. -4. Not combining with other string functions for more complex manipulations. - -## Related Functions - -- `print`: Used to log or display string values. -- `concat`: Used to concatenate multiple strings. -- `default-to`: Used to provide default values for optional types. - -## Conclusion - -The `int-to-ascii` function is a powerful tool for converting integer values to their string representations in Clarity smart contracts. This function enables you to create human-readable outputs from numeric data, facilitating logging, display, and storage of numeric values as strings. When used effectively, `int-to-ascii` enhances the readability and usability of numeric data within your smart contract code. diff --git a/content/docs/stacks/clarity/functions/int-to-utf8.mdx b/content/docs/stacks/clarity/functions/int-to-utf8.mdx deleted file mode 100644 index 7a98ff5f2..000000000 --- a/content/docs/stacks/clarity/functions/int-to-utf8.mdx +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: int-to-utf8 -description: Convert integers to UTF-8 string representations in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(int-to-utf8 value) -``` - - - - -- Input: `int | uint` -- Output: `(string-utf8 40)` - -## Why it matters - -The `int-to-utf8` function is crucial for: - -1. Converting integer values to their UTF-8 string representations. -2. Facilitating the display and logging of numeric data in a more versatile encoding. -3. Enabling the use of numeric values in contexts that require UTF-8 strings. -4. Simplifying the process of creating human-readable outputs from numeric data. - -## When to use it - -Use `int-to-utf8` when you need to: - -- Convert an integer or unsigned integer to a UTF-8 string. -- Display numeric values in a human-readable format. -- Log or store numeric data as UTF-8 strings. -- Prepare numeric data for concatenation with other UTF-8 strings. - -## Best Practices - -- Ensure the integer value is within the range that can be represented as a string. -- Use meaningful variable names for better readability. -- Combine with other string functions for more complex string manipulations. -- Be aware of the maximum length of the resulting string (40 characters). - -## Practical Example: Logging a User's Balance - -Let's implement a function that logs a user's balance as a UTF-8 string: - -```clarity -(define-map UserBalances { userId: principal } { balance: uint }) - -(define-public (log-balance (user principal)) - (let - ( - (balance (default-to u0 (map-get? UserBalances { userId: user }))) - (balanceStr (int-to-utf8 balance)) - ) - (print balanceStr) - ) -) - -;; Usage -(map-set UserBalances { userId: tx-sender } { balance: u100 }) -(log-balance tx-sender) ;; Logs "100" -``` - - - - -This example demonstrates: -1. Using `int-to-utf8` to convert a user's balance to a UTF-8 string. -2. Logging the string representation of the balance using `print`. -3. Handling the case where the user has no balance set. - -## Common Pitfalls - -1. Assuming the resulting string will always fit within 40 characters. -2. Forgetting to handle cases where the integer value is not set or is zero. -3. Using `int-to-utf8` in performance-critical sections without considering the overhead. -4. Not combining with other string functions for more complex manipulations. - -## Related Functions - -- `print`: Used to log or display string values. -- `concat`: Used to concatenate multiple strings. -- `default-to`: Used to provide default values for optional types. - -## Conclusion - -The `int-to-utf8` function is a powerful tool for converting integer values to their UTF-8 string representations in Clarity smart contracts. It enables you to create human-readable outputs from numeric data, facilitating logging, display, and storage of numeric values as strings. When used effectively, `int-to-utf8` enhances the readability and usability of numeric data within your smart contract code. diff --git a/content/docs/stacks/clarity/functions/is-eq.mdx b/content/docs/stacks/clarity/functions/is-eq.mdx deleted file mode 100644 index 0be867665..000000000 --- a/content/docs/stacks/clarity/functions/is-eq.mdx +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: is-eq -description: Compare values for equality in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(is-eq v1 v2 ...) -``` - - - - -- Input: `A, A, ...` -- Output: `bool` - -## Why it matters - -The `is-eq` function is crucial for: - -1. Comparing values to check for equality. -2. Implementing conditional logic based on value comparisons. -3. Ensuring data integrity by verifying that values match expected results. -4. Simplifying equality checks in smart contract code. - -## When to use it - -Use `is-eq` when you need to: - -- Compare multiple values for equality. -- Implement logic that depends on whether values are equal. -- Verify that input values match expected constants or variables. -- Simplify equality checks in your contract. - -## Best Practices - -- Ensure all values being compared are of the same type to avoid type errors. -- Use `is-eq` for simple equality checks and combine with other logical functions for complex conditions. -- Be aware that `is-eq` does not short-circuit; all values are evaluated. -- Use meaningful variable names for better readability. - -## Practical Example: Checking User Role - -Let's implement a function that checks if a user has a specific role: - -```clarity -(define-constant ADMIN_ROLE "admin") -(define-map UserRoles { userId: principal } { role: (string-ascii 10) }) - -(define-read-only (is-admin (user principal)) - (let - ( - (userRole (default-to "none" (map-get? UserRoles { userId: user }))) - ) - (is-eq userRole ADMIN_ROLE) - ) -) - -;; Usage -(map-set UserRoles { userId: tx-sender } { role: "admin" }) -(is-admin tx-sender) ;; Returns true -``` - - - - -This example demonstrates: -1. Using `is-eq` to compare a user's role with the constant `ADMIN_ROLE`. -2. Handling the case where the user role is not set by providing a default value. -3. Implementing a read-only function to check if a user is an admin. - -## Common Pitfalls - -1. Comparing values of different types, leading to type errors. -2. Assuming `is-eq` short-circuits like `and` or `or` (it does not). -3. Using `is-eq` for complex conditions where other logical functions might be more appropriate. -4. Not handling cases where values might be `none` or unset. - -## Related Functions - -- `is-some`: Checks if an optional value is `some`. -- `is-none`: Checks if an optional value is `none`. -- `asserts!`: Asserts a condition and throws an error if it is false. - -## Conclusion - -The `is-eq` function is a fundamental tool for comparing values in Clarity smart contracts. It provides a straightforward way to check for equality, enabling you to implement conditional logic and verify data integrity. When used effectively, `is-eq` simplifies equality checks and enhances the readability and maintainability of your smart contract code. diff --git a/content/docs/stacks/clarity/functions/is-err.mdx b/content/docs/stacks/clarity/functions/is-err.mdx deleted file mode 100644 index 62f75edbb..000000000 --- a/content/docs/stacks/clarity/functions/is-err.mdx +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: is-err -description: Check if a response is an error in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(is-err value) -``` - -- Input: `(response A B)` -- Output: `bool` - -## Why it matters - -The `is-err` function is crucial for: - -1. Determining if a response value represents an error. -2. Implementing error handling and validation logic. -3. Ensuring robust contract behavior by checking for errors. -4. Simplifying conditional checks based on response types. - -## When to use it - -Use `is-err` when you need to: - -- Check if a response value is an error. -- Implement conditional logic based on the success or failure of operations. -- Validate the results of function calls that return response types. -- Handle errors gracefully in your contract logic. - -## Best Practices - -- Use `is-err` in combination with `match` or `if` for comprehensive error handling. -- Ensure that the response value being checked is of the correct type. -- Use meaningful variable names for better readability. -- Combine with other response handling functions like `is-ok` for complete validation. - -## Practical Example: Validating a Token Transfer - -Let's implement a function that validates a token transfer and checks for errors: - -```clarity -(define-map UserBalances { userId: principal } { balance: uint }) - -(define-public (transfer-tokens (amount uint) (recipient principal)) - (let - ( - (senderBalance (default-to u0 (map-get? UserBalances { userId: tx-sender }))) - (recipientBalance (default-to u0 (map-get? UserBalances { userId: recipient }))) - (transferResult (if (>= senderBalance amount) - (begin - (map-set UserBalances { userId: tx-sender } { balance: (- senderBalance amount) }) - (map-set UserBalances { userId: recipient } { balance: (+ recipientBalance amount) }) - (ok true) - ) - (err u1) - )) - ) - (if (is-err transferResult) - (err u2) - (ok true) - ) - ) -) - -;; Usage -(map-set UserBalances { userId: tx-sender } { balance: u100 }) -(transfer-tokens u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) -(transfer-tokens u200 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u2) -``` - -This example demonstrates: -1. Using `is-err` to check if the token transfer operation resulted in an error. -2. Implementing conditional logic based on the success or failure of the transfer. -3. Handling both the success and error cases appropriately. - -## Common Pitfalls - -1. Assuming the response value is always of the correct type, leading to type errors. -2. Not handling all possible error cases, resulting in incomplete error handling. -3. Overlooking the need for comprehensive validation and error checking. -4. Using `is-err` without meaningful error codes or messages, making debugging harder. - -## Related Functions - -- `is-ok`: Checks if a response value is `ok`. -- `err`: Constructs an error response. -- `ok`: Constructs a success response. - -## Conclusion - -The `is-err` function is a fundamental tool for error handling in Clarity smart contracts. It allows you to check if a response value represents an error, enabling robust and comprehensive error handling and validation logic. When used effectively, `is-err` enhances the reliability and maintainability of your smart contract code by ensuring that errors are detected and handled appropriately. diff --git a/content/docs/stacks/clarity/functions/is-none.mdx b/content/docs/stacks/clarity/functions/is-none.mdx deleted file mode 100644 index 0bd3d66ba..000000000 --- a/content/docs/stacks/clarity/functions/is-none.mdx +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: is-none -description: Check if an optional value is none in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(is-none value) -``` - -- Input: `(optional A)` -- Output: `bool` - -## Why it matters - -The `is-none` function is crucial for: - -1. Determining if an optional value is `none`. -2. Implementing conditional logic based on the presence or absence of values. -3. Ensuring robust contract behavior by checking for missing values. -4. Simplifying checks for optional values in smart contract code. - -## When to use it - -Use `is-none` when you need to: - -- Check if an optional value is `none`. -- Implement logic that depends on whether a value is present or absent. -- Validate the results of function calls that return optional types. -- Handle cases where values might be missing or not set. - -## Best Practices - -- Use `is-none` in combination with `match` or `if` for comprehensive value handling. -- Ensure that the value being checked is of the correct optional type. -- Use meaningful variable names for better readability. -- Combine with other optional handling functions like `is-some` for complete validation. - -## Practical Example: Checking for Missing User Data - -Let's implement a function that checks if a user's profile data is missing: - -```clarity -(define-map UserProfiles { userId: principal } { name: (string-ascii 50), age: uint }) - -(define-read-only (is-profile-missing (user principal)) - (is-none (map-get? UserProfiles { userId: user })) -) - -;; Usage -(map-set UserProfiles { userId: tx-sender } { name: "Alice", age: u30 }) -(is-profile-missing tx-sender) ;; Returns false -(is-profile-missing 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns true -``` - -This example demonstrates: -1. Using `is-none` to check if a user's profile data is missing. -2. Implementing a read-only function to determine the presence of user data. -3. Handling both the case where the profile data is present and where it is missing. - -## Common Pitfalls - -1. Assuming the value will always be `some`, leading to unhandled `none` cases. -2. Using `is-none` on non-optional types, causing type errors. -3. Not handling all possible conditions, resulting in incomplete value checks. -4. Overlooking the need for comprehensive validation and error checking. - -## Related Functions - -- `is-some`: Checks if an optional value is `some`. -- `match`: Used for pattern matching and handling multiple conditions. -- `default-to`: Provides default values for optional types. - -## Conclusion - -The `is-none` function is a fundamental tool for checking optional values in Clarity smart contracts. It allows you to determine if a value is `none`, enabling robust and comprehensive value handling and validation logic. When used effectively, `is-none` enhances the reliability and maintainability of your smart contract code by ensuring that missing values are detected and handled appropriately. diff --git a/content/docs/stacks/clarity/functions/is-ok.mdx b/content/docs/stacks/clarity/functions/is-ok.mdx deleted file mode 100644 index c8ec71305..000000000 --- a/content/docs/stacks/clarity/functions/is-ok.mdx +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: is-ok -description: Check if a response is ok in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(is-ok value) -``` - -- Input: `(response A B)` -- Output: `bool` - -## Why it matters - -The `is-ok` function is crucial for: - -1. Determining if a response value represents a successful operation. -2. Implementing conditional logic based on the success or failure of operations. -3. Ensuring robust contract behavior by checking for successful responses. -4. Simplifying checks for response types in smart contract code. - -## When to use it - -Use `is-ok` when you need to: - -- Check if a response value is `ok`. -- Implement logic that depends on the success of operations. -- Validate the results of function calls that return response types. -- Handle success cases gracefully in your contract logic. - -## Best Practices - -- Use `is-ok` in combination with `match` or `if` for comprehensive response handling. -- Ensure that the response value being checked is of the correct type. -- Use meaningful variable names for better readability. -- Combine with other response handling functions like `is-err` for complete validation. - -## Practical Example: Validating a Token Transfer - -Let's implement a function that validates a token transfer and checks for success: - -```clarity -(define-map UserBalances { userId: principal } { balance: uint }) - -(define-public (transfer-tokens (amount uint) (recipient principal)) - (let - ( - (senderBalance (default-to u0 (map-get? UserBalances { userId: tx-sender }))) - (recipientBalance (default-to u0 (map-get? UserBalances { userId: recipient }))) - (transferResult (if (>= senderBalance amount) - (begin - (map-set UserBalances { userId: tx-sender } { balance: (- senderBalance amount) }) - (map-set UserBalances { userId: recipient } { balance: (+ recipientBalance amount) }) - (ok true) - ) - (err u1) - )) - ) - (if (is-ok transferResult) - (ok true) - (err u2) - ) - ) -) - -;; Usage -(map-set UserBalances { userId: tx-sender } { balance: u100 }) -(transfer-tokens u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) -(transfer-tokens u200 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u2) -``` - -This example demonstrates: -1. Using `is-ok` to check if the token transfer operation was successful. -2. Implementing conditional logic based on the success of the transfer. -3. Handling both the success and error cases appropriately. - -## Common Pitfalls - -1. Assuming the response value is always of the correct type, leading to type errors. -2. Not handling all possible success and error cases, resulting in incomplete response handling. -3. Overlooking the need for comprehensive validation and error checking. -4. Using `is-ok` without meaningful success codes or messages, making debugging harder. - -## Related Functions - -- `is-err`: Checks if a response value is `err`. -- `err`: Constructs an error response. -- `ok`: Constructs a success response. - -## Conclusion - -The `is-ok` function is a fundamental tool for checking response values in Clarity smart contracts. It allows you to determine if a response value represents a successful operation, enabling robust and comprehensive response handling and validation logic. When used effectively, `is-ok` enhances the reliability and maintainability of your smart contract code by ensuring that successful operations are detected and handled appropriately. diff --git a/content/docs/stacks/clarity/functions/is-some.mdx b/content/docs/stacks/clarity/functions/is-some.mdx deleted file mode 100644 index 128003584..000000000 --- a/content/docs/stacks/clarity/functions/is-some.mdx +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: is-some -description: Check if an optional value is some in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(is-some value) -``` - -- Input: `(optional A)` -- Output: `bool` - -## Why it matters - -The `is-some` function is crucial for: - -1. Determining if an optional value is `some`. -2. Implementing conditional logic based on the presence of values. -3. Ensuring robust contract behavior by checking for existing values. -4. Simplifying checks for optional values in smart contract code. - -## When to use it - -Use `is-some` when you need to: - -- Check if an optional value is `some`. -- Implement logic that depends on whether a value is present. -- Validate the results of function calls that return optional types. -- Handle cases where values might be present or absent. - -## Best Practices - -- Use `is-some` in combination with `match` or `if` for comprehensive value handling. -- Ensure that the value being checked is of the correct optional type. -- Use meaningful variable names for better readability. -- Combine with other optional handling functions like `is-none` for complete validation. - -## Practical Example: Checking for Existing User Data - -Let's implement a function that checks if a user's profile data exists: - -```clarity -(define-map UserProfiles { userId: principal } { name: (string-ascii 50), age: uint }) - -(define-read-only (is-profile-existing (user principal)) - (is-some (map-get? UserProfiles { userId: user })) -) - -;; Usage -(map-set UserProfiles { userId: tx-sender } { name: "Alice", age: u30 }) -(is-profile-existing tx-sender) ;; Returns true -(is-profile-existing 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns false -``` - -This example demonstrates: -1. Using `is-some` to check if a user's profile data exists. -2. Implementing a read-only function to determine the presence of user data. -3. Handling both the case where the profile data is present and where it is absent. - -## Common Pitfalls - -1. Assuming the value will always be `some`, leading to unhandled `none` cases. -2. Using `is-some` on non-optional types, causing type errors. -3. Not handling all possible conditions, resulting in incomplete value checks. -4. Overlooking the need for comprehensive validation and error checking. - -## Related Functions - -- `is-none`: Checks if an optional value is `none`. -- `match`: Used for pattern matching and handling multiple conditions. -- `default-to`: Provides default values for optional types. - -## Conclusion - -The `is-some` function is a fundamental tool for checking optional values in Clarity smart contracts. It allows you to determine if a value is `some`, enabling robust and comprehensive value handling and validation logic. When used effectively, `is-some` enhances the reliability and maintainability of your smart contract code by ensuring that existing values are detected and handled appropriately. diff --git a/content/docs/stacks/clarity/functions/is-standard.mdx b/content/docs/stacks/clarity/functions/is-standard.mdx deleted file mode 100644 index 198e0cc25..000000000 --- a/content/docs/stacks/clarity/functions/is-standard.mdx +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: is-standard -description: Check if a value is a standard principal in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(is-standard value) -``` - -- Input: `principal` -- Output: `bool` - -## Why it matters - -The `is-standard` function is crucial for: - -1. Determining if a principal is a standard principal (i.e., a user address). -2. Implementing conditional logic based on the type of principal. -3. Ensuring that certain operations are only performed by standard principals. -4. Simplifying checks for principal types in smart contract code. - -## When to use it - -Use `is-standard` when you need to: - -- Check if a principal is a standard user address. -- Implement logic that depends on the type of principal. -- Validate the type of principal before performing certain operations. -- Handle cases where only standard principals are allowed. - -## Best Practices - -- Use `is-standard` in combination with `if` or `match` for comprehensive principal type handling. -- Ensure that the value being checked is of the correct principal type. -- Use meaningful variable names for better readability. -- Note that you can pass in a valid contract principal as well, not just a standard principal (e.g., `'SP12` or `'SP12.contract`). - -## Practical Example: Restricting Access to Standard Principals - -Let's implement a function that restricts access to standard principals: - -```clarity -(define-map UserBalances { userId: principal } { balance: uint }) - -(define-public (transfer-tokens (amount uint) (recipient principal)) - (if (is-standard tx-sender) - (let - ( - (senderBalance (default-to u0 (map-get? UserBalances { userId: tx-sender }))) - (recipientBalance (default-to u0 (map-get? UserBalances { userId: recipient }))) - ) - (if (>= senderBalance amount) - (begin - (map-set UserBalances { userId: tx-sender } { balance: (- senderBalance amount) }) - (map-set UserBalances { userId: recipient } { balance: (+ recipientBalance amount) }) - (ok true) - ) - (err u1) - ) - ) - (err u2) - ) -) - -;; Usage -(map-set UserBalances { userId: tx-sender } { balance: u100 }) -(transfer-tokens u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) if tx-sender is a standard principal -``` - -This example demonstrates: -1. Using `is-standard` to check if the transaction sender is a standard principal. -2. Implementing conditional logic based on the type of principal. -3. Handling both the case where the principal is standard and where it is not. - -## Common Pitfalls - -1. Assuming the principal will always be standard, leading to unhandled cases. -2. Using `is-standard` on non-principal types, causing type errors. -3. Not handling all possible conditions, resulting in incomplete principal type checks. -4. Overlooking the need for comprehensive validation and error checking. - -## Related Functions - -- `tx-sender`: Returns the principal that initiated the transaction. -- `contract-caller`: Returns the caller of the current contract context. - -## Conclusion - -The `is-standard` function is a fundamental tool for checking principal types in Clarity smart contracts. It allows you to determine if a principal is a standard user address, enabling robust and comprehensive principal type handling and validation logic. When used effectively, `is-standard` enhances the reliability and maintainability of your smart contract code by ensuring that operations are performed by the correct type of principal. diff --git a/content/docs/stacks/clarity/functions/keccak256.mdx b/content/docs/stacks/clarity/functions/keccak256.mdx deleted file mode 100644 index f7af697fd..000000000 --- a/content/docs/stacks/clarity/functions/keccak256.mdx +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: keccak256 -description: Compute the Keccak-256 hash of a buffer in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(keccak256 value) -``` - -- Input: `buff` -- Output: `(buff 32)` - -## Why it matters - -The `keccak256` function is crucial for: - -1. Computing cryptographic hashes of data. -2. Ensuring data integrity and authenticity. -3. Implementing cryptographic operations in smart contracts. -4. Creating unique identifiers for data. - -## When to use it - -Use `keccak256` when you need to: - -- Compute a cryptographic hash of a buffer. -- Verify data integrity and authenticity. -- Generate unique identifiers for data. -- Implement cryptographic operations in your contract. - -## Best Practices - -- Ensure the input buffer is of the correct length and format. -- Use meaningful variable names for better readability. -- Combine with other cryptographic functions for more complex operations. -- Be aware of the security implications of using cryptographic hashes. - -## Practical Example: Hashing a User's Data - -Let's implement a function that computes the Keccak-256 hash of a user's data: - -```clarity -(define-map UserData { userId: principal } { data: (buff 32) }) - -(define-public (hash-user-data (user principal)) - (let - ( - (data (default-to (buff 0) (map-get? UserData { userId: user }))) - (hash (keccak256 data)) - ) - (ok hash) - ) -) - -;; Usage -(map-set UserData { userId: tx-sender } { data: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef }) -(hash-user-data tx-sender) ;; Returns the Keccak-256 hash of the data -``` - -This example demonstrates: -1. Using `keccak256` to compute the hash of a user's data. -2. Implementing a public function to return the hash. -3. Handling the case where the user's data is not set by providing a default value. - -## Common Pitfalls - -1. Using `keccak256` on non-buffer types, causing type errors. -2. Not handling cases where the input buffer is empty or invalid. -3. Overlooking the need for proper error handling and validation. -4. Assuming the hash function is collision-resistant without understanding its limitations. - -## Related Functions - -- `sha256`: Computes the SHA-256 hash of a buffer. -- `hash160`: Computes the RIPEMD-160 hash of the SHA-256 hash of a buffer. -- `concat`: Concatenates multiple buffers. - -## Conclusion - -The `keccak256` function is a powerful tool for computing cryptographic hashes in Clarity smart contracts. It allows you to ensure data integrity and authenticity, generate unique identifiers, and implement cryptographic operations. When used effectively, `keccak256` enhances the security and reliability of your smart contract code by providing a robust mechanism for hashing data. diff --git a/content/docs/stacks/clarity/functions/len.mdx b/content/docs/stacks/clarity/functions/len.mdx deleted file mode 100644 index 9a61d9b07..000000000 --- a/content/docs/stacks/clarity/functions/len.mdx +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: len -description: Get the length of a sequence in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(len sequence) -``` - -- Input: `sequence_A` -- Output: `uint` - -## Why it matters - -The `len` function is crucial for: - -1. Determining the length of various sequence types. -2. Implementing logic that depends on the size of sequences. -3. Ensuring data integrity by validating sequence lengths. -4. Simplifying length checks in smart contract code. - -## When to use it - -Use `len` when you need to: - -- Get the length of a list, buffer, or string. -- Implement logic that depends on the size of sequences. -- Validate the length of input data. -- Handle cases where the size of a sequence is important. - -## Best Practices - -- Ensure the sequence type is compatible with the `len` function. -- Use meaningful variable names for better readability. -- Combine with other functions for comprehensive sequence handling. -- Be aware of the maximum length of sequences in Clarity. - -## Practical Example: Validating a List Length - -Let's implement a function that validates the length of a list of integers: - -```clarity -(define-read-only (validate-list-length (numbers (list 10 int))) - (let - ( - (length (len numbers)) - ) - (if (<= length u10) - (ok length) - (err u1) - ) - ) -) - -;; Usage -(validate-list-length (list 1 2 3 4 5)) ;; Returns (ok u5) -(validate-list-length (list 1 2 3 4 5 6 7 8 9 10 11)) ;; Returns (err u1) -``` - -This example demonstrates: -1. Using `len` to get the length of a list of integers. -2. Implementing conditional logic based on the length of the list. -3. Handling both the case where the list length is valid and where it is not. - -## Common Pitfalls - -1. Using `len` on incompatible types, causing type errors. -2. Assuming the length will always be within a certain range, leading to unhandled cases. -3. Not handling all possible conditions, resulting in incomplete length checks. -4. Overlooking the need for comprehensive validation and error checking. - -## Related Functions - -- `as-max-len?`: Ensures a sequence does not exceed a maximum length. -- `concat`: Concatenates multiple sequences. -- `default-to`: Provides default values for optional types. - -## Conclusion - -The `len` function is a fundamental tool for getting the length of sequences in Clarity smart contracts. It allows you to determine the size of lists, buffers, and strings, enabling robust and comprehensive sequence handling and validation logic. When used effectively, `len` enhances the reliability and maintainability of your smart contract code by ensuring that sequence lengths are detected and handled appropriately. diff --git a/content/docs/stacks/clarity/functions/less-than-or-equal.mdx b/content/docs/stacks/clarity/functions/less-than-or-equal.mdx deleted file mode 100644 index 76084f7af..000000000 --- a/content/docs/stacks/clarity/functions/less-than-or-equal.mdx +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: less than or equal -description: Use the less than or equal function for comparisons in Clarity smart contracts. ---- - -The less than or equal function (`<=`) in Clarity compares two values and returns true if the first value is less than or equal to the second. It's a fundamental comparison operation used in many smart contract conditions and logic flows. - -## Function Signature - -```clarity -(<= v1 v2) -``` - -- Input: Two values of the same type (int, uint, string-ascii, string-utf8, or buff) -- Output: A boolean (true or false) - -## Why it matters - -The less than or equal function is crucial for: - -1. Implementing conditional logic in smart contracts. -2. Comparing numerical values for financial operations. -3. Ordering and sorting data. -4. Implementing maximum thresholds or limits in contract logic. -5. Checking for equality alongside less than comparisons. - -## When to use it - -Use the less than or equal function when you need to: - -- Compare two numerical values to determine if one is smaller or equal. -- Implement maximum thresholds for certain operations, including the threshold value itself. -- Create conditional logic based on numerical comparisons, including equality. -- Sort or order data based on numerical or lexicographical order, including equal values. - -## Best Practices - -- Ensure that both inputs are of the same type to avoid runtime errors. -- Be aware of the differences in comparison between signed (int) and unsigned (uint) integers. -- When comparing strings or buffers, understand that the comparison is lexicographical. -- Consider edge cases, especially when dealing with the limits of integer ranges. -- Use `<=` instead of `<` when you want to include equality in your comparison. - -## Practical Example: Token Vesting Contract - -Let's implement a simple token vesting contract that uses the less than or equal function to manage vesting periods: - -```clarity -;; Define constants -(define-constant VESTING_PERIOD u31536000) ;; 1 year in seconds -(define-constant TOTAL_ALLOCATION u1000000) ;; 1 million tokens - -;; Define data variables -(define-data-var vestingStartTime uint u0) -(define-data-var tokensClaimed uint u0) - -;; Function to start vesting -(define-public (start-vesting) - (begin - (asserts! (is-eq (var-get vestingStartTime) u0) (err u1)) - (var-set vestingStartTime block-height) - (ok true) - ) -) - -;; Function to calculate vested amount -(define-read-only (get-vested-amount) - (let - ( - (elapsed-time (- block-height (var-get vestingStartTime))) - (vesting-ratio (/ elapsed-time VESTING_PERIOD)) - ) - (if (<= elapsed-time VESTING_PERIOD) - (* TOTAL_ALLOCATION vesting-ratio) - TOTAL_ALLOCATION - ) - ) -) - -;; Function to claim vested tokens -(define-public (claim-tokens) - (let - ( - (vested-amount (get-vested-amount)) - (claimable-amount (- vested-amount (var-get tokensClaimed))) - ) - (asserts! (> claimable-amount u0) (err u2)) - (var-set tokensClaimed vested-amount) - ;; Here you would typically transfer tokens - ;; For simplicity, we're just returning the claimed amount - (ok claimable-amount) - ) -) -``` - -This example demonstrates: -1. Using `<=` to check if the elapsed time is within or equal to the vesting period. -2. Combining the less than or equal check with other contract logic for a vesting system. -3. Implementing a maximum threshold (the vesting period) that includes the exact end time. - -## Common Pitfalls - -1. Comparing values of different types, which will result in a runtime error. -2. Confusing `<=` with `<` when setting thresholds, potentially excluding valid values. -3. Overlooking the inclusive nature of `<=` in boundary conditions. - -## Related Functions - -- `<`: Used for strict less than comparisons. -- `>`: Used for greater than comparisons. -- `>=`: Used for greater than or equal to comparisons. - -## Conclusion - -The less than or equal function is a fundamental tool for implementing comparison logic in Clarity smart contracts. By understanding its behavior with different types and potential edge cases, you can create robust conditional logic and enforce important thresholds in your contracts, including scenarios where equality is a valid condition. diff --git a/content/docs/stacks/clarity/functions/less-than.mdx b/content/docs/stacks/clarity/functions/less-than.mdx deleted file mode 100644 index 675d3abf8..000000000 --- a/content/docs/stacks/clarity/functions/less-than.mdx +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: less than -description: Use the less than function for comparisons in Clarity smart contracts. ---- - -The less than function (`<`) in Clarity compares two values and returns true if the first value is less than the second. It's a fundamental comparison operation used in many smart contract conditions and logic flows. - -## Function Signature - -```clarity -(< v1 v2) -``` - -- Input: Two values of the same type (int, uint, string-ascii, string-utf8, or buff) -- Output: A boolean (true or false) - -## Why it matters - -The less than function is crucial for: - -1. Implementing conditional logic in smart contracts. -2. Comparing numerical values for financial operations. -3. Ordering and sorting data. -4. Implementing maximum thresholds or limits in contract logic. - -## When to use it - -Use the less than function when you need to: - -- Compare two numerical values to determine if one is smaller. -- Implement maximum thresholds for certain operations. -- Create conditional logic based on numerical comparisons. -- Sort or order data based on numerical or lexicographical order. - -## Best Practices - -- Ensure that both inputs are of the same type to avoid runtime errors. -- Be aware of the differences in comparison between signed (int) and unsigned (uint) integers. -- When comparing strings or buffers, understand that the comparison is lexicographical. -- Consider edge cases, especially when dealing with the limits of integer ranges. - -## Practical Example: Auction Contract with Maximum Bid - -Let's implement a simple auction contract that uses the less than function to enforce a maximum bid amount: - -```clarity -;; Define constants -(define-constant MAX_BID u1000000000) ;; 1000 STX -(define-constant AUCTION_END_HEIGHT u100) - -;; Define data variables -(define-data-var currentHighestBid uint u0) -(define-data-var highestBidder (optional principal) none) - -;; Function to place a bid -(define-public (place-bid (bid uint)) - (let - ( - (current-block-height block-height) - ) - ;; Check if the auction is still open - (asserts! (< current-block-height AUCTION_END_HEIGHT) (err u1)) - ;; Check if the bid is less than the maximum allowed bid - (asserts! (< bid MAX_BID) (err u2)) - ;; Check if the bid is higher than the current highest bid - (asserts! (> bid (var-get currentHighestBid)) (err u3)) - ;; Place the bid - (try! (stx-transfer? bid tx-sender (as-contract tx-sender))) - (var-set currentHighestBid bid) - (var-set highestBidder (some tx-sender)) - (ok bid) - ) -) - -;; Function to check current highest bid -(define-read-only (get-highest-bid) - (ok (var-get currentHighestBid)) -) - -;; Function to check if auction has ended -(define-read-only (auction-ended) - (>= block-height AUCTION_END_HEIGHT) -) -``` - -This example demonstrates: -1. Using `<` to check if the current block height is less than the auction end height. -2. Using `<` to ensure the bid is less than the maximum allowed bid. -3. Combining the less than check with other contract logic for an auction system. - -## Common Pitfalls - -1. Comparing values of different types, which will result in a runtime error. -2. Not considering the inclusive nature of `<=` vs the exclusive nature of `<` when setting thresholds. -3. Overlooking potential integer underflow when working with very small numbers. - -## Related Functions - -- `>`: Used for greater than comparisons. -- `<=`: Used for less than or equal to comparisons. -- `>=`: Used for greater than or equal to comparisons. - -## Conclusion - -The less than function is a fundamental tool for implementing comparison logic in Clarity smart contracts. By understanding its behavior with different types and potential edge cases, you can create robust conditional logic and enforce important thresholds in your contracts. diff --git a/content/docs/stacks/clarity/functions/let.mdx b/content/docs/stacks/clarity/functions/let.mdx deleted file mode 100644 index a836c7ca2..000000000 --- a/content/docs/stacks/clarity/functions/let.mdx +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: let -description: Bind variables to expressions in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(let ((name1 expr1) (name2 expr2) ...) expr-body1 expr-body2 ... expr-body-last) -``` - -- Input: `((name1 AnyType) (name2 AnyType) ...), AnyType, ... A` -- Output: `A` - -## Why it matters - -The `let` function is crucial for: - -1. Binding variables to expressions within a local scope. -2. Simplifying complex expressions by breaking them into smaller parts. -3. Improving code readability and maintainability. -4. Enabling sequential evaluation of expressions. - -## When to use it - -Use `let` when you need to: - -- Bind variables to expressions within a local scope. -- Simplify complex expressions by breaking them into smaller parts. -- Improve the readability and maintainability of your code. -- Ensure sequential evaluation of expressions. - -## Best Practices - -- Use meaningful variable names for better readability. -- Ensure that the expressions are evaluated in the correct order. -- Combine with other control flow functions for more complex logic. -- Be aware that `let` bindings are sequential and can refer to prior bindings. - -## Practical Example: Calculating a Sum - -Let's implement a function that calculates the sum of two numbers using `let`: - -```clarity -(define-public (calculate-sum (a int) (b int)) - (let - ( - (sum (+ a b)) - ) - (ok sum) - ) -) - -;; Usage -(calculate-sum 3 5) ;; Returns (ok 8) -``` - -This example demonstrates: -1. Using `let` to bind the variable `sum` to the result of adding `a` and `b`. -2. Returning the sum as the result of the function. -3. Simplifying the function body by breaking it into smaller parts. - -## Common Pitfalls - -1. Using `let` bindings out of order, leading to incorrect evaluations. -2. Not handling all possible conditions, resulting in incomplete logic. -3. Overlooking the need for proper error handling and validation. -4. Using `let` for simple expressions where it is not necessary. - -## Related Functions - -- `begin`: Evaluates multiple expressions sequentially, returning the last expression's value. -- `if`: Implements conditional logic based on boolean expressions. -- `match`: Used for pattern matching and handling multiple conditions. - -## Conclusion - -The `let` function is a fundamental tool for binding variables to expressions in Clarity smart contracts. It allows you to simplify complex expressions, improve code readability, and ensure sequential evaluation of expressions. When used effectively, `let` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to manage local variables and expressions. diff --git a/content/docs/stacks/clarity/functions/list.mdx b/content/docs/stacks/clarity/functions/list.mdx deleted file mode 100644 index 4ee4c5ac5..000000000 --- a/content/docs/stacks/clarity/functions/list.mdx +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: list -description: Construct lists in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(list expr1 expr2 expr3 ...) -``` - -- Input: `A, ...` -- Output: `(list A)` - -## Why it matters - -The `list` function is crucial for: - -1. Constructing lists of elements in Clarity. -2. Enabling the use of lists for data storage and manipulation. -3. Simplifying the creation of sequences of values. -4. Facilitating operations on collections of data. - -## When to use it - -Use `list` when you need to: - -- Construct a list of elements. -- Store and manipulate sequences of values. -- Pass lists as arguments to functions. -- Perform operations on collections of data. - -## Best Practices - -- Ensure all elements in the list are of the same type. -- Use meaningful variable names for better readability. -- Combine with other list functions for comprehensive list handling. -- Be aware of the maximum length of lists in Clarity. - -## Practical Example: Creating a List of Integers - -Let's implement a function that creates a list of integers and returns its length: - -```clarity -(define-read-only (create-list) - (let - ( - (numbers (list 1 2 3 4 5)) - ) - (len numbers) - ) -) - -;; Usage -(create-list) ;; Returns u5 -``` - -This example demonstrates: -1. Using `list` to create a list of integers. -2. Binding the list to a variable using `let`. -3. Returning the length of the list using `len`. - -## Common Pitfalls - -1. Using `list` with elements of different types, causing type errors. -2. Assuming the list will always be within a certain length, leading to unhandled cases. -3. Not handling all possible conditions, resulting in incomplete list checks. -4. Overlooking the need for comprehensive validation and error checking. - -## Related Functions - -- `len`: Returns the length of a list. -- `append`: Adds an element to the end of a list. -- `concat`: Concatenates multiple lists. - -## Conclusion - -The `list` function is a fundamental tool for constructing lists in Clarity smart contracts. It allows you to create sequences of values, enabling robust and comprehensive list handling and manipulation. When used effectively, `list` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to manage collections of data. diff --git a/content/docs/stacks/clarity/functions/log2.mdx b/content/docs/stacks/clarity/functions/log2.mdx deleted file mode 100644 index 0d613d732..000000000 --- a/content/docs/stacks/clarity/functions/log2.mdx +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: log2 -description: Calculate the base-2 logarithm of a number in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(log2 n) -``` - -- Input: `int | uint` -- Output: `int | uint` - -## Why it matters - -The `log2` function is crucial for: - -1. Calculating the base-2 logarithm of a number. -2. Implementing mathematical operations that require logarithmic calculations. -3. Simplifying the process of determining the power of 2 needed to obtain a given value. -4. Facilitating operations that depend on logarithmic scaling. - -## When to use it - -Use `log2` when you need to: - -- Calculate the base-2 logarithm of an integer or unsigned integer. -- Implement logic that depends on logarithmic calculations. -- Determine the power of 2 needed to obtain a given value. -- Simplify mathematical operations involving logarithms. - -## Best Practices - -- Ensure the input value is non-negative, as `log2` fails on negative numbers. -- Use meaningful variable names for better readability. -- Combine with other mathematical functions for comprehensive calculations. -- Be aware of the integer rounding behavior of `log2`. - -## Practical Example: Calculating Logarithm of a Number - -Let's implement a function that calculates the base-2 logarithm of a given number: - -```clarity -(define-read-only (calculate-log2 (n uint)) - (log2 n) -) - -;; Usage -(calculate-log2 u8) ;; Returns u3 -(calculate-log2 u16) ;; Returns u4 -``` - -This example demonstrates: -1. Using `log2` to calculate the base-2 logarithm of a given number. -2. Implementing a read-only function to return the logarithm. -3. Handling both small and large input values. - -## Common Pitfalls - -1. Using `log2` on negative numbers, causing the function to fail. -2. Assuming the result will always be an integer, leading to incorrect expectations. -3. Not handling all possible conditions, resulting in incomplete calculations. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `sqrti`: Returns the largest integer that is less than or equal to the square root of a number. -- `pow`: Raises a number to the power of another number. -- `sqrt`: Returns the square root of a number. - -## Conclusion - -The `log2` function is a fundamental tool for calculating the base-2 logarithm of numbers in Clarity smart contracts. It allows you to perform logarithmic calculations, enabling robust and comprehensive mathematical operations. When used effectively, `log2` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to manage logarithmic calculations. diff --git a/content/docs/stacks/clarity/functions/map-delete.mdx b/content/docs/stacks/clarity/functions/map-delete.mdx deleted file mode 100644 index bc94fa1e5..000000000 --- a/content/docs/stacks/clarity/functions/map-delete.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: map-delete -description: Remove an entry from a map in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(map-delete map-name key-tuple) -``` - -- Input: `MapName, tuple` -- Output: `bool` - -## Why it matters - -The `map-delete` function is crucial for: - -1. Removing entries from a map. -2. Managing and updating the state of data stored in maps. -3. Ensuring data integrity by allowing the deletion of obsolete or incorrect entries. -4. Simplifying the process of maintaining clean and accurate data in smart contracts. - -## When to use it - -Use `map-delete` when you need to: - -- Remove an entry from a map. -- Manage and update the state of data stored in maps. -- Ensure data integrity by deleting obsolete or incorrect entries. -- Maintain clean and accurate data in your smart contract. - -## Best Practices - -- Ensure the key-tuple accurately identifies the entry to be deleted. -- Use meaningful variable names for better readability. -- Combine with other map functions for comprehensive map management. -- Be aware of the performance implications of frequent deletions in large maps. - -## Practical Example: Deleting a User's Data - -Let's implement a function that deletes a user's data from a map: - -```clarity -(define-map UserData { userId: principal } { data: (buff 32) }) - -(define-public (delete-user-data (user principal)) - (ok (map-delete UserData { userId: user })) -) - -;; Usage -(map-set UserData { userId: tx-sender } { data: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef }) ;; Returns true -(delete-user-data tx-sender) ;; Returns (ok true) -``` - -This example demonstrates: -1. Using `map-delete` to remove a user's data from the `UserData` map. -2. Implementing a public function to delete the data. -3. Handling the case where the user's data is present and needs to be removed. - -## Common Pitfalls - -1. Using `map-delete` with an incorrect key-tuple, causing the deletion to fail. -2. Assuming the entry will always exist, leading to unhandled cases. -3. Not handling all possible conditions, resulting in incomplete data management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `map-set`: Sets the value associated with a key in a map. -- `map-get?`: Retrieves an entry from a map. -- `map-insert`: Inserts a value into a map if the key does not already exist. - -## Conclusion - -The `map-delete` function is a fundamental tool for managing data in Clarity smart contracts. It allows you to remove entries from maps, ensuring data integrity and maintaining clean and accurate data. When used effectively, `map-delete` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to manage map entries. diff --git a/content/docs/stacks/clarity/functions/map-get.mdx b/content/docs/stacks/clarity/functions/map-get.mdx deleted file mode 100644 index 25ad3c1a8..000000000 --- a/content/docs/stacks/clarity/functions/map-get.mdx +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: map-get? -description: Retrieve an entry from a map in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(map-get? map-name key-tuple) -``` - -- Input: `MapName, tuple` -- Output: `(optional (tuple))` - -## Why it matters - -The `map-get?` function is crucial for: - -1. Retrieving entries from a map. -2. Implementing logic that depends on the presence of map entries. -3. Ensuring data integrity by checking for the existence of values. -4. Simplifying the process of accessing stored data in smart contracts. - -## When to use it - -Use `map-get?` when you need to: - -- Retrieve an entry from a map. -- Implement logic that depends on the presence of map entries. -- Check for the existence of values in a map. -- Access stored data in your smart contract. - -## Best Practices - -- Ensure the key-tuple accurately identifies the entry to be retrieved. -- Use meaningful variable names for better readability. -- Combine with other map functions for comprehensive map management. -- Handle the `none` case to avoid runtime errors. - -## Practical Example: Retrieving User Data - -Let's implement a function that retrieves a user's data from a map: - -```clarity -(define-map UserData { userId: principal } { data: (buff 32) }) - -(define-read-only (get-user-data (user principal)) - (map-get? UserData { userId: user }) -) - -;; Usage -(map-set UserData { userId: tx-sender } { data: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef }) -(get-user-data tx-sender) ;; Returns (some (tuple (data 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef))) -(get-user-data 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns none -``` - -This example demonstrates: -1. Using `map-get?` to retrieve a user's data from the `UserData` map. -2. Implementing a read-only function to return the retrieved data. -3. Handling both the case where the user's data is present and where it is not. - -## Common Pitfalls - -1. Using `map-get?` with an incorrect key-tuple, causing the retrieval to fail. -2. Assuming the entry will always exist, leading to unhandled `none` cases. -3. Not handling all possible conditions, resulting in incomplete data retrieval. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `map-set`: Sets the value associated with a key in a map. -- `map-delete`: Removes an entry from a map. -- `map-insert`: Inserts a value into a map if the key does not already exist. - -## Conclusion - -The `map-get?` function is a fundamental tool for retrieving entries from maps in Clarity smart contracts. It allows you to access stored data, implement logic based on map entries, and ensure data integrity. When used effectively, `map-get?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to retrieve map entries. diff --git a/content/docs/stacks/clarity/functions/map-insert.mdx b/content/docs/stacks/clarity/functions/map-insert.mdx deleted file mode 100644 index a446110a9..000000000 --- a/content/docs/stacks/clarity/functions/map-insert.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: map-insert -description: Insert an entry into a map in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(map-insert map-name key-tuple value-tuple) -``` - -- Input: `MapName, tuple_A, tuple_B` -- Output: `bool` - -## Why it matters - -The `map-insert` function is crucial for: - -1. Adding new entries to a map. -2. Ensuring data integrity by preventing overwrites of existing entries. -3. Simplifying the process of managing data in smart contracts. -4. Enabling the creation of unique key-value pairs in maps. - -## When to use it - -Use `map-insert` when you need to: - -- Add a new entry to a map. -- Ensure that existing entries are not overwritten. -- Manage data in your smart contract. -- Create unique key-value pairs in maps. - -## Best Practices - -- Ensure the key-tuple and value-tuple are correctly formatted. -- Use meaningful variable names for better readability. -- Combine with other map functions for comprehensive map management. -- Handle the case where the key already exists to avoid unexpected behavior. - -## Practical Example: Inserting User Data - -Let's implement a function that inserts a user's data into a map: - -```clarity -(define-map UserData { userId: principal } { data: (buff 32) }) - -(define-public (insert-user-data (user principal) (data (buff 32))) - (ok (map-insert UserData { userId: user } { data: data })) -) - -;; Usage -(insert-user-data tx-sender 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef) ;; Returns (ok true) if the entry is inserted -(insert-user-data tx-sender 0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdef) ;; Returns (ok false) if the entry already exists -``` - -This example demonstrates: -1. Using `map-insert` to add a user's data to the `UserData` map. -2. Implementing a public function to insert the data. -3. Handling both the case where the entry is successfully inserted and where it already exists. - -## Common Pitfalls - -1. Using `map-insert` with incorrectly formatted tuples, causing the insertion to fail. -2. Assuming the entry will always be inserted, leading to unhandled cases. -3. Not handling all possible conditions, resulting in incomplete data management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `map-set`: Sets the value associated with a key in a map, overwriting any existing value. -- `map-delete`: Removes an entry from a map. -- `map-get?`: Retrieves an entry from a map. - -## Conclusion - -The `map-insert` function is a fundamental tool for adding entries to maps in Clarity smart contracts. It allows you to manage data, ensure data integrity, and create unique key-value pairs. When used effectively, `map-insert` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to manage data insertion. diff --git a/content/docs/stacks/clarity/functions/map-set.mdx b/content/docs/stacks/clarity/functions/map-set.mdx deleted file mode 100644 index b90b01f66..000000000 --- a/content/docs/stacks/clarity/functions/map-set.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: map-set -description: Set an entry in a map in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(map-set map-name key-tuple value-tuple) -``` - -- Input: `MapName, tuple_A, tuple_B` -- Output: `bool` - -## Why it matters - -The `map-set` function is crucial for: - -1. Setting or updating entries in a map. -2. Managing and updating the state of data stored in maps. -3. Ensuring data integrity by allowing updates to existing entries. -4. Simplifying the process of maintaining accurate data in smart contracts. - -## When to use it - -Use `map-set` when you need to: - -- Set or update an entry in a map. -- Manage and update the state of data stored in maps. -- Ensure data integrity by updating existing entries. -- Maintain accurate data in your smart contract. - -## Best Practices - -- Ensure the key-tuple and value-tuple are correctly formatted. -- Use meaningful variable names for better readability. -- Combine with other map functions for comprehensive map management. -- Be aware of the performance implications of frequent updates in large maps. - -## Practical Example: Setting User Data - -Let's implement a function that sets a user's data in a map: - -```clarity -(define-map UserData { userId: principal } { data: (buff 32) }) - -(define-public (set-user-data (user principal) (data (buff 32))) - (ok (map-set UserData { userId: user } { data: data })) -) - -;; Usage -(set-user-data tx-sender 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef) ;; Returns (ok true) -(set-user-data tx-sender 0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdef) ;; Returns (ok true) -``` - -This example demonstrates: -1. Using `map-set` to set a user's data in the `UserData` map. -2. Implementing a public function to set the data. -3. Handling both the case where the entry is newly created and where it is updated. - -## Common Pitfalls - -1. Using `map-set` with incorrectly formatted tuples, causing the operation to fail. -2. Assuming the entry will always be updated, leading to unhandled cases. -3. Not handling all possible conditions, resulting in incomplete data management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `map-insert`: Inserts a value into a map if the key does not already exist. -- `map-delete`: Removes an entry from a map. -- `map-get?`: Retrieves an entry from a map. - -## Conclusion - -The `map-set` function is a fundamental tool for setting or updating entries in maps in Clarity smart contracts. It allows you to manage data, ensure data integrity, and maintain accurate data. When used effectively, `map-set` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to manage map entries. diff --git a/content/docs/stacks/clarity/functions/map.mdx b/content/docs/stacks/clarity/functions/map.mdx deleted file mode 100644 index 060b1790a..000000000 --- a/content/docs/stacks/clarity/functions/map.mdx +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: map -description: Apply a function to each element of a list in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(map function list) -``` - -- Input: `(function (A) => B)`, `(list A)` -- Output: `(list B)` - -## Why it matters - -The `map` function is crucial for: - -1. Applying a function to each element of a list. -2. Transforming lists by applying operations to their elements. -3. Simplifying the process of performing bulk operations on lists. -4. Enhancing code readability and maintainability by abstracting repetitive operations. - -## When to use it - -Use `map` when you need to: - -- Apply a function to each element of a list. -- Transform a list by applying operations to its elements. -- Perform bulk operations on lists. -- Simplify and abstract repetitive operations on list elements. - -## Best Practices - -- Ensure the function being applied is compatible with the elements of the list. -- Use meaningful variable names for better readability. -- Combine with other list functions for comprehensive list handling. -- Be aware of the performance implications of applying functions to large lists. - -## Practical Example: Doubling Each Element in a List - -Let's implement a function that doubles each element in a list of integers: - -```clarity -(define-private (double (n int)) - (* n 2) -) - -(define-read-only (double-elements (numbers (list 10 int))) - (map double numbers) -) - -;; Usage -(double-elements (list 1 2 3 4 5)) ;; Returns (list 2 4 6 8 10) -``` - -This example demonstrates: -1. Defining a private function `double` to double an integer. -2. Using `map` to apply the `double` function to each element in a list. -3. Implementing a read-only function to return the transformed list. -4. Handling both small and large input lists. - -## Common Pitfalls - -1. Using `map` with incompatible function and list element types, causing type errors. -2. Assuming the list will always be within a certain length, leading to unhandled cases. -3. Not handling all possible conditions, resulting in incomplete list transformations. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `filter`: Filters elements of a list based on a predicate function. -- `fold`: Reduces a list to a single value by applying a function. -- `len`: Returns the length of a list. - -## Conclusion - -The `map` function is a fundamental tool for applying functions to each element of a list in Clarity smart contracts. It allows you to transform lists, perform bulk operations, and simplify repetitive tasks. When used effectively, `map` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to manage list transformations. diff --git a/content/docs/stacks/clarity/functions/match.mdx b/content/docs/stacks/clarity/functions/match.mdx deleted file mode 100644 index 4c4de9289..000000000 --- a/content/docs/stacks/clarity/functions/match.mdx +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: match -description: Handle different branches or cases in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(match opt-input some-binding-name some-branch none-branch) -(match-resp input ok-binding-name ok-branch err-binding-name err-branch) -``` - -- Input: `(optional A) name expression expression | (response A B) name expression name expression` -- Output: `C` - -## Why it matters - -The `match` function is crucial for: - -1. Handling different branches or cases for optional and response types. -2. Simplifying complex conditional logic. -3. Enhancing code readability and maintainability. -4. Ensuring comprehensive handling of all possible cases. - -## When to use it - -Use `match` when you need to: - -- Handle different branches or cases for optional and response types. -- Simplify complex conditional logic. -- Enhance the readability and maintainability of your code. -- Ensure comprehensive handling of all possible cases. - -## Best Practices - -- Ensure all possible branches are covered to avoid unhandled cases. -- Use meaningful variable names for better readability. -- Combine with other control flow functions for more complex logic. -- Be aware of the performance implications of extensive branching. - -## Practical Example: Handling Optional and Response Values - -Let's implement functions that handle optional and response values using `match`: - -```clarity -(define-private (add-10 (x (optional int))) - (match x - value (+ 10 value) - 10 - ) -) -(add-10 (some 5)) ;; Returns 15 -(add-10 none) ;; Returns 10 - -(define-private (add-or-pass-err (x (response int (string-ascii 10))) (to-add int)) - (match x - value (ok (+ to-add value)) - err-value (err err-value) - ) -) -(add-or-pass-err (ok 5) 20) ;; Returns (ok 25) -(add-or-pass-err (err "ERROR") 20) ;; Returns (err "ERROR") -``` - -This example demonstrates: -1. Using `match` to handle the result of an optional value. -2. Using `match` to handle the result of a response value. -3. Implementing functions to return the appropriate result based on the input type. - -## Common Pitfalls - -1. Using `match` without covering all possible branches, leading to unhandled cases. -2. Assuming the value will always match a certain branch, causing runtime errors. -3. Not handling all possible conditions, resulting in incomplete logic. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `if`: Implements conditional logic based on boolean expressions. -- `let`: Binds variables to expressions within a local scope. -- `default-to`: Provides default values for optional types. - -## Conclusion - -The `match` function is a fundamental tool for handling different branches or cases in Clarity smart contracts. It allows you to manage optional and response types, simplify complex conditional logic, and ensure comprehensive handling of all possible cases. When used effectively, `match` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to manage branching logic. diff --git a/content/docs/stacks/clarity/functions/merge.mdx b/content/docs/stacks/clarity/functions/merge.mdx deleted file mode 100644 index fc452251e..000000000 --- a/content/docs/stacks/clarity/functions/merge.mdx +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: merge -description: Merge tuples in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(merge tuple1 tuple2) -``` - -- Input: `tuple, tuple` -- Output: `tuple` - -## Why it matters - -The `merge` function is crucial for: - -1. Combining fields from two tuples into a single tuple. -2. Simplifying the process of updating and managing data structures. -3. Ensuring data integrity by creating new tuples without mutating the original ones. -4. Enhancing code readability and maintainability by abstracting tuple merging operations. - -## When to use it - -Use `merge` when you need to: - -- Combine fields from two tuples into a single tuple. -- Update and manage data structures in a clean and efficient manner. -- Ensure data integrity by creating new tuples without mutating the original ones. -- Simplify and abstract tuple merging operations. - -## Best Practices - -- Ensure the tuples being merged have compatible fields. -- Use meaningful variable names for better readability. -- Combine with other tuple and map functions for comprehensive data management. -- Be aware of the performance implications of frequent tuple merging in large data structures. - -## Practical Example: Merging User Data - -Let's implement a function that merges additional data into a user's existing data: - -```clarity -(define-map Users { id: int } { name: (string-ascii 12), address: (optional principal) }) - -(define-public (update-user-address (user-id int) (new-address principal)) - (let - ( - (user (unwrap-panic (map-get? Users { id: user-id }))) - (updated-user (merge user { address: (some new-address) })) - ) - (map-set Users { id: user-id } updated-user) - ) -) - -;; Usage -(map-insert Users { id: 1337 } { name: "john", address: none }) ;; Returns true -(update-user-address 1337 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns true -(map-get? Users { id: 1337 }) ;; Returns (some (tuple (name "john") (address (some SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF)))) -``` - -This example demonstrates: -1. Using `merge` to combine a user's existing data with new address data. -2. Implementing a public function to update the user's address. -3. Handling both the retrieval and updating of user data in a clean and efficient manner. - -## Common Pitfalls - -1. Using `merge` with tuples that have incompatible fields, causing runtime errors. -2. Assuming the tuples will always have the expected fields, leading to unhandled cases. -3. Not handling all possible conditions, resulting in incomplete data management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `map-set`: Sets the value associated with a key in a map. -- `map-get?`: Retrieves an entry from a map. -- `map-insert`: Inserts a value into a map if the key does not already exist. - -## Conclusion - -The `merge` function is a fundamental tool for combining tuples in Clarity smart contracts. It allows you to manage and update data structures efficiently, ensuring data integrity and enhancing code readability. When used effectively, `merge` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to manage tuple merging operations. diff --git a/content/docs/stacks/clarity/functions/mod.mdx b/content/docs/stacks/clarity/functions/mod.mdx deleted file mode 100644 index d856575af..000000000 --- a/content/docs/stacks/clarity/functions/mod.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: mod -description: Calculate the remainder of integer division in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(mod i1 i2) -``` - -- Input: `int, int | uint, uint | string-ascii, string-ascii | string-utf8, string-utf8 | buff, buff` -- Output: `int | uint` - -## Why it matters - -The `mod` function is crucial for: - -1. Calculating the remainder of integer division. -2. Implementing logic that depends on modular arithmetic. -3. Simplifying the process of performing operations that require remainders. -4. Enhancing code readability and maintainability by abstracting modular operations. - -## When to use it - -Use `mod` when you need to: - -- Calculate the remainder of integer division. -- Implement logic that depends on modular arithmetic. -- Perform operations that require remainders. -- Simplify and abstract modular operations. - -## Best Practices - -- Ensure the divisor is not zero to avoid runtime errors. -- Use meaningful variable names for better readability. -- Combine with other mathematical functions for comprehensive calculations. -- Be aware of the performance implications of frequent modular operations. - -## Practical Example: Calculating Remainders - -Let's implement a function that calculates the remainder of dividing two numbers: - -```clarity -(define-read-only (calculate-remainder (a int) (b int)) - (mod a b) -) - -;; Usage -(calculate-remainder 5 2) ;; Returns 1 -(calculate-remainder 7 3) ;; Returns 1 -(calculate-remainder 10 4) ;; Returns 2 -``` - -This example demonstrates: -1. Using `mod` to calculate the remainder of dividing two numbers. -2. Implementing a read-only function to return the remainder. -3. Handling both small and large input values. - -## Common Pitfalls - -1. Using `mod` with a divisor of zero, causing a runtime error. -2. Assuming the result will always be positive, leading to incorrect expectations. -3. Not handling all possible conditions, resulting in incomplete calculations. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `+`: Adds two numbers. -- `-`: Subtracts one number from another. -- `*`: Multiplies two numbers. -- `/`: Divides one number by another. - -## Conclusion - -The `mod` function is a fundamental tool for calculating the remainder of integer division in Clarity smart contracts. It allows you to perform modular arithmetic, enabling robust and comprehensive mathematical operations. When used effectively, `mod` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to manage modular calculations. diff --git a/content/docs/stacks/clarity/functions/multiply.mdx b/content/docs/stacks/clarity/functions/multiply.mdx deleted file mode 100644 index f284a2ccc..000000000 --- a/content/docs/stacks/clarity/functions/multiply.mdx +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: multiply -description: Use the multiplication function for arithmetic operations in Clarity smart contracts. ---- - -The multiplication function (`*`) in Clarity performs multiplication on a variable number of integer inputs. It's a fundamental arithmetic operation used in many smart contract calculations. - -## Function Signature - -```clarity -(* i1 i2...) -``` - -- Input: Two or more integers (int or uint) -- Output: A single integer (int or uint) - -## Why it matters - -The multiplication function is crucial for: - -1. Performing basic arithmetic calculations within smart contracts. -2. Scaling values, such as calculating fees or interest. -3. Implementing more complex mathematical operations. -4. Adjusting token amounts in financial contracts. - -## When to use it - -Use the multiplication function when you need to: - -- Perform basic multiplication in your contract logic. -- Scale values proportionally. -- Calculate compound values or rates. -- Implement mathematical formulas that involve multiplication. - -## Best Practices - -- Always consider the possibility of overflow when multiplying large numbers. -- Use appropriate types (int or uint) based on your needs and expected value ranges. -- Consider using `mul-overflow?` for checked multiplication if overflow detection is needed. -- Be aware that multiplying by zero will always return zero. - -## Practical Example: Token Vesting Contract - -Let's implement a simple token vesting contract that uses multiplication to calculate vested amounts: - -```clarity -;; Define constants -(define-constant VESTING_PERIOD u365) ;; 1 year in days -(define-constant TOTAL_ALLOCATION u1000000) ;; Total tokens to vest - -;; Define data variables -(define-data-var startTime uint u0) -(define-data-var beneficiary principal tx-sender) - -;; Function to initialize vesting -(define-public (start-vesting (recipient principal)) - (begin - (asserts! (is-eq tx-sender (var-get beneficiary)) (err u1)) - (var-set startTime block-height) - (var-set beneficiary recipient) - (ok true) - ) -) - -;; Function to calculate vested amount -(define-read-only (get-vested-amount) - (let - ( - (elapsed-time (- block-height (var-get startTime))) - (vesting-rate (/ TOTAL_ALLOCATION VESTING_PERIOD)) - ) - (if (>= elapsed-time VESTING_PERIOD) - TOTAL_ALLOCATION - (* vesting-rate elapsed-time) - ) - ) -) - -;; Function to claim vested tokens -(define-public (claim-tokens) - (let - ( - (vested-amount (get-vested-amount)) - ) - (asserts! (> vested-amount u0) (err u2)) - ;; Here you would typically transfer tokens - ;; For simplicity, we're just returning the amount - (ok vested-amount) - ) -) -``` - -This example demonstrates: -1. Using multiplication to calculate the vested amount based on elapsed time and vesting rate. -2. Combining multiplication with division to implement a linear vesting schedule. -3. Using multiplication as part of a larger mathematical formula in a smart contract context. - -## Common Pitfalls - -1. Overlooking potential overflow when multiplying large numbers. -2. Not considering the effect of integer division when combined with multiplication. -3. Assuming multiplication always increases a value (forgetting about multiplication by fractions < 1 in integer arithmetic). - -## Related Functions - -- `/`: Used for division operations. -- `+`: Used for addition operations. -- `-`: Used for subtraction operations. -- `mul-overflow?`: Used for checked multiplication with overflow detection. - -## Conclusion - -The multiplication function is a fundamental tool for performing arithmetic operations in Clarity smart contracts. By understanding its behavior with different types of inputs and potential edge cases, you can use it effectively to implement various mathematical operations in your contracts, from simple scaling to more complex financial calculations. diff --git a/content/docs/stacks/clarity/functions/nft-burn.mdx b/content/docs/stacks/clarity/functions/nft-burn.mdx deleted file mode 100644 index 02914007c..000000000 --- a/content/docs/stacks/clarity/functions/nft-burn.mdx +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: nft-burn? -description: Burn a non-fungible token (NFT) in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(nft-burn? asset-class asset-identifier sender) -``` - -- Input: `AssetName, A, principal` -- Output: `(response bool uint)` - -## Why it matters - -The `nft-burn?` function is crucial for: - -1. Reducing the circulating supply of a non-fungible token (NFT). -2. Managing the lifecycle of NFTs by allowing their destruction. -3. Ensuring data integrity by removing ownership records of burned NFTs. -4. Simplifying the process of handling NFT burn operations in smart contracts. - -## When to use it - -Use `nft-burn?` when you need to: - -- Reduce the circulating supply of an NFT. -- Manage the lifecycle of NFTs by allowing their destruction. -- Remove ownership records of burned NFTs. -- Handle NFT burn operations in your smart contract. - -## Best Practices - -- Ensure the `sender` principal owns the NFT before attempting to burn it. -- Use meaningful variable names for better readability. -- Combine with other NFT functions for comprehensive NFT management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Burning an NFT - -Let's implement a function that burns an NFT owned by the sender: - -```clarity -(define-non-fungible-token Stackaroo (string-ascii 40)) - -(define-public (burn-nft (id (string-ascii 40))) - (nft-burn? Stackaroo id tx-sender) -) - -;; Usage -(nft-mint? Stackaroo "Roo" tx-sender) ;; Returns (ok true) -(burn-nft "Roo") ;; Returns (ok true) -(nft-burn? Stackaroo "Roo" tx-sender) ;; Returns (err u3) because the asset no longer exists -``` - -This example demonstrates: -1. Using `nft-burn?` to burn an NFT owned by the sender. -2. Implementing a public function to handle the burn operation. -3. Handling both the successful burn and the case where the asset no longer exists. - -## Common Pitfalls - -1. Using `nft-burn?` without ensuring the `sender` owns the NFT, causing the operation to fail. -2. Assuming the NFT will always exist, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete NFT management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `nft-mint?`: Mints a new non-fungible token. -- `nft-transfer?`: Transfers ownership of a non-fungible token. -- `nft-get-owner?`: Retrieves the owner of a non-fungible token. - -## Conclusion - -The `nft-burn?` function is a fundamental tool for managing the lifecycle of non-fungible tokens in Clarity smart contracts. It allows you to reduce the circulating supply of NFTs, manage their destruction, and ensure data integrity. When used effectively, `nft-burn?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle NFT burn operations. diff --git a/content/docs/stacks/clarity/functions/nft-get-owner.mdx b/content/docs/stacks/clarity/functions/nft-get-owner.mdx deleted file mode 100644 index fff95fc22..000000000 --- a/content/docs/stacks/clarity/functions/nft-get-owner.mdx +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: nft-get-owner? -description: Retrieve the owner of a non-fungible token (NFT) in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(nft-get-owner? asset-class asset-identifier) -``` - -- Input: `AssetName, A` -- Output: `(optional principal)` - -## Why it matters - -The `nft-get-owner?` function is crucial for: - -1. Retrieving the owner of a non-fungible token (NFT). -2. Implementing logic that depends on the ownership of NFTs. -3. Ensuring data integrity by verifying ownership records. -4. Simplifying the process of accessing ownership information in smart contracts. - -## When to use it - -Use `nft-get-owner?` when you need to: - -- Retrieve the owner of an NFT. -- Implement logic that depends on the ownership of NFTs. -- Verify ownership records in your smart contract. -- Access ownership information for NFTs. - -## Best Practices - -- Ensure the `asset-identifier` is correctly formatted and exists. -- Use meaningful variable names for better readability. -- Combine with other NFT functions for comprehensive NFT management. -- Handle the `none` case to avoid runtime errors. - -## Practical Example: Retrieving NFT Owner - -Let's implement a function that retrieves the owner of an NFT: - -```clarity -(define-non-fungible-token Stackaroo (string-ascii 40)) - -(define-read-only (get-nft-owner (id (string-ascii 40))) - (nft-get-owner? Stackaroo id) -) - -;; Usage -(nft-mint? Stackaroo "Roo" tx-sender) ;; Returns (ok true) -(get-nft-owner "Roo") ;; Returns (some tx-sender) -(get-nft-owner "NonExistent") ;; Returns none -``` - -This example demonstrates: -1. Using `nft-get-owner?` to retrieve the owner of an NFT. -2. Implementing a read-only function to return the owner's principal. -3. Handling both the case where the NFT exists and where it does not. - -## Common Pitfalls - -1. Using `nft-get-owner?` with an incorrect or non-existent `asset-identifier`, causing the function to return `none`. -2. Assuming the NFT will always exist, leading to unhandled `none` cases. -3. Not handling all possible conditions, resulting in incomplete ownership checks. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `nft-mint?`: Mints a new non-fungible token. -- `nft-transfer?`: Transfers ownership of a non-fungible token. -- `nft-burn?`: Burns a non-fungible token. - -## Conclusion - -The `nft-get-owner?` function is a fundamental tool for retrieving the owner of non-fungible tokens in Clarity smart contracts. It allows you to access ownership information, verify ownership records, and implement logic based on NFT ownership. When used effectively, `nft-get-owner?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to manage NFT ownership. diff --git a/content/docs/stacks/clarity/functions/nft-mint.mdx b/content/docs/stacks/clarity/functions/nft-mint.mdx deleted file mode 100644 index 3a74ff510..000000000 --- a/content/docs/stacks/clarity/functions/nft-mint.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: nft-mint? -description: Mint a non-fungible token (NFT) in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(nft-mint? asset-class asset-identifier recipient) -``` - -- Input: `AssetName, A, principal` -- Output: `(response bool uint)` - -## Why it matters - -The `nft-mint?` function is crucial for: - -1. Creating new non-fungible tokens (NFTs). -2. Assigning ownership of newly created NFTs. -3. Ensuring data integrity by preventing duplicate NFT creation. -4. Simplifying the process of minting NFTs in smart contracts. - -## When to use it - -Use `nft-mint?` when you need to: - -- Create a new NFT. -- Assign ownership of a newly created NFT. -- Prevent duplicate NFT creation. -- Handle NFT minting operations in your smart contract. - -## Best Practices - -- Ensure the `asset-identifier` is unique and correctly formatted. -- Use meaningful variable names for better readability. -- Combine with other NFT functions for comprehensive NFT management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Minting an NFT - -Let's implement a function that mints a new NFT and assigns it to the recipient: - -```clarity -(define-non-fungible-token Stackaroo (string-ascii 40)) - -(define-public (mint-nft (id (string-ascii 40)) (recipient principal)) - (nft-mint? Stackaroo id recipient) -) - -;; Usage -(mint-nft "Roo" tx-sender) ;; Returns (ok true) -(mint-nft "Roo" tx-sender) ;; Returns (err u1) because the asset already exists -``` - -This example demonstrates: -1. Using `nft-mint?` to create a new NFT and assign it to the recipient. -2. Implementing a public function to handle the minting operation. -3. Handling both the successful mint and the case where the asset already exists. - -## Common Pitfalls - -1. Using `nft-mint?` with a non-unique `asset-identifier`, causing the operation to fail. -2. Assuming the NFT will always be minted, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete NFT management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `nft-get-owner?`: Retrieves the owner of a non-fungible token. -- `nft-transfer?`: Transfers ownership of a non-fungible token. -- `nft-burn?`: Burns a non-fungible token. - -## Conclusion - -The `nft-mint?` function is a fundamental tool for creating non-fungible tokens in Clarity smart contracts. It allows you to mint new NFTs, assign ownership, and ensure data integrity by preventing duplicate NFT creation. When used effectively, `nft-mint?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to manage NFT minting operations. diff --git a/content/docs/stacks/clarity/functions/nft-transfer.mdx b/content/docs/stacks/clarity/functions/nft-transfer.mdx deleted file mode 100644 index 38dd17820..000000000 --- a/content/docs/stacks/clarity/functions/nft-transfer.mdx +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: nft-transfer? -description: Transfer ownership of a non-fungible token (NFT) in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(nft-transfer? asset-class asset-identifier sender recipient) -``` - -- Input: `AssetName, A, principal, principal` -- Output: `(response bool uint)` - -## Why it matters - -The `nft-transfer?` function is crucial for: - -1. Changing the ownership of a non-fungible token (NFT). -2. Implementing logic that depends on the transfer of NFTs. -3. Ensuring data integrity by updating ownership records. -4. Simplifying the process of transferring NFTs in smart contracts. - -## When to use it - -Use `nft-transfer?` when you need to: - -- Change the ownership of an NFT. -- Implement logic that depends on the transfer of NFTs. -- Update ownership records in your smart contract. -- Handle NFT transfer operations. - -## Best Practices - -- Ensure the `sender` principal owns the NFT before attempting to transfer it. -- Ensure the `sender` and `recipient` are different principals. -- Use meaningful variable names for better readability. -- Combine with other NFT functions for comprehensive NFT management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Transferring an NFT - -Let's implement a function that transfers an NFT from the sender to the recipient: - -```clarity -(define-non-fungible-token Stackaroo (string-ascii 40)) - -(define-public (transfer-nft (id (string-ascii 40)) (recipient principal)) - (nft-transfer? Stackaroo id tx-sender recipient) -) - -;; Usage -(nft-mint? Stackaroo "Roo" tx-sender) ;; Returns (ok true) -(transfer-nft "Roo" 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) -(nft-transfer? Stackaroo "Roo" tx-sender 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u1) because the sender no longer owns the asset -(nft-transfer? Stackaroo "NonExistent" tx-sender 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (err u2) because the asset does not exist -``` - -This example demonstrates: -1. Using `nft-transfer?` to transfer an NFT from the sender to the recipient. -2. Implementing a public function to handle the transfer operation. -3. Handling both the successful transfer and the case where the sender no longer owns the asset. -4. Handling the case where the asset does not exist. - -## Common Pitfalls - -1. Using `nft-transfer?` without ensuring the `sender` owns the NFT, causing the operation to fail. -2. Assuming the `sender` and `recipient` are the same principal, leading to an invalid transfer. -3. Not handling all possible conditions, resulting in incomplete NFT management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `nft-mint?`: Mints a new non-fungible token. -- `nft-get-owner?`: Retrieves the owner of a non-fungible token. -- `nft-burn?`: Burns a non-fungible token. - -## Conclusion - -The `nft-transfer?` function is a fundamental tool for transferring ownership of non-fungible tokens in Clarity smart contracts. It allows you to change NFT ownership, implement transfer logic, and ensure data integrity. When used effectively, `nft-transfer?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle NFT transfer operations. diff --git a/content/docs/stacks/clarity/functions/not.mdx b/content/docs/stacks/clarity/functions/not.mdx deleted file mode 100644 index 975d8d679..000000000 --- a/content/docs/stacks/clarity/functions/not.mdx +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: not -description: Logical negation in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(not boolean-expression) -``` - -- Input: `bool` -- Output: `bool` - -## Why it matters - -The `not` function is crucial for: - -1. Implementing logical negation in conditional statements. -2. Simplifying the process of inverting boolean expressions. -3. Enhancing code readability and maintainability by abstracting logical negation. - -## When to use it - -Use `not` when you need to: - -- Invert a boolean expression. -- Implement logical negation in conditional statements. -- Simplify and abstract the process of inverting boolean values. - -## Best Practices - -- Ensure the input is a boolean expression. -- Use meaningful variable names for better readability. -- Combine with other logical functions for comprehensive boolean logic. -- Be aware of the performance implications of complex logical operations. - -## Practical Example: Inverting a Boolean Expression - -Let's implement a function that checks if a number is not zero: - -```clarity -(define-read-only (is-not-zero (n int)) - (not (is-eq n 0)) -) - -;; Usage -(is-not-zero 5) ;; Returns true -(is-not-zero 0) ;; Returns false -``` - -This example demonstrates: -1. Using `not` to invert the result of a boolean expression. -2. Implementing a read-only function to check if a number is not zero. -3. Handling both true and false cases. - -## Common Pitfalls - -1. Using `not` with non-boolean expressions, causing type errors. -2. Assuming the result will always be true or false, leading to incorrect logic. -3. Not handling all possible conditions, resulting in incomplete boolean logic. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `and`: Logical conjunction of multiple boolean expressions. -- `or`: Logical disjunction of multiple boolean expressions. -- `is-eq`: Checks if two values are equal. - -## Conclusion - -The `not` function is a fundamental tool for implementing logical negation in Clarity smart contracts. It allows you to invert boolean expressions, enabling robust and comprehensive boolean logic. When used effectively, `not` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to manage logical negation. diff --git a/content/docs/stacks/clarity/functions/ok.mdx b/content/docs/stacks/clarity/functions/ok.mdx deleted file mode 100644 index 9832cfd10..000000000 --- a/content/docs/stacks/clarity/functions/ok.mdx +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: ok -description: Construct a successful response type in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(ok value) -``` - -- Input: `A` -- Output: `(response A B)` - -## Why it matters - -The `ok` function is crucial for: - -1. Constructing a successful response type. -2. Indicating that a function executed successfully. -3. Ensuring data integrity by clearly distinguishing between success and error states. -4. Simplifying the process of handling function return values in smart contracts. - -## When to use it - -Use `ok` when you need to: - -- Construct a successful response type. -- Indicate that a function executed successfully. -- Clearly distinguish between success and error states. -- Handle function return values in your smart contract. - -## Best Practices - -- Ensure the value passed to `ok` is the intended successful result. -- Use meaningful variable names for better readability. -- Combine with `err` for comprehensive response handling. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Returning a Successful Response - -Let's implement a function that returns a successful response with a value: - -```clarity -(define-read-only (get-successful-response (value int)) - (ok value) -) - -;; Usage -(get-successful-response 5) ;; Returns (ok 5) -``` - -This example demonstrates: -1. Using `ok` to construct a successful response type. -2. Implementing a read-only function to return a successful response. -3. Handling the successful response case. - -## Common Pitfalls - -1. Using `ok` with an incorrect or invalid value, causing unexpected behavior. -2. Assuming the response will always be successful, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete response handling. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `err`: Constructs an error response type. -- `match`: Handles different branches or cases for optional and response types. - -## Conclusion - -The `ok` function is a fundamental tool for constructing successful response types in Clarity smart contracts. It allows you to indicate successful function execution, ensure data integrity, and simplify response handling. When used effectively, `ok` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle successful responses. diff --git a/content/docs/stacks/clarity/functions/or.mdx b/content/docs/stacks/clarity/functions/or.mdx deleted file mode 100644 index 11692b683..000000000 --- a/content/docs/stacks/clarity/functions/or.mdx +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: or -description: Logical disjunction in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(or b1 b2 ...) -``` - -- Input: `bool, ...` -- Output: `bool` - -## Why it matters - -The `or` function is crucial for: - -1. Implementing logical disjunction in conditional statements. -2. Simplifying the process of evaluating multiple boolean expressions. -3. Enhancing code readability and maintainability by abstracting logical disjunction. - -## When to use it - -Use `or` when you need to: - -- Evaluate multiple boolean expressions and return `true` if any are `true`. -- Implement logical disjunction in conditional statements. -- Simplify and abstract the process of evaluating multiple boolean values. - -## Best Practices - -- Ensure all inputs are boolean expressions. -- Use meaningful variable names for better readability. -- Combine with other logical functions for comprehensive boolean logic. -- Be aware of the performance implications of complex logical operations. - -## Practical Example: Evaluating Multiple Conditions - -Let's implement a function that checks if a number is either zero or negative: - -```clarity -(define-read-only (is-zero-or-negative (n int)) - (or (is-eq n 0) (< n 0)) -) - -;; Usage -(is-zero-or-negative 5) ;; Returns false -(is-zero-or-negative 0) ;; Returns true -(is-zero-or-negative -3) ;; Returns true -``` - -This example demonstrates: -1. Using `or` to evaluate multiple boolean expressions. -2. Implementing a read-only function to check if a number is either zero or negative. -3. Handling both true and false cases. - -## Common Pitfalls - -1. Using `or` with non-boolean expressions, causing type errors. -2. Assuming the result will always be true or false, leading to incorrect logic. -3. Not handling all possible conditions, resulting in incomplete boolean logic. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `and`: Logical conjunction of multiple boolean expressions. -- `not`: Logical negation of a boolean expression. -- `is-eq`: Checks if two values are equal. - -## Conclusion - -The `or` function is a fundamental tool for implementing logical disjunction in Clarity smart contracts. It allows you to evaluate multiple boolean expressions, enabling robust and comprehensive boolean logic. When used effectively, `or` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to manage logical disjunction. diff --git a/content/docs/stacks/clarity/functions/pow.mdx b/content/docs/stacks/clarity/functions/pow.mdx deleted file mode 100644 index e0a2f06e4..000000000 --- a/content/docs/stacks/clarity/functions/pow.mdx +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: pow -description: Calculate the power of a number in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(pow base exponent) -``` - -- Input: `int, int | uint, uint` -- Output: `int | uint` - -## Why it matters - -The `pow` function is crucial for: - -1. Performing exponentiation operations. -2. Implementing logic that depends on power calculations. -3. Simplifying the process of raising numbers to a power. -4. Enhancing code readability and maintainability by abstracting exponentiation. - -## When to use it - -Use `pow` when you need to: - -- Perform exponentiation operations. -- Implement logic that depends on power calculations. -- Raise numbers to a power. -- Simplify and abstract exponentiation operations. - -## Best Practices - -- Ensure the base and exponent are correctly formatted and within acceptable ranges. -- Use meaningful variable names for better readability. -- Combine with other mathematical functions for comprehensive calculations. -- Be aware of the performance implications of large exponentiation operations. - -## Practical Example: Calculating Token Balances in Decimal Format - -Let's implement a function that calculates the power of a number, specifically for converting integer representations of tokens or uStx: - -```clarity -(define-constant MICRO_TOKENS (pow u10 u6)) ;; 6 decimal places -(define-data-var userBalance uint u100) ;; Amount reprented in a clear and readable format - -(define-read-only (get-total-micro-balance (userAddress principal)) - (* (var-get userBalance) MICRO_TOKENS) -) - -;; Usage -(get-total-micro-balance tx-sender) -``` - -This example demonstrates: -1. Using `pow` to define a constant for micro tokens with 6 decimal places. -2. Implementing a read-only function to calculate the total balance in decimal format. -3. Handling balances from different versions of a token contract. - -## Common Pitfalls - -1. Using `pow` with negative exponents, which is not supported and will cause a runtime error. -2. Assuming the result will always be within acceptable ranges, leading to overflow errors. -3. Not handling all possible conditions, resulting in incomplete calculations. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `*`: Multiplies two or more numbers. -- `+`: Adds two or more numbers. -- `-`: Subtracts one number from another. -- `/`: Divides one number by another. - -## Conclusion - -The `pow` function is a fundamental tool for performing exponentiation in Clarity smart contracts. It allows you to raise numbers to a power, enabling robust and comprehensive mathematical operations. When used effectively, `pow` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to manage power calculations. diff --git a/content/docs/stacks/clarity/functions/principal-construct.mdx b/content/docs/stacks/clarity/functions/principal-construct.mdx deleted file mode 100644 index fd875af35..000000000 --- a/content/docs/stacks/clarity/functions/principal-construct.mdx +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: principal-construct? -description: Construct a principal in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(principal-construct? version-byte hash-bytes [contract-name]) -``` - -- Input: `(buff 1), (buff 20), [(string-ascii 40)]` -- Output: `(response principal { error_code: uint, principal: (optional principal) })` - -## Why it matters - -The `principal-construct?` function is crucial for: - -1. Creating standard or contract principals. -2. Managing identities and permissions in smart contracts. -3. Ensuring data integrity by validating principal construction. -4. Simplifying the process of creating principals in smart contracts. - -## When to use it - -Use `principal-construct?` when you need to: - -- Create a standard or contract principal. -- Manage identities and permissions in your smart contract. -- Validate the construction of principals. -- Handle principal creation operations. - -## Best Practices - -- Ensure the `version-byte` and `hash-bytes` are correctly formatted. -- Use meaningful variable names for better readability. -- Combine with other principal functions for comprehensive identity management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Constructing a Principal - -Let's implement a function that constructs a standard principal: - -```clarity -(define-public (create-standard-principal (versionByte (buff 1)) (hashBytes (buff 20))) - (principal-construct? versionByte hashBytes) -) - -;; Usage -(create-standard-principal 0x1a 0xfa6bf38ed557fe417333710d6033e9419391a320) ;; Returns (ok 'ST3X6QWWETNBZWGBK6DRGTR1KX50S74D3425Q1TPK) -``` - -This example demonstrates: -1. Using `principal-construct?` to create a standard principal. -2. Implementing a public function to handle the principal construction. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `principal-construct?` with incorrectly formatted `versionByte` or `hashBytes`, causing the operation to fail. -2. Assuming the principal will always be valid, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete principal management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `principal-of?`: Returns the principal derived from a public key. -- `contract-caller`: Returns the caller of the current contract context. -- `tx-sender`: Returns the sender of the current transaction. - -## Conclusion - -The `principal-construct?` function is a fundamental tool for creating principals in Clarity smart contracts. It allows you to manage identities and permissions, ensuring data integrity and simplifying principal creation. When used effectively, `principal-construct?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle principal construction operations. diff --git a/content/docs/stacks/clarity/functions/principal-destruct.mdx b/content/docs/stacks/clarity/functions/principal-destruct.mdx deleted file mode 100644 index cbfc5e028..000000000 --- a/content/docs/stacks/clarity/functions/principal-destruct.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: principal-destruct? -description: Decompose a principal into its components in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(principal-destruct? principal-address) -``` - -- Input: `principal` -- Output: `(response (tuple (hash-bytes (buff 20)) (name (optional (string-ascii 40))) (version (buff 1))) (tuple (hash-bytes (buff 20)) (name (optional (string-ascii 40))) (version (buff 1)))` - -## Why it matters - -The `principal-destruct?` function is crucial for: - -1. Decomposing a principal into its component parts. -2. Managing identities and permissions in smart contracts. -3. Ensuring data integrity by validating principal components. -4. Simplifying the process of handling principals in smart contracts. - -## When to use it - -Use `principal-destruct?` when you need to: - -- Decompose a principal into its component parts. -- Manage identities and permissions in your smart contract. -- Validate the components of a principal. -- Handle principal decomposition operations. - -## Best Practices - -- Ensure the `principal` is correctly formatted. -- Use meaningful variable names for better readability. -- Combine with other principal functions for comprehensive identity management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Decomposing a Principal - -Let's implement a function that destructs a principal back into its components: - -```clarity -(define-public (destruct-principal (principal principal)) - (principal-destruct? principal) -) - -;; Usage -(destruct-principal 'ST3X6QWWETNBZWGBK6DRGTR1KX50S74D3425Q1TPK) -;; Returns (ok (tuple (hash-bytes 0xfa6bf38ed557fe417333710d6033e9419391a320) (name none) (version 0x1a))) -(destruct-principal 'ST3X6QWWETNBZWGBK6DRGTR1KX50S74D3425Q1TPK.foo) -;; Returns (ok (tuple (hash-bytes 0xfa6bf38ed557fe417333710d6033e9419391a320) (name (some "foo")) (version 0x1a))) -``` - -This example demonstrates: -1. Using `principal-destruct?` to decompose a principal into its components. -2. Implementing a public function to handle the principal decomposition. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `principal-destruct?` with incorrectly formatted principals, causing the operation to fail. -2. Assuming the principal will always be valid, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete principal management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `principal-construct?`: Constructs a principal from its components. -- `principal-of?`: Returns the principal derived from a public key. -- `contract-caller`: Returns the caller of the current contract context. - -## Conclusion - -The `principal-destruct?` function is a fundamental tool for decomposing principals into their component parts in Clarity smart contracts. It allows you to manage identities and permissions, ensuring data integrity and simplifying principal handling. When used effectively, `principal-destruct?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle principal decomposition operations. diff --git a/content/docs/stacks/clarity/functions/principal-of.mdx b/content/docs/stacks/clarity/functions/principal-of.mdx deleted file mode 100644 index 549b9cad0..000000000 --- a/content/docs/stacks/clarity/functions/principal-of.mdx +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: principal-of? -description: Derive a principal from a public key in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(principal-of? public-key) -``` - -- Input: `(buff 33)` -- Output: `(response principal uint)` - -## Why it matters - -The `principal-of?` function is crucial for: - -1. Deriving a principal from a public key. -2. Managing identities and permissions in smart contracts. -3. Ensuring data integrity by validating public key to principal conversion. -4. Simplifying the process of handling principals derived from public keys. - -## When to use it - -Use `principal-of?` when you need to: - -- Derive a principal from a public key. -- Manage identities and permissions in your smart contract. -- Validate the conversion of a public key to a principal. -- Handle principal derivation operations. - -## Best Practices - -- Ensure the `public-key` is correctly formatted and valid. -- Use meaningful variable names for better readability. -- Combine with other principal functions for comprehensive identity management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Deriving a Principal - -Let's implement a function that derives a principal from a public key: - -```clarity -(define-public (derive-principal (public-key (buff 33))) - (principal-of? public-key) -) - -;; Usage -(derive-principal 0x0390a5cac7c33fda49f70bc1b0866fa0ba7a9440d9de647fecb8132ceb76a94dfa) ;; Returns (ok 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM) -``` - -This example demonstrates: -1. Using `principal-of?` to derive a principal from a public key. -2. Implementing a public function to handle the principal derivation. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `principal-of?` with an incorrectly formatted or invalid `public-key`, causing the operation to fail. -2. Assuming the principal will always be valid, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete principal management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `principal-construct?`: Constructs a principal from its components. -- `principal-destruct?`: Decomposes a principal into its components. -- `contract-caller`: Returns the caller of the current contract context. - -## Conclusion - -The `principal-of?` function is a fundamental tool for deriving principals from public keys in Clarity smart contracts. It allows you to manage identities and permissions, ensuring data integrity and simplifying principal handling. When used effectively, `principal-of?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle principal derivation operations. diff --git a/content/docs/stacks/clarity/functions/print.mdx b/content/docs/stacks/clarity/functions/print.mdx deleted file mode 100644 index 8e19d7106..000000000 --- a/content/docs/stacks/clarity/functions/print.mdx +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: print -description: Evaluate and printing expressions in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(print expr) -``` - -- Input: `A` -- Output: `A` - -## Why it matters - -The `print` function is crucial for: - -1. Debugging and logging expressions during contract development. -2. Evaluating and returning the input expression. -3. Enhancing code readability and maintainability by providing a way to output intermediate values. - -## When to use it - -Use `print` when you need to: - -- Debug and log expressions during contract development. -- Evaluate and return an input expression. -- Output intermediate values for better understanding of contract behavior. - -## Best Practices - -- Use `print` primarily for debugging and development purposes. -- Ensure that the expression passed to `print` is meaningful and necessary for debugging. -- Remove or comment out `print` statements in production code to avoid unnecessary output. - -## Practical Example: Printing an Expression - -Let's implement a function that prints the result of an addition operation: - -```clarity -(define-read-only (add-and-print (a int) (b int)) - (print (+ a b)) -) - -;; Usage -(add-and-print 3 4) ;; Prints 7 and returns 7 -(add-and-print 10 20) ;; Prints 30 and returns 30 -``` - -This example demonstrates: -1. Using `print` to output the result of an addition operation. -2. Implementing a public function to handle the addition and printing. -3. Handling both small and large input values. - -## Common Pitfalls - -1. Using `print` excessively, leading to cluttered output and reduced readability. -2. Assuming `print` is necessary for all expressions, leading to overuse. -3. Not removing or commenting out `print` statements in production code, resulting in unnecessary output. - -## Related Functions - -- `+`: Adds two or more numbers. -- `-`: Subtracts one number from another. -- `*`: Multiplies two or more numbers. -- `/`: Divides one number by another. - -## Conclusion - -The `print` function is a fundamental tool for debugging and logging expressions in Clarity smart contracts. It allows you to evaluate and return input expressions, providing a way to output intermediate values for better understanding of contract behavior. When used effectively, `print` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to debug and log expressions. diff --git a/content/docs/stacks/clarity/functions/replace-at.mdx b/content/docs/stacks/clarity/functions/replace-at.mdx deleted file mode 100644 index 867ea27b7..000000000 --- a/content/docs/stacks/clarity/functions/replace-at.mdx +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: replace-at? -description: Replace an element at a specific index in a sequence in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(replace-at? sequence index new-element) -``` - -- Input: `sequence_A, uint, A` -- Output: `(response sequence_A uint)` - -## Why it matters - -The `replace-at?` function is crucial for: - -1. Modifying elements in a sequence at a specific index. -2. Implementing logic that requires updating sequences. -3. Ensuring data integrity by validating index and element replacement. -4. Simplifying the process of handling sequence modifications in smart contracts. - -## When to use it - -Use `replace-at?` when you need to: - -- Modify an element in a sequence at a specific index. -- Implement logic that requires updating sequences. -- Validate the index and element replacement in your smart contract. -- Handle sequence modification operations. - -## Best Practices - -- Ensure the `index` is within the bounds of the sequence. -- Use meaningful variable names for better readability. -- Combine with other sequence functions for comprehensive sequence management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Replacing an Element in a List - -Let's implement a function that replaces an element in a list at a specific index: - -```clarity -(define-read-only (replace-element (items (list 5 int)) (index uint) (newElement int)) - (replace-at? items index newElement) -) - -;; Usage -(replace-element (list 1 2 3 4 5) u2 10) ;; Returns (some (list (1 2 10 4 5))) -(replace-element (list 1 2 3 4 5) u5 10) ;; Returns (none) because the index is out of bounds -``` - -This example demonstrates: -1. Using `replace-at?` to modify an element in a list at a specific index. -2. Implementing a public function to handle the element replacement. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `replace-at?` with an index that is out of bounds, causing the operation to fail. -2. Assuming the sequence will always be valid, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete sequence management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `append`: Adds an element to the end of a list. -- `index-of?`: Returns the first index at which an item can be found in a sequence. -- `get`: Retrieves an element from a sequence at a specific index. - -## Conclusion - -The `replace-at?` function is a fundamental tool for modifying elements in sequences in Clarity smart contracts. It allows you to update sequences, ensuring data integrity and simplifying sequence handling. When used effectively, `replace-at?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle sequence modification operations. diff --git a/content/docs/stacks/clarity/functions/secp256k1-recover.mdx b/content/docs/stacks/clarity/functions/secp256k1-recover.mdx deleted file mode 100644 index 143ef8655..000000000 --- a/content/docs/stacks/clarity/functions/secp256k1-recover.mdx +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: secp256k1-recover? -description: Recover the public key from a message hash and signature in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(secp256k1-recover? message-hash signature) -``` - -- Input: `(buff 32), (buff 65)` -- Output: `(response (buff 33) uint)` - -## Why it matters - -The `secp256k1-recover?` function is crucial for: - -1. Verifying the authenticity of a message by recovering the public key from a signature. -2. Implementing cryptographic verification in smart contracts. -3. Ensuring data integrity by validating signatures. -4. Simplifying the process of handling cryptographic operations in smart contracts. - -## When to use it - -Use `secp256k1-recover?` when you need to: - -- Verify the authenticity of a message by recovering the public key from a signature. -- Implement cryptographic verification in your smart contract. -- Validate signatures to ensure data integrity. -- Handle cryptographic operations. - -## Best Practices - -- Ensure the `message-hash` and `signature` are correctly formatted and valid. -- Use meaningful variable names for better readability. -- Combine with other cryptographic functions for comprehensive security management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Recovering a Public Key - -Let's implement a function that recovers the public key from a message hash and signature: - -```clarity -(define-read-only (recover-public-key (messageHash (buff 32)) (signature (buff 65))) - (secp256k1-recover? messageHash signature) -) - -;; Usage -(recover-public-key 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301) -;; Returns (ok 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) -``` - -This example demonstrates: -1. Using `secp256k1-recover?` to recover a public key from a message hash and signature. -2. Implementing a public function to handle the public key recovery. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `secp256k1-recover?` with incorrectly formatted or invalid `message-hash` or `signature`, causing the operation to fail. -2. Assuming the public key will always be valid, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete cryptographic verification. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `principal-of?`: Returns the principal derived from a public key. -- `hash160`: Computes the RIPEMD-160 hash of the SHA-256 hash of the input. -- `sha256`: Computes the SHA-256 hash of the input. - -## Conclusion - -The `secp256k1-recover?` function is a fundamental tool for recovering public keys from message hashes and signatures in Clarity smart contracts. It allows you to verify the authenticity of messages, ensuring data integrity and simplifying cryptographic operations. When used effectively, `secp256k1-recover?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle cryptographic verification. diff --git a/content/docs/stacks/clarity/functions/secp256k1-verify.mdx b/content/docs/stacks/clarity/functions/secp256k1-verify.mdx deleted file mode 100644 index 80192fe80..000000000 --- a/content/docs/stacks/clarity/functions/secp256k1-verify.mdx +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: secp256k1-verify -description: Verify a signature against a message hash and public key in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(secp256k1-verify message-hash signature public-key) -``` - -- Input: `(buff 32), (buff 64) | (buff 65), (buff 33)` -- Output: `bool` - -## Why it matters - -The `secp256k1-verify` function is crucial for: - -1. Verifying the authenticity of a message by checking the signature against the public key. -2. Implementing cryptographic verification in smart contracts. -3. Ensuring data integrity by validating signatures. -4. Simplifying the process of handling cryptographic operations in smart contracts. - -## When to use it - -Use `secp256k1-verify` when you need to: - -- Verify the authenticity of a message by checking the signature against the public key. -- Implement cryptographic verification in your smart contract. -- Validate signatures to ensure data integrity. -- Handle cryptographic operations. - -## Best Practices - -- Ensure the `message-hash`, `signature`, and `public-key` are correctly formatted and valid. -- Use meaningful variable names for better readability. -- Combine with other cryptographic functions for comprehensive security management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Verifying a Signature - -Let's implement a function that verifies a signature against a message hash and public key: - -```clarity -(define-read-only (verify-signature (messageHash (buff 32)) (signature (buff 65)) (publicKey (buff 33))) - (secp256k1-verify messageHash signature publicKey) -) - -;; Usage -(verify-signature 0xde5b9eb9e7c5592930eb2e30a01369c36586d872082ed8181ee83d2a0ec20f04 0x8738487ebe69b93d8e51583be8eee50bb4213fc49c767d329632730cc193b873554428fc936ca3569afc15f1c9365f6591d6251a89fee9c9ac661116824d3a1301 0x03adb8de4bfb65db2cfd6120d55c6526ae9c52e675db7e47308636534ba7786110) -;; Returns true -``` - -This example demonstrates: -1. Using `secp256k1-verify` to verify a signature against a message hash and public key. -2. Implementing a public function to handle the signature verification. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `secp256k1-verify` with incorrectly formatted or invalid `message-hash`, `signature`, or `public-key`, causing the operation to fail. -2. Assuming the verification will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete cryptographic verification. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `secp256k1-recover?`: Recovers the public key from a message hash and signature. -- `sha256`: Computes the SHA-256 hash of the input. -- `hash160`: Computes the RIPEMD-160 hash of the SHA-256 hash of the input. - -## Conclusion - -The `secp256k1-verify` function is a fundamental tool for verifying signatures against message hashes and public keys in Clarity smart contracts. It allows you to ensure data integrity and simplify cryptographic operations. When used effectively, `secp256k1-verify` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle cryptographic verification. diff --git a/content/docs/stacks/clarity/functions/sha256.mdx b/content/docs/stacks/clarity/functions/sha256.mdx deleted file mode 100644 index 3f4cb486f..000000000 --- a/content/docs/stacks/clarity/functions/sha256.mdx +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: sha256 -description: Compute the SHA-256 hash of a value in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(sha256 value) -``` - -- Input: `buff | uint | int` -- Output: `(buff 32)` - -## Why it matters - -The `sha256` function is crucial for: - -1. Computing the SHA-256 hash of a given value. -2. Implementing cryptographic operations in smart contracts. -3. Ensuring data integrity by generating unique hashes. -4. Simplifying the process of handling cryptographic hashing in smart contracts. - -## When to use it - -Use `sha256` when you need to: - -- Compute the SHA-256 hash of a given value. -- Implement cryptographic operations in your smart contract. -- Generate unique hashes to ensure data integrity. -- Handle cryptographic hashing operations. - -## Best Practices - -- Ensure the input value is correctly formatted and valid. -- Use meaningful variable names for better readability. -- Combine with other cryptographic functions for comprehensive security management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Computing a SHA-256 Hash - -Let's implement a function that computes the SHA-256 hash of a given buffer: - -```clarity -(define-read-only (compute-sha256 (input (buff 32))) - (sha256 input) -) - -;; Usage -(compute-sha256 0x68656c6c6f20776f726c64000000000000000000000000000000000000000000) -;; Returns 0x28effae679c457da1e5158c063b3dfa78d0ade721b9aa9f1fc3f46dba4c0ea15 -``` - -This example demonstrates: -1. Using `sha256` to compute the hash of a given buffer. -2. Implementing a public function to handle the hash computation. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `sha256` with incorrectly formatted or invalid input values, causing the operation to fail. -2. Assuming the hash will always be valid, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete cryptographic hashing. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `sha512`: Computes the SHA-512 hash of the input. -- `sha512/256`: Computes the SHA-512/256 hash of the input. -- `keccak256`: Computes the KECCAK-256 hash of the input. - -## Conclusion - -The `sha256` function is a fundamental tool for computing SHA-256 hashes in Clarity smart contracts. It allows you to implement cryptographic operations, ensuring data integrity and simplifying cryptographic hashing. When used effectively, `sha256` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle cryptographic hashing operations. diff --git a/content/docs/stacks/clarity/functions/sha512-256.mdx b/content/docs/stacks/clarity/functions/sha512-256.mdx deleted file mode 100644 index 45cdec7b3..000000000 --- a/content/docs/stacks/clarity/functions/sha512-256.mdx +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: sha512/256 -description: Compute the SHA-512/256 hash of a value in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(sha512/256 value) -``` - -- Input: `buff | uint | int` -- Output: `(buff 32)` - -## Why it matters - -The `sha512/256` function is crucial for: - -1. Computing the SHA-512/256 hash of a given value. -2. Implementing cryptographic operations in smart contracts. -3. Ensuring data integrity by generating unique hashes. -4. Simplifying the process of handling cryptographic hashing in smart contracts. - -## When to use it - -Use `sha512/256` when you need to: - -- Compute the SHA-512/256 hash of a given value. -- Implement cryptographic operations in your smart contract. -- Generate unique hashes to ensure data integrity. -- Handle cryptographic hashing operations. - -## Best Practices - -- Ensure the input value is correctly formatted and valid. -- Use meaningful variable names for better readability. -- Combine with other cryptographic functions for comprehensive security management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Computing a SHA-512/256 Hash - -Let's implement a function that computes the SHA-512/256 hash of a given buffer: - -```clarity -(define-read-only (compute-sha512-256 (input (buff 32))) - (sha512/256 input) -) - -;; Usage -(compute-sha512-256 0x68656c6c6f20776f726c64000000000000000000000000000000000000000000) -;; Returns 0xcf0edb437886eae39b21ebad0caeea342d2bd61c98e9d09d0e89109a546d01fc -``` - -This example demonstrates: -1. Using `sha512/256` to compute the hash of a given buffer. -2. Implementing a public function to handle the hash computation. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `sha512/256` with incorrectly formatted or invalid input values, causing the operation to fail. -2. Assuming the hash will always be valid, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete cryptographic hashing. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `sha256`: Computes the SHA-256 hash of the input. -- `sha512`: Computes the SHA-512 hash of the input. -- `keccak256`: Computes the KECCAK-256 hash of the input. - -## Conclusion - -The `sha512/256` function is a fundamental tool for computing SHA-512/256 hashes in Clarity smart contracts. It allows you to implement cryptographic operations, ensuring data integrity and simplifying cryptographic hashing. When used effectively, `sha512/256` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle cryptographic hashing operations. diff --git a/content/docs/stacks/clarity/functions/sha512.mdx b/content/docs/stacks/clarity/functions/sha512.mdx deleted file mode 100644 index 829c2b33c..000000000 --- a/content/docs/stacks/clarity/functions/sha512.mdx +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: sha512 -description: Compute the SHA-512 hash of a value in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(sha512 value) -``` - -- Input: `buff | uint | int` -- Output: `(buff 64)` - -## Why it matters - -The `sha512` function is crucial for: - -1. Computing the SHA-512 hash of a given value. -2. Implementing cryptographic operations in smart contracts. -3. Ensuring data integrity by generating unique hashes. -4. Simplifying the process of handling cryptographic hashing in smart contracts. - -## When to use it - -Use `sha512` when you need to: - -- Compute the SHA-512 hash of a given value. -- Implement cryptographic operations in your smart contract. -- Generate unique hashes to ensure data integrity. -- Handle cryptographic hashing operations. - -## Best Practices - -- Ensure the input value is correctly formatted and valid. -- Use meaningful variable names for better readability. -- Combine with other cryptographic functions for comprehensive security management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Computing a SHA-512 Hash - -Let's implement a function that computes the SHA-512 hash of a given buffer: - -```clarity -(define-read-only (compute-sha512 (input (buff 32))) - (sha512 input) -) - -;; Usage -(compute-sha512 0x68656c6c6f20776f726c64000000000000000000000000000000000000000000) -;; Returns 0x638f0da7489fae1f981a47199a2854d0fa117cea82bd86049930aa86e565c6cdccd52fc0e6bba5a135961ed5b7360d5e2b0ff65889acbac01361f5e291a6da45 -``` - -This example demonstrates: -1. Using `sha512` to compute the hash of a given buffer. -2. Implementing a public function to handle the hash computation. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `sha512` with incorrectly formatted or invalid input values, causing the operation to fail. -2. Assuming the hash will always be valid, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete cryptographic hashing. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `sha256`: Computes the SHA-256 hash of the input. -- `sha512/256`: Computes the SHA-512/256 hash of the input. -- `keccak256`: Computes the KECCAK-256 hash of the input. - -## Conclusion - -The `sha512` function is a fundamental tool for computing SHA-512 hashes in Clarity smart contracts. It allows you to implement cryptographic operations, ensuring data integrity and simplifying cryptographic hashing. When used effectively, `sha512` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle cryptographic hashing operations. diff --git a/content/docs/stacks/clarity/functions/slice.mdx b/content/docs/stacks/clarity/functions/slice.mdx deleted file mode 100644 index 5a74dfb69..000000000 --- a/content/docs/stacks/clarity/functions/slice.mdx +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: slice? -description: Extract a sub-sequence from a sequence in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(slice? sequence left-position right-position) -``` - -- Input: `sequence_A, uint, uint` -- Output: `(optional sequence_A)` - -## Why it matters - -The `slice?` function is crucial for: - -1. Extracting sub-sequences from sequences. -2. Implementing logic that requires partial data extraction. -3. Ensuring data integrity by validating indices for slicing. -4. Simplifying the process of handling sub-sequence extraction in smart contracts. - -## When to use it - -Use `slice?` when you need to: - -- Extract a sub-sequence from a sequence. -- Implement logic that requires partial data extraction. -- Validate indices for slicing to ensure data integrity. -- Handle sub-sequence extraction operations. - -## Best Practices - -- Ensure the `left-position` and `right-position` are within the bounds of the sequence. -- Use meaningful variable names for better readability. -- Combine with other sequence functions for comprehensive sequence management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Extracting a Sub-sequence from a String - -Let's implement a function that extracts a sub-sequence from a string: - -```clarity -(define-read-only (extract-substring (input (string-ascii 20)) (start uint) (end uint)) - (slice? input start end) -) - -;; Usage -(extract-substring "blockstack" u5 u10) ;; Returns (some "stack") -(extract-substring "blockstack" u0 u5) ;; Returns (some "block") -(extract-substring "blockstack" u5 u15) ;; Returns none (out of bounds) -``` - -This example demonstrates: -1. Using `slice?` to extract a sub-sequence from a string. -2. Implementing a public function to handle the sub-sequence extraction. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `slice?` with indices that are out of bounds, causing the operation to fail. -2. Assuming the sub-sequence will always be valid, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete sequence management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `len`: Returns the length of a sequence. -- `concat`: Concatenates two sequences. -- `index-of?`: Returns the first index at which an item can be found in a sequence. - -## Conclusion - -The `slice?` function is a fundamental tool for extracting sub-sequences in Clarity smart contracts. It allows you to implement logic that requires partial data extraction, ensuring data integrity and simplifying sequence handling. When used effectively, `slice?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle sub-sequence extraction operations. diff --git a/content/docs/stacks/clarity/functions/some.mdx b/content/docs/stacks/clarity/functions/some.mdx deleted file mode 100644 index 46e8f191b..000000000 --- a/content/docs/stacks/clarity/functions/some.mdx +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: some -description: Construct an optional type from a value in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(some value) -``` - -- Input: `A` -- Output: `(optional A)` - -## Why it matters - -The `some` function is crucial for: - -1. Constructing an optional type from a given value. -2. Implementing logic that requires optional types. -3. Ensuring data integrity by explicitly handling optional values. -4. Simplifying the process of working with optional types in smart contracts. - -## When to use it - -Use `some` when you need to: - -- Construct an optional type from a given value. -- Implement logic that requires optional types. -- Explicitly handle optional values to ensure data integrity. -- Work with optional types in your smart contract. - -## Best Practices - -- Ensure the value passed to `some` is the intended value to be wrapped in an optional type. -- Use meaningful variable names for better readability. -- Combine with other optional functions for comprehensive optional type management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Constructing an Optional Type - -Let's implement a function that constructs an optional type from a given integer: - -```clarity -(define-read-only (wrap-in-optional (input int)) - (some input) -) - -;; Usage -(wrap-in-optional 42) ;; Returns (some 42) -(wrap-in-optional -1) ;; Returns (some -1) -``` - -This example demonstrates: -1. Using `some` to construct an optional type from a given integer. -2. Implementing a public function to handle the optional type construction. -3. Handling both positive and negative input values. - -## Common Pitfalls - -1. Using `some` without ensuring the value is the intended value to be wrapped, causing unexpected behavior. -2. Assuming the optional type will always be valid, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete optional type management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `is-some`: Checks if an optional type contains a value. -- `is-none`: Checks if an optional type is empty. -- `unwrap!`: Unwraps an optional type, returning the contained value or throwing an error if empty. - -## Conclusion - -The `some` function is a fundamental tool for constructing optional types in Clarity smart contracts. It allows you to implement logic that requires optional types, ensuring data integrity and simplifying optional type handling. When used effectively, `some` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle optional type construction. diff --git a/content/docs/stacks/clarity/functions/sqrti.mdx b/content/docs/stacks/clarity/functions/sqrti.mdx deleted file mode 100644 index f65282ae4..000000000 --- a/content/docs/stacks/clarity/functions/sqrti.mdx +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: sqrti -description: Calculate the integer square root of a number in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(sqrti n) -``` - -- Input: `int | uint` -- Output: `int | uint` - -## Why it matters - -The `sqrti` function is crucial for: - -1. Calculating the largest integer less than or equal to the square root of a number. -2. Implementing mathematical operations in smart contracts. -3. Ensuring data integrity by providing precise integer square root calculations. -4. Simplifying the process of handling square root operations in smart contracts. - -## When to use it - -Use `sqrti` when you need to: - -- Calculate the integer square root of a number. -- Implement mathematical operations in your smart contract. -- Ensure precise integer square root calculations. -- Handle square root operations. - -## Best Practices - -- Ensure the input value is non-negative to avoid runtime errors. -- Use meaningful variable names for better readability. -- Combine with other mathematical functions for comprehensive calculations. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Calculating Integer Square Roots - -Let's implement a function that calculates the integer square root of a given number: - -```clarity -(define-read-only (calculate-sqrti (input uint)) - (sqrti input) -) - -;; Usage -(calculate-sqrti u11) ;; Returns u3 -(calculate-sqrti u1000000) ;; Returns u1000 -(calculate-sqrti u1) ;; Returns u1 -(calculate-sqrti u0) ;; Returns u0 -``` - -This example demonstrates: -1. Using `sqrti` to calculate the integer square root of a given number. -2. Implementing a public function to handle the square root calculation. -3. Handling both small and large input values. - -## Common Pitfalls - -1. Using `sqrti` with negative numbers, causing the operation to fail. -2. Assuming the result will always be valid, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete mathematical operations. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `*`: Multiplies two or more numbers. -- `+`: Adds two or more numbers. -- `-`: Subtracts one number from another. -- `/`: Divides one number by another. - -## Conclusion - -The `sqrti` function is a fundamental tool for calculating integer square roots in Clarity smart contracts. It allows you to implement precise mathematical operations, ensuring data integrity and simplifying square root calculations. When used effectively, `sqrti` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle integer square root operations. diff --git a/content/docs/stacks/clarity/functions/string-to-int.mdx b/content/docs/stacks/clarity/functions/string-to-int.mdx deleted file mode 100644 index 5f70d513d..000000000 --- a/content/docs/stacks/clarity/functions/string-to-int.mdx +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: string-to-int? -description: Convert a string to an optional integer in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(string-to-int? string) -``` - -- Input: `(string-ascii 1048576) | (string-utf8 262144)` -- Output: `(optional int)` - -## Why it matters - -The `string-to-int?` function is crucial for: - -1. Converting string representations of numbers to integers. -2. Implementing logic that requires numeric values from string inputs. -3. Ensuring data integrity by validating string-to-integer conversions. -4. Simplifying the process of handling numeric conversions in smart contracts. - -## When to use it - -Use `string-to-int?` when you need to: - -- Convert a string representation of a number to an integer. -- Implement logic that requires numeric values from string inputs. -- Validate string-to-integer conversions to ensure data integrity. -- Handle numeric conversions in your smart contract. - -## Best Practices - -- Ensure the input string is correctly formatted and represents a valid integer. -- Use meaningful variable names for better readability. -- Combine with other string and numeric functions for comprehensive data management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Converting a String to an Integer - -Let's implement a function that converts a string to an optional integer: - -```clarity -(define-read-only (convert-string-to-int (input (string-ascii 20))) - (string-to-int? input) -) - -;; Usage -(convert-string-to-int "123") ;; Returns (some 123) -(convert-string-to-int "-456") ;; Returns (some -456) -(convert-string-to-int "abc") ;; Returns none -``` - -This example demonstrates: -1. Using `string-to-int?` to convert a string to an optional integer. -2. Implementing a public function to handle the string-to-integer conversion. -3. Handling both valid and invalid string inputs. - -## Common Pitfalls - -1. Using `string-to-int?` with incorrectly formatted or invalid string inputs, causing the operation to return `none`. -2. Assuming the conversion will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete data management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `string-to-uint?`: Converts a string to an optional unsigned integer. -- `int-to-ascii`: Converts an integer to a string-ascii representation. -- `int-to-utf8`: Converts an integer to a string-utf8 representation. - -## Conclusion - -The `string-to-int?` function is a fundamental tool for converting string representations of numbers to integers in Clarity smart contracts. It allows you to implement logic that requires numeric values from string inputs, ensuring data integrity and simplifying numeric conversions. When used effectively, `string-to-int?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle string-to-integer conversions. diff --git a/content/docs/stacks/clarity/functions/string-to-uint.mdx b/content/docs/stacks/clarity/functions/string-to-uint.mdx deleted file mode 100644 index b4ad00c60..000000000 --- a/content/docs/stacks/clarity/functions/string-to-uint.mdx +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: string-to-uint? -description: Convert a string to an optional unsigned integer in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(string-to-uint? string) -``` - -- Input: `(string-ascii 1048576) | (string-utf8 262144)` -- Output: `(optional uint)` - -## Why it matters - -The `string-to-uint?` function is crucial for: - -1. Converting string representations of numbers to unsigned integers. -2. Implementing logic that requires numeric values from string inputs. -3. Ensuring data integrity by validating string-to-unsigned-integer conversions. -4. Simplifying the process of handling numeric conversions in smart contracts. - -## When to use it - -Use `string-to-uint?` when you need to: - -- Convert a string representation of a number to an unsigned integer. -- Implement logic that requires numeric values from string inputs. -- Validate string-to-unsigned-integer conversions to ensure data integrity. -- Handle numeric conversions in your smart contract. - -## Best Practices - -- Ensure the input string is correctly formatted and represents a valid unsigned integer. -- Use meaningful variable names for better readability. -- Combine with other string and numeric functions for comprehensive data management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Converting a String to an Unsigned Integer - -Let's implement a function that converts a string to an optional unsigned integer: - -```clarity -(define-read-only (convert-string-to-uint (input (string-ascii 20))) - (string-to-uint? input) -) - -;; Usage -(convert-string-to-uint "123") ;; Returns (some u123) -(convert-string-to-uint "456") ;; Returns (some u456) -(convert-string-to-uint "abc") ;; Returns none -``` - -This example demonstrates: -1. Using `string-to-uint?` to convert a string to an optional unsigned integer. -2. Implementing a public function to handle the string-to-unsigned-integer conversion. -3. Handling both valid and invalid string inputs. - -## Common Pitfalls - -1. Using `string-to-uint?` with incorrectly formatted or invalid string inputs, causing the operation to return `none`. -2. Assuming the conversion will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete data management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `string-to-int?`: Converts a string to an optional signed integer. -- `int-to-ascii`: Converts an integer to a string-ascii representation. -- `int-to-utf8`: Converts an integer to a string-utf8 representation. - -## Conclusion - -The `string-to-uint?` function is a fundamental tool for converting string representations of numbers to unsigned integers in Clarity smart contracts. It allows you to implement logic that requires numeric values from string inputs, ensuring data integrity and simplifying numeric conversions. When used effectively, `string-to-uint?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle string-to-unsigned-integer conversions. diff --git a/content/docs/stacks/clarity/functions/stx-account.mdx b/content/docs/stacks/clarity/functions/stx-account.mdx deleted file mode 100644 index b8e4b1d8d..000000000 --- a/content/docs/stacks/clarity/functions/stx-account.mdx +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: stx-account -description: Query STX account information in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(stx-account principal) -``` - -- Input: `principal` -- Output: `(tuple (balance uint) (nonce uint) (stx-locked uint))` - -## Why it matters - -The `stx-account` function is crucial for: - -1. Querying detailed information about a STX account. -2. Implementing logic that requires account balance, nonce, and locked STX information. -3. Ensuring data integrity by providing accurate account details. -4. Simplifying the process of handling account-related operations in smart contracts. - -## When to use it - -Use `stx-account` when you need to: - -- Query detailed information about a STX account. -- Implement logic that requires account balance, nonce, and locked STX information. -- Ensure accurate account details for data integrity. -- Handle account-related operations in your smart contract. - -## Best Practices - -- Ensure the `principal` is correctly formatted and valid. -- Use meaningful variable names for better readability. -- Combine with other account functions for comprehensive account management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Querying STX Account Information - -Let's implement a function that queries the STX account information for a given principal: - -```clarity -(define-read-only (get-stx-account-info (account principal)) - (stx-account account) -) - -;; Usage -(get-stx-account-info 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) -;; Returns (tuple (balance u0) (nonce u0) (stx-locked u0)) -``` - -This example demonstrates: -1. Using `stx-account` to query detailed information about a STX account. -2. Implementing a public function to handle the account information query. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `stx-account` with an incorrectly formatted or invalid `principal`, causing the operation to fail. -2. Assuming the account information will always be valid, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete account management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `stx-get-balance`: Queries the STX balance of a principal. -- `stx-transfer?`: Transfers STX from one principal to another. -- `stx-burn?`: Burns STX from a principal's account. - -## Conclusion - -The `stx-account` function is a fundamental tool for querying detailed STX account information in Clarity smart contracts. It allows you to implement logic that requires account balance, nonce, and locked STX information, ensuring data integrity and simplifying account-related operations. When used effectively, `stx-account` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle account information queries. diff --git a/content/docs/stacks/clarity/functions/stx-burn.mdx b/content/docs/stacks/clarity/functions/stx-burn.mdx deleted file mode 100644 index 4dd1ba9c0..000000000 --- a/content/docs/stacks/clarity/functions/stx-burn.mdx +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: stx-burn? -description: Burn STX from a principal's account in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(stx-burn? amount sender) -``` - -- Input: `uint, principal` -- Output: `(response bool uint)` - -## Why it matters - -The `stx-burn?` function is crucial for: - -1. Decreasing the STX holdings of a principal by burning the specified amount. -2. Implementing logic that requires reducing the circulating supply of STX. -3. Ensuring data integrity by validating the burn operation. -4. Simplifying the process of handling STX burning in smart contracts. - -## When to use it - -Use `stx-burn?` when you need to: - -- Decrease the STX holdings of a principal by burning the specified amount. -- Implement logic that requires reducing the circulating supply of STX. -- Validate the burn operation to ensure data integrity. -- Handle STX burning operations in your smart contract. - -## Best Practices - -- Ensure the `amount` is positive and the `sender` has sufficient balance. -- Use meaningful variable names for better readability. -- Combine with other STX functions for comprehensive account management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Burning STX from an Account - -Let's implement a function that burns a specified amount of STX from the `tx-sender`: - -```clarity -(define-public (burn-stx (amount uint)) - (stx-burn? amount tx-sender) -) - -;; Usage -(burn-stx u50) ;; Returns (ok true) -``` - -This example demonstrates: -1. Using `stx-burn?` to burn a specified amount of STX from the `tx-sender`. -2. Implementing a public function to handle the STX burning operation. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `stx-burn?` with a non-positive amount, causing the operation to fail. -2. Assuming the burn operation will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete account management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `stx-get-balance`: Queries the STX balance of a principal. -- `stx-transfer?`: Transfers STX from one principal to another. -- `stx-account`: Queries detailed STX account information. - -## Conclusion - -The `stx-burn?` function is a fundamental tool for burning STX from a principal's account in Clarity smart contracts. It allows you to implement logic that requires reducing the circulating supply of STX, ensuring data integrity and simplifying STX burning operations. When used effectively, `stx-burn?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle STX burning operations. diff --git a/content/docs/stacks/clarity/functions/stx-get-balance.mdx b/content/docs/stacks/clarity/functions/stx-get-balance.mdx deleted file mode 100644 index ef30a254c..000000000 --- a/content/docs/stacks/clarity/functions/stx-get-balance.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: stx-get-balance -description: Query the STX balance of a principal in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(stx-get-balance owner) -``` - -- Input: `principal` -- Output: `uint` - -## Why it matters - -The `stx-get-balance` function is crucial for: - -1. Querying the STX balance of a principal. -2. Implementing logic that requires checking account balances. -3. Ensuring data integrity by providing accurate balance information. -4. Simplifying the process of handling balance-related operations in smart contracts. - -## When to use it - -Use `stx-get-balance` when you need to: - -- Query the STX balance of a principal. -- Implement logic that requires checking account balances. -- Ensure accurate balance information for data integrity. -- Handle balance-related operations in your smart contract. - -## Best Practices - -- Ensure the `principal` is correctly formatted and valid. -- Use meaningful variable names for better readability. -- Combine with other account functions for comprehensive account management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Querying STX Balance - -Let's implement a function that queries the STX balance of a given principal: - -```clarity -(define-read-only (get-stx-balance (account principal)) - (stx-get-balance account) -) - -;; Usage -(get-stx-balance 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) -;; Returns u0 if the account has no balance -(get-stx-balance (as-contract tx-sender)) -;; Returns the balance of the contract's principal -``` - -This example demonstrates: -1. Using `stx-get-balance` to query the STX balance of a principal. -2. Implementing a public function to handle the balance query. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `stx-get-balance` with an incorrectly formatted or invalid `principal`, causing the operation to fail. -2. Assuming the balance query will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete account management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `stx-transfer?`: Transfers STX from one principal to another. -- `stx-burn?`: Burns STX from a principal's account. -- `stx-account`: Queries detailed STX account information. - -## Conclusion - -The `stx-get-balance` function is a fundamental tool for querying the STX balance of a principal in Clarity smart contracts. It allows you to implement logic that requires checking account balances, ensuring data integrity and simplifying balance-related operations. When used effectively, `stx-get-balance` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle balance queries. diff --git a/content/docs/stacks/clarity/functions/stx-transfer-memo.mdx b/content/docs/stacks/clarity/functions/stx-transfer-memo.mdx deleted file mode 100644 index 068c5c7de..000000000 --- a/content/docs/stacks/clarity/functions/stx-transfer-memo.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: stx-transfer-memo? -description: Transfer STX with a memo field in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(stx-transfer-memo? amount sender recipient memo) -``` - -- Input: `uint, principal, principal, buff` -- Output: `(response bool uint)` - -## Why it matters - -The `stx-transfer-memo?` function is crucial for: - -1. Transferring STX between principals with an additional memo field. -2. Implementing logic that requires recording a memo with each transfer. -3. Ensuring data integrity by validating the transfer operation. -4. Simplifying the process of handling STX transfers with memos in smart contracts. - -## When to use it - -Use `stx-transfer-memo?` when you need to: - -- Transfer STX between principals with an additional memo field. -- Implement logic that requires recording a memo with each transfer. -- Validate the transfer operation to ensure data integrity. -- Handle STX transfers with memos in your smart contract. - -## Best Practices - -- Ensure the `amount` is positive and the `sender` has sufficient balance. -- Use meaningful variable names for better readability. -- Combine with other STX functions for comprehensive account management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Transferring STX with a Memo - -Let's implement a function that transfers STX with a memo from the `tx-sender` to a recipient: - -```clarity -(define-public (transfer-stx-with-memo (amount uint) (recipient principal) (memo (buff 34))) - (stx-transfer-memo? amount tx-sender recipient memo) -) - -;; Usage -(transfer-stx-with-memo u60 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 0x010203) -;; Returns (ok true) if successful -(transfer-stx-with-memo u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR 0x040506) -;; Returns (err u1) if the sender does not have enough balance -``` - -This example demonstrates: -1. Using `stx-transfer-memo?` to transfer STX with a memo. -2. Implementing a public function to handle the STX transfer with a memo. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `stx-transfer-memo?` with a non-positive amount, causing the operation to fail. -2. Assuming the transfer operation will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete account management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `stx-get-balance`: Queries the STX balance of a principal. -- `stx-transfer?`: Transfers STX from one principal to another without a memo. -- `stx-burn?`: Burns STX from a principal's account. - -## Conclusion - -The `stx-transfer-memo?` function is a fundamental tool for transferring STX with a memo in Clarity smart contracts. It allows you to implement logic that requires recording a memo with each transfer, ensuring data integrity and simplifying STX transfer operations. When used effectively, `stx-transfer-memo?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle STX transfers with memos. diff --git a/content/docs/stacks/clarity/functions/stx-transfer.mdx b/content/docs/stacks/clarity/functions/stx-transfer.mdx deleted file mode 100644 index d48aab38b..000000000 --- a/content/docs/stacks/clarity/functions/stx-transfer.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: stx-transfer? -description: Transfer STX between principals in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(stx-transfer? amount sender recipient) -``` - -- Input: `uint, principal, principal` -- Output: `(response bool uint)` - -## Why it matters - -The `stx-transfer?` function is crucial for: - -1. Transferring STX between principals. -2. Implementing logic that requires moving STX from one account to another. -3. Ensuring data integrity by validating the transfer operation. -4. Simplifying the process of handling STX transfers in smart contracts. - -## When to use it - -Use `stx-transfer?` when you need to: - -- Transfer STX between principals. -- Implement logic that requires moving STX from one account to another. -- Validate the transfer operation to ensure data integrity. -- Handle STX transfers in your smart contract. - -## Best Practices - -- Ensure the `amount` is positive and the `sender` has sufficient balance. -- Use meaningful variable names for better readability. -- Combine with other STX functions for comprehensive account management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Transferring STX - -Let's implement a function that transfers STX from the `tx-sender` to a recipient: - -```clarity -(define-public (transfer-stx (amount uint) (recipient principal)) - (stx-transfer? amount tx-sender recipient) -) - -;; Usage -(transfer-stx u60 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) -;; Returns (ok true) if successful -(transfer-stx u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) -;; Returns (err u1) if the sender does not have enough balance -``` - -This example demonstrates: -1. Using `stx-transfer?` to transfer STX from the `tx-sender` to a recipient. -2. Implementing a public function to handle the STX transfer. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `stx-transfer?` with a non-positive amount, causing the operation to fail. -2. Assuming the transfer operation will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete account management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `stx-get-balance`: Queries the STX balance of a principal. -- `stx-transfer-memo?`: Transfers STX from one principal to another with a memo. -- `stx-burn?`: Burns STX from a principal's account. - -## Conclusion - -The `stx-transfer?` function is a fundamental tool for transferring STX between principals in Clarity smart contracts. It allows you to implement logic that requires moving STX from one account to another, ensuring data integrity and simplifying STX transfer operations. When used effectively, `stx-transfer?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle STX transfers. diff --git a/content/docs/stacks/clarity/functions/subtract.mdx b/content/docs/stacks/clarity/functions/subtract.mdx deleted file mode 100644 index 96d008e6a..000000000 --- a/content/docs/stacks/clarity/functions/subtract.mdx +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: subtract -description: Use the subtraction function for arithmetic operations in Clarity smart contracts. ---- - -The subtraction function (`-`) in Clarity performs subtraction on a variable number of integer inputs. It's a fundamental arithmetic operation used in many smart contract calculations. - -## Function Signature - -```clarity -(- i1 i2...) -``` - -- Input: Two or more integers (int or uint) -- Output: A single integer (int or uint) - -## Why it matters - -The subtraction function is crucial for: - -1. Performing basic arithmetic calculations within smart contracts. -2. Decreasing values or counters. -3. Calculating differences between quantities. -4. Implementing mathematical formulas that involve subtraction. - -## When to use it - -Use the subtraction function when you need to: - -- Perform basic subtraction in your contract logic. -- Decrement values or counters. -- Calculate the difference between two or more values. -- Implement mathematical formulas that involve subtraction. - -## Best Practices - -- Always consider the possibility of underflow when subtracting from small numbers. -- Use appropriate types (int or uint) based on your needs and expected value ranges. -- Be aware that subtracting a negative number results in addition. -- Consider using checked arithmetic functions if underflow detection is critical. - -## Practical Example: Simple Escrow Contract - -Let's implement a basic escrow contract that uses subtraction to manage balances: - -```clarity -;; Define constants -(define-constant ESCROW_FEE u100) ;; 100 tokens as escrow fee - -;; Define data variables -(define-map Balances principal uint) -(define-data-var escrowBalance uint u0) - -;; Function to deposit funds -(define-public (deposit (amount uint)) - (let - ( - (currentBalance (default-to u0 (map-get? Balances tx-sender))) - ) - (try! (stx-transfer? amount tx-sender (as-contract tx-sender))) - (map-set Balances tx-sender (+ currentBalance amount)) - (ok true) - ) -) - -;; Function to initiate escrow -(define-public (start-escrow (recipient principal) (amount uint)) - (let - ( - (senderBalance (default-to u0 (map-get? Balances tx-sender))) - ) - (asserts! (>= senderBalance (+ amount ESCROW_FEE)) (err u1)) - (map-set Balances tx-sender (- senderBalance (+ amount ESCROW_FEE))) - (var-set escrowBalance (+ (var-get escrowBalance) amount)) - (ok true) - ) -) - -;; Function to complete escrow and transfer funds -(define-public (complete-escrow (recipient principal) (amount uint)) - (let - ( - (escrowAmount (var-get escrowBalance)) - ) - (asserts! (>= escrowAmount amount) (err u2)) - (try! (as-contract (stx-transfer? amount tx-sender recipient))) - (var-set escrowBalance (- escrowAmount amount)) - (ok true) - ) -) -``` - -This example demonstrates: -1. Using subtraction to update `Balances` when initiating an escrow. -2. Using subtraction to update the escrow balance when completing a transfer. -3. Combining subtraction with addition to handle fees and balance updates. - -## Common Pitfalls - -1. Overlooking potential underflow when subtracting from small numbers. -2. Not considering the effect of subtracting negative numbers (for int types). -3. Forgetting to update related variables or state when decrementing values. - -## Related Functions - -- `+`: Used for addition operations. -- `*`: Used for multiplication operations. -- `/`: Used for division operations. - -## Conclusion - -The subtraction function is a fundamental tool for performing arithmetic operations in Clarity smart contracts. By understanding its behavior with different types of inputs and potential edge cases, you can use it effectively to implement various mathematical operations in your contracts, from simple decrements to more complex financial calculations. diff --git a/content/docs/stacks/clarity/functions/to-consensus-buff.mdx b/content/docs/stacks/clarity/functions/to-consensus-buff.mdx deleted file mode 100644 index 2ebcc6d24..000000000 --- a/content/docs/stacks/clarity/functions/to-consensus-buff.mdx +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: to-consensus-buff? -description: Serialize a Clarity value into a buffer for consensus in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(to-consensus-buff? value) -``` - -- Input: `any` -- Output: `(optional (buff 32))` - -## Why it matters - -The `to-consensus-buff?` function is crucial for: - -1. Serializing Clarity values into buffers for consensus. -2. Implementing logic that requires converting Clarity values to a standardized buffer format. -3. Ensuring data integrity by validating the serialization process. -4. Simplifying the process of handling value serialization in smart contracts. - -## When to use it - -Use `to-consensus-buff?` when you need to: - -- Serialize Clarity values into buffers for consensus. -- Implement logic that requires converting Clarity values to a standardized buffer format. -- Validate the serialization process to ensure data integrity. -- Handle value serialization in your smart contract. - -## Best Practices - -- Ensure the input value is correctly formatted and valid. -- Use meaningful variable names for better readability. -- Combine with other serialization functions for comprehensive data management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Serializing a Clarity Value - -Let's implement a function that serializes an integer value into a buffer: - -```clarity -(define-read-only (serialize-int (input int)) - (to-consensus-buff? input) -) - -(define-read-only (serialize-tuple (input (tuple (name (string-ascii 50)) (age uint)))) - (to-consensus-buff? input) -) - -;; Usage -(serialize-int 42) ;; Returns (some 0x000000000000000000000000000000000000000000000000000000000000002a) -(serialize-int -1) ;; Returns none (since negative integers cannot be serialized) -(serialize-tuple (tuple (name "Harper Dog") (age u5))) ;; Returns (some 0x0c00000002036167650100000000000000000000000000000005046e616d650d0000000a48617270657220446f67) -``` - -This example demonstrates: -1. Using `to-consensus-buff?` to serialize an integer value into a buffer. -2. Implementing a public function to handle the serialization process. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `to-consensus-buff?` with incorrectly formatted or invalid input values, causing the operation to fail. -2. Assuming the serialization will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete data management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `from-consensus-buff?`: Deserializes a buffer into a Clarity value. -- `buff-to-int-be`: Converts a big-endian buffer to an integer. -- `buff-to-uint-le`: Converts a little-endian buffer to an unsigned integer. - -## Conclusion - -The `to-consensus-buff?` function is a fundamental tool for serializing Clarity values into buffers for consensus in Clarity smart contracts. It allows you to implement logic that requires converting Clarity values to a standardized buffer format, ensuring data integrity and simplifying value serialization. When used effectively, `to-consensus-buff?` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle value serialization. diff --git a/content/docs/stacks/clarity/functions/to-int.mdx b/content/docs/stacks/clarity/functions/to-int.mdx deleted file mode 100644 index c241506de..000000000 --- a/content/docs/stacks/clarity/functions/to-int.mdx +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: to-int -description: Convert an unsigned integer to a signed integer in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(to-int value) -``` - -- Input: `uint` -- Output: `int` - -## Why it matters - -The `to-int` function is crucial for: - -1. Converting unsigned integers to signed integers. -2. Implementing logic that requires signed integer operations. -3. Ensuring data integrity by validating the conversion process. -4. Simplifying the process of handling integer conversions in smart contracts. - -## When to use it - -Use `to-int` when you need to: - -- Convert an unsigned integer to a signed integer. -- Implement logic that requires signed integer operations. -- Validate the conversion process to ensure data integrity. -- Handle integer conversions in your smart contract. - -## Best Practices - -- Ensure the input value is within the range that can be represented as a signed integer. -- Use meaningful variable names for better readability. -- Combine with other integer functions for comprehensive data management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Converting Unsigned Integer to Signed Integer - -Let's implement a function that converts an unsigned integer to a signed integer: - -```clarity -(define-read-only (convert-to-int (input uint)) - (to-int input) -) - -;; Usage -(convert-to-int u42) ;; Returns 42 -(convert-to-int u0) ;; Returns 0 -(convert-to-int u1000000) ;; Returns 1000000 -``` - -This example demonstrates: -1. Using `to-int` to convert an unsigned integer to a signed integer. -2. Implementing a public function to handle the conversion process. -3. Handling both small and large input values. - -## Common Pitfalls - -1. Using `to-int` with values that exceed the range of signed integers, causing unexpected behavior. -2. Assuming the conversion will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete data management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `to-uint`: Converts a signed integer to an unsigned integer. -- `int-to-ascii`: Converts an integer to a string-ascii representation. -- `int-to-utf8`: Converts an integer to a string-utf8 representation. - -## Conclusion - -The `to-int` function is a fundamental tool for converting unsigned integers to signed integers in Clarity smart contracts. It allows you to implement logic that requires signed integer operations, ensuring data integrity and simplifying integer conversions. When used effectively, `to-int` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle integer conversions. diff --git a/content/docs/stacks/clarity/functions/to-uint.mdx b/content/docs/stacks/clarity/functions/to-uint.mdx deleted file mode 100644 index a5630fd3c..000000000 --- a/content/docs/stacks/clarity/functions/to-uint.mdx +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: to-uint -description: Convert a signed integer to an unsigned integer in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(to-uint value) -``` - -- Input: `int` -- Output: `uint` - -## Why it matters - -The `to-uint` function is crucial for: - -1. Converting signed integers to unsigned integers. -2. Implementing logic that requires unsigned integer operations. -3. Ensuring data integrity by validating the conversion process. -4. Simplifying the process of handling integer conversions in smart contracts. - -## When to use it - -Use `to-uint` when you need to: - -- Convert a signed integer to an unsigned integer. -- Implement logic that requires unsigned integer operations. -- Validate the conversion process to ensure data integrity. -- Handle integer conversions in your smart contract. - -## Best Practices - -- Ensure the input value is non-negative to avoid runtime errors. -- Use meaningful variable names for better readability. -- Combine with other integer functions for comprehensive data management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Converting Signed Integer to Unsigned Integer - -Let's implement a function that converts a signed integer to an unsigned integer: - -```clarity -(define-read-only (convert-to-uint (input int)) - (to-uint input) -) - -;; Usage -(convert-to-uint 42) ;; Returns u42 -(convert-to-uint 0) ;; Returns u0 -(convert-to-uint -1) ;; Causes a runtime error -``` - -This example demonstrates: -1. Using `to-uint` to convert a signed integer to an unsigned integer. -2. Implementing a public function to handle the conversion process. -3. Handling both positive and zero input values. - -## Common Pitfalls - -1. Using `to-uint` with negative values, causing a runtime error. -2. Assuming the conversion will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete data management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `to-int`: Converts an unsigned integer to a signed integer. -- `int-to-ascii`: Converts an integer to a string-ascii representation. -- `int-to-utf8`: Converts an integer to a string-utf8 representation. - -## Conclusion - -The `to-uint` function is a fundamental tool for converting signed integers to unsigned integers in Clarity smart contracts. It allows you to implement logic that requires unsigned integer operations, ensuring data integrity and simplifying integer conversions. When used effectively, `to-uint` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle integer conversions. diff --git a/content/docs/stacks/clarity/functions/try.mdx b/content/docs/stacks/clarity/functions/try.mdx deleted file mode 100644 index 8d6fb2cc1..000000000 --- a/content/docs/stacks/clarity/functions/try.mdx +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: try! -description: Handle errors in Clarity smart contracts using the `try!` function. ---- - -## Function Signature - -```clarity -(try! expression) -``` - -- Input: `expression` (of type `(response T E)`) -- Output: `T` (if the response is `ok`) or causes a runtime error (if the response is `err`) - -## Why it matters - -The `try!` function is crucial for: - -1. Simplifying error handling in Clarity smart contracts. -2. Implementing logic that requires automatic error propagation. -3. Ensuring data integrity by validating operations and handling errors gracefully. -4. Simplifying the process of handling responses in smart contracts. - -## When to use it - -Use `try!` when you need to: - -- Simplify error handling in your smart contract. -- Implement logic that requires automatic error propagation. -- Validate operations and handle errors gracefully. -- Handle responses in your smart contract. - -## Best Practices - -- Ensure the expression returns a response type `(response T E)`. -- Use meaningful variable names for better readability. -- Combine with other error handling functions for comprehensive error management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Handling Errors in a Transfer Function - -Let's implement a function that transfers STX and handles errors using `try!`: - -```clarity -(define-public (transfer-stx (amount uint) (recipient principal)) - (begin - (try! (stx-transfer? amount tx-sender recipient)) - (ok true) - ) -) - -;; Usage -(transfer-stx u60 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) -;; Returns (ok true) if successful -(transfer-stx u50 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) -;; Returns (err u1) if the sender does not have enough balance -``` - -This example demonstrates: -1. Using `try!` to handle errors in a STX transfer operation. -2. Implementing a public function to handle the transfer and error propagation. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `try!` with expressions that do not return a response type, causing runtime errors. -2. Assuming the operation will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete error management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `unwrap!`: Unwraps an optional value, causing a runtime error if the value is `none`. -- `asserts!`: Asserts a condition, causing a runtime error if the condition is false. -- `is-err`: Checks if a response is an error. - -## Conclusion - -The `try!` function is a fundamental tool for handling errors in Clarity smart contracts. It allows you to simplify error handling, ensuring data integrity and automatic error propagation. When used effectively, `try!` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle responses and errors. diff --git a/content/docs/stacks/clarity/functions/tuple.mdx b/content/docs/stacks/clarity/functions/tuple.mdx deleted file mode 100644 index 20cb98919..000000000 --- a/content/docs/stacks/clarity/functions/tuple.mdx +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: tuple -description: Use tuples to group data values with named fields in Clarity smart contracts. ---- - -## Type Definition - -```clarity -{label-0: value-type-0, label-1: value-type-1, ...} -``` - -- Input: `various types` -- Output: `tuple` - -## Why it matters - -The `tuple` type is crucial for: - -1. Grouping related data values with named fields. -2. Implementing complex data structures in smart contracts. -3. Ensuring data integrity by providing a clear structure for related values. -4. Simplifying the process of handling grouped data in smart contracts. - -## When to use it - -Use `tuple` when you need to: - -- Group related data values with named fields. -- Implement complex data structures in your smart contract. -- Ensure data integrity by providing a clear structure for related values. -- Handle grouped data in your smart contract. - -## Best Practices - -- Use descriptive names for tuple fields for better readability. -- Ensure the types of the tuple fields are appropriate for the data they represent. -- Combine with other data types and functions for comprehensive data management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Using Tuples to Store User Information - -Let's implement a function that stores and retrieves user information using tuples: - -```clarity -(define-map UserInfo { userId: principal } { name: (string-ascii 20), age: uint }) - -(define-public (set-user-info (user principal) (name (string-ascii 20)) (age uint)) - (begin - (map-set UserInfo { userId: user } { name: name, age: age }) - (ok true) - ) -) - -(define-read-only (get-user-info (user principal)) - (map-get? UserInfo { userId: user }) -) - -;; Usage -(set-user-info tx-sender "Alice" u30) ;; Sets the user info -(get-user-info tx-sender) ;; Returns (some { name: "Alice", age: u30 }) -``` - -This example demonstrates: -1. Using tuples to store user information with named fields. -2. Implementing functions to set and get user information using tuples. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using non-descriptive names for tuple fields, causing confusion. -2. Assuming the tuple structure will always be valid, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete data management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `map-set`: Sets a value in a map. -- `map-get?`: Retrieves a value from a map. -- `default-to`: Provides a default value if an optional is `none`. - -## Conclusion - -The `tuple` type is a fundamental tool for grouping related data values with named fields in Clarity smart contracts. It allows you to implement complex data structures, ensuring data integrity and simplifying data management. When used effectively, `tuple` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle grouped data. diff --git a/content/docs/stacks/clarity/functions/unwrap-err-panic.mdx b/content/docs/stacks/clarity/functions/unwrap-err-panic.mdx deleted file mode 100644 index c39ac4eb5..000000000 --- a/content/docs/stacks/clarity/functions/unwrap-err-panic.mdx +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: unwrap-err-panic -description: Unpack error responses and throwing runtime errors in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(unwrap-err-panic response-input) -``` - -- Input: `(response A B)` -- Output: `B` - -## Why it matters - -The `unwrap-err-panic` function is crucial for: - -1. Unpacking error responses to access their inner values. -2. Implementing logic that requires handling error responses. -3. Ensuring data integrity by validating the error unpacking process. -4. Simplifying the process of handling error responses in smart contracts by throwing runtime errors when necessary. - -## When to use it - -Use `unwrap-err-panic` when you need to: - -- Unpack error responses to access their inner values. -- Implement logic that requires handling error responses. -- Validate the error unpacking process to ensure data integrity. -- Handle error responses in your smart contract and throw runtime errors when necessary. - -## Best Practices - -- Ensure the input value is a response type. -- Use meaningful variable names for better readability. -- Combine with other error handling functions for comprehensive error management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Unpacking an Error Response and Throwing a Runtime Error - -Let's implement a function that processes an error response using `unwrap-err-panic`: - -```clarity -(define-public (process-error-response (input (response int int))) - (let - ( - (errorValue (unwrap-err-panic input)) - ) - (ok errorValue) - ) -) - -;; Usage -(process-error-response (err 42)) ;; Returns (ok 42) -(process-error-response (ok 1)) ;; Throws a runtime exception -``` - -This example demonstrates: -1. Using `unwrap-err-panic` to unpack an error response. -2. Implementing a public function to handle the error unpacking process. -3. Handling both successful and error cases, with runtime errors thrown for `ok` values. - -## Common Pitfalls - -1. Using `unwrap-err-panic` with values that are not response types, causing runtime errors. -2. Assuming the error unpacking will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete error management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `unwrap!`: Unpacks optional and response types, returning a thrown value if unpacking fails. -- `unwrap-err!`: Unpacks error responses, returning a thrown value if the response is `ok`. -- `try!`: Unpacks optional and response types, returning `none` or the `err` value if unpacking fails. - -## Conclusion - -The `unwrap-err-panic` function is a fundamental tool for unpacking error responses and throwing runtime errors in Clarity smart contracts. It allows you to implement logic that requires handling error responses, ensuring data integrity and simplifying the error unpacking process. When used effectively, `unwrap-err-panic` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle error responses and throw runtime errors when necessary. diff --git a/content/docs/stacks/clarity/functions/unwrap-err.mdx b/content/docs/stacks/clarity/functions/unwrap-err.mdx deleted file mode 100644 index c698e3be4..000000000 --- a/content/docs/stacks/clarity/functions/unwrap-err.mdx +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: unwrap-err! -description: Unpack error responses in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(unwrap-err! response-input thrown-value) -``` - -- Input: `(response A B), C` -- Output: `B` - -## Why it matters - -The `unwrap-err!` function is crucial for: - -1. Unpacking error responses to access their inner values. -2. Implementing logic that requires handling error responses. -3. Ensuring data integrity by validating the error unpacking process. -4. Simplifying the process of handling error responses in smart contracts. - -## When to use it - -Use `unwrap-err!` when you need to: - -- Unpack error responses to access their inner values. -- Implement logic that requires handling error responses. -- Validate the error unpacking process to ensure data integrity. -- Handle error responses in your smart contract. - -## Best Practices - -- Ensure the input value is a response type. -- Use meaningful variable names for better readability. -- Combine with other error handling functions for comprehensive error management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Unpacking an Error Response - -Let's implement a function that processes an error response using `unwrap-err!`: - -```clarity -(define-public (process-error-response (input (response int int))) - (let - ( - (errorValue (unwrap-err! input (err "No error found"))) - ) - (ok errorValue) - ) -) - -;; Usage -(process-error-response (err 42)) ;; Returns (ok 42) -(process-error-response (ok 1)) ;; Returns (err "No error found") -``` - -This example demonstrates: -1. Using `unwrap-err!` to unpack an error response. -2. Implementing a public function to handle the error unpacking process. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `unwrap-err!` with values that are not response types, causing runtime errors. -2. Assuming the error unpacking will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete error management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `unwrap!`: Unpacks optional and response types, returning a thrown value if unpacking fails. -- `unwrap-panic`: Unpacks optional and response types, throwing a runtime error if unpacking fails. -- `try!`: Unpacks optional and response types, returning `none` or the `err` value if unpacking fails. - -## Conclusion - -The `unwrap-err!` function is a fundamental tool for unpacking error responses in Clarity smart contracts. It allows you to implement logic that requires handling error responses, ensuring data integrity and simplifying the error unpacking process. When used effectively, `unwrap-err!` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle error responses. diff --git a/content/docs/stacks/clarity/functions/unwrap-panic.mdx b/content/docs/stacks/clarity/functions/unwrap-panic.mdx deleted file mode 100644 index 903b9d2f4..000000000 --- a/content/docs/stacks/clarity/functions/unwrap-panic.mdx +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: unwrap-panic -description: Unpack optional and response types and throwing runtime errors in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(unwrap-panic option-input) -``` - -- Input: `(optional A) | (response A B)` -- Output: `A` - -## Why it matters - -The `unwrap-panic` function is crucial for: - -1. Unpacking optional and response types to access their inner values. -2. Implementing logic that requires handling optional and response types. -3. Ensuring data integrity by validating the unpacking process. -4. Simplifying the process of handling optional and response types in smart contracts by throwing runtime errors when necessary. - -## When to use it - -Use `unwrap-panic` when you need to: - -- Unpack optional and response types to access their inner values. -- Implement logic that requires handling optional and response types. -- Validate the unpacking process to ensure data integrity. -- Handle optional and response types in your smart contract and throw runtime errors when necessary. - -## Best Practices - -- Ensure the input value is an optional or response type. -- Use meaningful variable names for better readability. -- Combine with other error handling functions for comprehensive error management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Unpacking an Optional Value and Throwing a Runtime Error - -Let's implement a function that retrieves a value from a map and unpacks it using `unwrap-panic`: - -```clarity -(define-map UserInfo { userId: principal } { name: (string-ascii 20), age: uint }) - -(define-public (get-user-age (user principal)) - (let - ( - (userData (unwrap-panic (map-get? UserInfo { userId: user }))) - ) - (ok (get age userData)) - ) -) - -;; Usage -(map-set UserInfo { userId: tx-sender } { name: "Alice", age: u30 }) -(get-user-age tx-sender) ;; Returns (ok u30) -(get-user-age 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Throws a runtime exception -``` - -## Common Pitfalls - -1. Using `unwrap-panic` with values that are not optional or response types, causing runtime errors. -2. Assuming the unpacking will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete error management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `unwrap!`: Unpacks optional and response types, returning a thrown value if unpacking fails. -- `unwrap-err!`: Unpacks error responses, returning a thrown value if the response is `ok`. -- `try!`: Unpacks optional and response types, returning `none` or the `err` value if unpacking fails. - -## Conclusion - -The `unwrap-panic` function is a fundamental tool for unpacking optional and response types and throwing runtime errors in Clarity smart contracts. It allows you to implement logic that requires handling optional and response types, ensuring data integrity and simplifying the unpacking process. When used effectively, `unwrap-panic` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle optional and response types and throw runtime errors when necessary. diff --git a/content/docs/stacks/clarity/functions/unwrap.mdx b/content/docs/stacks/clarity/functions/unwrap.mdx deleted file mode 100644 index ac0260064..000000000 --- a/content/docs/stacks/clarity/functions/unwrap.mdx +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: unwrap! -description: Unpack optional and response types in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(unwrap! option-input thrown-value) -``` - -- Input: `(optional A) | (response A B), C` -- Output: `A` - -## Why it matters - -The `unwrap!` function is crucial for: - -1. Unpacking optional and response types to access their inner values. -2. Implementing logic that requires handling optional and response types. -3. Ensuring data integrity by validating the unpacking process. -4. Simplifying the process of handling optional and response types in smart contracts. - -## When to use it - -Use `unwrap!` when you need to: - -- Unpack optional and response types to access their inner values. -- Implement logic that requires handling optional and response types. -- Validate the unpacking process to ensure data integrity. -- Handle optional and response types in your smart contract. - -## Best Practices - -- Ensure the input value is an optional or response type. -- Use meaningful variable names for better readability. -- Combine with other error handling functions for comprehensive error management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Unpacking an Optional Value - -Let's implement a function that retrieves a value from a map and unpacks it using `unwrap!`: - -```clarity -(define-map UserInfo { userId: principal } { name: (string-ascii 20), age: uint }) - -(define-public (get-user-age (user principal)) - (let - ( - (userData (unwrap! (map-get? UserInfo { userId: user }) (err "User not found"))) - ) - (ok (get age userData)) - ) -) - -;; Usage -(map-set UserInfo { userId: tx-sender } { name: "Alice", age: u30 }) -(get-user-age tx-sender) ;; Returns (ok u30) -(get-user-age 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns (err "User not found") -``` - -This example demonstrates: -1. Using `unwrap!` to unpack an optional value from a map. -2. Implementing a public function to handle the unpacking process. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `unwrap!` with values that are not optional or response types, causing runtime errors. -2. Assuming the unpacking will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete error management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `try!`: Unpacks optional and response types, returning `none` or the `err` value if unpacking fails. -- `unwrap-panic`: Unpacks optional and response types, throwing a runtime error if unpacking fails. -- `default-to`: Provides a default value if an optional is `none`. - -## Conclusion - -The `unwrap!` function is a fundamental tool for unpacking optional and response types in Clarity smart contracts. It allows you to implement logic that requires handling optional and response types, ensuring data integrity and simplifying the unpacking process. When used effectively, `unwrap!` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle optional and response types. diff --git a/content/docs/stacks/clarity/functions/use-trait.mdx b/content/docs/stacks/clarity/functions/use-trait.mdx deleted file mode 100644 index 568f604fd..000000000 --- a/content/docs/stacks/clarity/functions/use-trait.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: use-trait -description: Import and use traits from other contracts in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(use-trait trait-alias trait-identifier) -``` - -- Input: `VarName, TraitIdentifier` -- Output: `Not Applicable` - -## Why it matters - -The `use-trait` function is crucial for: - -1. Importing traits defined in other contracts. -2. Implementing logic that requires conformance to specific interfaces. -3. Ensuring code reusability and modularity by leveraging traits. -4. Simplifying the process of using external traits in smart contracts. - -## When to use it - -Use `use-trait` when you need to: - -- Import traits defined in other contracts. -- Implement logic that requires conformance to specific interfaces. -- Ensure code reusability and modularity by leveraging traits. -- Handle trait imports in your smart contract. - -## Best Practices - -- Use descriptive names for trait aliases for better readability. -- Ensure the trait identifier is correctly formatted and valid. -- Combine with other contract functions for comprehensive contract management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Importing and Using a Trait - -Let's implement a function that imports a trait and uses it in a contract: - -```clarity -(use-trait token-trait 'SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR.token-trait) - -(define-public (forward-get-balance (user principal) (contract )) - (ok (contract-of contract)) -) - -;; Usage -(forward-get-balance tx-sender 'SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR.token-trait) -;; Returns the principal of the contract implementing the token-trait -``` - -This example demonstrates: -1. Using `use-trait` to import a trait from another contract. -2. Implementing a public function to use the imported trait. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `use-trait` with incorrectly formatted or invalid trait identifiers, causing runtime errors. -2. Assuming the trait import will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete contract management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `contract-of`: Returns the principal of the contract implementing the trait. -- `define-trait`: Defines a new trait in the current contract. -- `impl-trait`: Implements a trait in the current contract. - -## Conclusion - -The `use-trait` function is a fundamental tool for importing and using traits from other contracts in Clarity smart contracts. It allows you to implement logic that requires conformance to specific interfaces, ensuring code reusability and modularity. When used effectively, `use-trait` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle trait imports. diff --git a/content/docs/stacks/clarity/functions/var-get.mdx b/content/docs/stacks/clarity/functions/var-get.mdx deleted file mode 100644 index b17ab163f..000000000 --- a/content/docs/stacks/clarity/functions/var-get.mdx +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: var-get -description: Retrieve the value of a data variable in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(var-get var-name) -``` - -- Input: `VarName` -- Output: `A` - -## Why it matters - -The `var-get` function is crucial for: - -1. Retrieving the value of a data variable. -2. Implementing logic that requires accessing stored data. -3. Ensuring data integrity by validating the retrieval process. -4. Simplifying the process of handling data variables in smart contracts. - -## When to use it - -Use `var-get` when you need to: - -- Retrieve the value of a data variable. -- Implement logic that requires accessing stored data. -- Validate the retrieval process to ensure data integrity. -- Handle data variables in your smart contract. - -## Best Practices - -- Ensure the variable name is correctly formatted and valid. -- Use meaningful variable names for better readability. -- Combine with other data functions for comprehensive data management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Retrieving a Data Variable - -```clarity -(define-data-var cursor int 6) - -(define-public (get-cursor) - (ok (var-get cursor)) -) - -;; Usage -(get-cursor) ;; Returns (ok 6) -``` - -This example demonstrates: -1. Using `var-get` to retrieve the value of a data variable. -2. Implementing a public function to handle the retrieval process. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `var-get` with incorrectly formatted or invalid variable names, causing runtime errors. -2. Assuming the retrieval will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete data management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `var-set`: Sets the value of a data variable. -- `map-get?`: Retrieves a value from a map. -- `default-to`: Provides a default value if an optional is `none`. - -## Conclusion - -The `var-get` function is a fundamental tool for retrieving the value of a data variable in Clarity smart contracts. It allows you to implement logic that requires accessing stored data, ensuring data integrity and simplifying the retrieval process. When used effectively, `var-get` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle data variables. diff --git a/content/docs/stacks/clarity/functions/var-set.mdx b/content/docs/stacks/clarity/functions/var-set.mdx deleted file mode 100644 index 60951b0da..000000000 --- a/content/docs/stacks/clarity/functions/var-set.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: var-set -description: Set the value of a data variable in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(var-set var-name expr1) -``` - -- Input: `VarName, AnyType` -- Output: `bool` - -## Why it matters - -The `var-set` function is crucial for: - -1. Setting the value of a data variable. -2. Implementing logic that requires updating stored data. -3. Ensuring data integrity by validating the update process. -4. Simplifying the process of handling data variables in smart contracts. - -## When to use it - -Use `var-set` when you need to: - -- Set the value of a data variable. -- Implement logic that requires updating stored data. -- Validate the update process to ensure data integrity. -- Handle data variables in your smart contract. - -## Best Practices - -- Ensure the variable name is correctly formatted and valid. -- Use meaningful variable names for better readability. -- Combine with other data functions for comprehensive data management. -- Handle the possible error cases to ensure robust contract behavior. - -## Practical Example: Setting a Data Variable - -Let's implement a function that sets the value of a data variable: - -```clarity -(define-data-var cursor int 6) - -(define-public (increment-cursor) - (ok (var-set cursor (+ (var-get cursor) 1))) -) - -;; Usage -(increment-cursor) ;; Sets cursor to 7 -(var-get cursor) ;; Returns 7 -``` - -This example demonstrates: -1. Using `var-set` to set the value of a data variable. -2. Implementing a public function to handle the update process. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `var-set` with incorrectly formatted or invalid variable names, causing runtime errors. -2. Assuming the update will always succeed, leading to unhandled error cases. -3. Not handling all possible conditions, resulting in incomplete data management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `var-get`: Retrieves the value of a data variable. -- `map-set`: Sets a value in a map. -- `default-to`: Provides a default value if an optional is `none`. - -## Conclusion - -The `var-set` function is a fundamental tool for setting the value of a data variable in Clarity smart contracts. It allows you to implement logic that requires updating stored data, ensuring data integrity and simplifying the update process. When used effectively, `var-set` enhances the reliability and maintainability of your smart contract code by providing a clear and concise way to handle data variables. diff --git a/content/docs/stacks/clarity/functions/xor.mdx b/content/docs/stacks/clarity/functions/xor.mdx deleted file mode 100644 index 089bde885..000000000 --- a/content/docs/stacks/clarity/functions/xor.mdx +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: xor -description: Perform a bitwise exclusive OR operation in Clarity smart contracts. ---- - -## Function Signature - -```clarity -(xor int1 int2) -``` - -- Input: `int, int` -- Output: `int` - -## Why it matters - -The `xor` function is crucial for: - -1. Performing bitwise operations essential for cryptographic functions. -2. Implementing conditional logic that requires toggling between states. -3. Enhancing data security through simple encryption mechanisms. -4. Simplifying the process of handling bitwise operations in smart contracts. - -## When to use it - -Use `xor` when you need to: - -- Perform bitwise exclusive OR operations. -- Implement simple encryption or decryption mechanisms. -- Toggle between two states based on certain conditions. -- Enhance the security of your smart contract through cryptographic operations. - -## Best Practices - -- Ensure the integers used with `xor` are within the valid range for your application. -- Use meaningful variable names to enhance code readability. -- Combine `xor` with other logical operations to implement complex conditions. -- Handle possible edge cases to ensure robust contract behavior. - -## Practical Example: Simple Encryption - -Let's implement a simple encryption and decryption mechanism using the `xor` function: - -```clarity -(define-public (encrypt (data int) (key int)) - (ok (xor data key)) -) - -(define-public (decrypt (encryptedData int) (key int)) - (ok (xor encryptedData key)) -) - -;; Usage -(encrypt 42 123) ;; Encrypts 42 with key 123, returns (ok 81) -(decrypt 165 123) ;; Decrypts 165 with key 123, returns (ok 222) -``` - -This example demonstrates: -1. Using `xor` to perform a bitwise exclusive OR operation. -2. Implementing public functions to handle encryption and decryption. -3. Handling both successful and error cases. - -## Common Pitfalls - -1. Using `xor` with non-integer types, causing runtime errors. -2. Misunderstanding the behavior of `xor`, leading to incorrect logic implementation. -3. Not considering edge cases, resulting in incomplete data management. -4. Overlooking the need for proper error handling and validation. - -## Related Functions - -- `and`: Performs a bitwise AND operation. -- `or`: Performs a bitwise OR operation. -- `not`: Performs a bitwise NOT operation. - -## Conclusion - -The `xor` function is a powerful tool for performing bitwise exclusive OR operations in Clarity smart contracts. It allows you to implement cryptographic functions, conditional logic, and simple encryption mechanisms, enhancing the security and functionality of your smart contracts. When used effectively, `xor` simplifies the process of handling bitwise operations and ensures robust contract behavior. diff --git a/content/docs/stacks/clarity/index.mdx b/content/docs/stacks/clarity/index.mdx deleted file mode 100644 index cbe05b0c3..000000000 --- a/content/docs/stacks/clarity/index.mdx +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: Introduction -description: Explore and master Clarity's built-in functions for smart contract development. ---- - -import { Code } from 'lucide-react'; -import { SecondaryCard } from '@/components/card'; - - -We're introducing a new series of guides that explore Clarity functions in depth, focusing on their practical applications in blockchain development. - - -Each page in this section covers one or more related Clarity functions, explaining their purpose, demonstrating implementation with code samples, and discussing best practices. Ready to enhance your Clarity smart contract development skills? - -## Explore guides - - - - - - - -Need help or have questions? Join the discussion in the [#clarity channel](https://stacks.chat) on Discord and connect with other Clarity developers. diff --git a/content/docs/stacks/clarity/meta.json b/content/docs/stacks/clarity/meta.json deleted file mode 100644 index 70a25476b..000000000 --- a/content/docs/stacks/clarity/meta.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "title": "Clarity", - "root": true, - "pages": [ - "---Clarity---", - "index", - "---Guides---", - "basic-arithmetic", - "access-control", - "handling-optionals-and-errors", - "---Functions---", - "...functions" - ] -} diff --git a/content/docs/stacks/connect/guides/authenticate-users.mdx b/content/docs/stacks/connect/guides/authenticate-users.mdx deleted file mode 100644 index 051b0e36d..000000000 --- a/content/docs/stacks/connect/guides/authenticate-users.mdx +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: Authenticate users -description: Connect to user wallets and authenticate your users using @stacks/connect. ---- - -import { ConnectWalletButton } from '@/components/code/connect-wallet-button'; -import { ContentBackground } from '@/components/ui/icon'; - -Authentication is a fundamental part of many web applications, ensuring that users are who they claim to be and that their data is secure. With the Stacks blockchain, user authentication involves connecting to users' wallets and managing their sessions securely. - -The `@stacks/connect` package provides the tools needed to integrate this functionality seamlessly into your web app. - -In this guide, you will learn how to: - -1. [Install the `@stacks/connect` package](#install-the-stacksconnect-package). -2. [Connect to a user's wallet](#connect-to-a-users-wallet). -3. [Manage authentication state](#manage-authentication-state). -4. [Access user data](#access-user-data). - -{/* To see this guide in action, check out a full example [here](https://github.com/hiro-so/stacks-connect-example). */} - ---- - -## Install the @stacks/connect package - -```package-install -@stacks/connect -``` - -## Connect to a user's wallet - -After installing the `@stacks/connect` package, you can use the `connect` function to initiate a wallet connection. This will trigger a popup that allows users to select and connect their wallet. - -```ts -import { connect } from '@stacks/connect'; - -async function authenticate() { - const response = await connect(); - // response contains the user's addresses -} -``` - -
-
-
- -
-
- -
-
-
- -The `connect` function stores the user's addresses in local storage by default, making it easy to persist the user's session across page reloads and browser sessions. - -You can customize the connection behavior by passing options to the `connect` function, such as forcing wallet selection or specifying default providers. See the [advanced usage](/stacks/connect/packages/connect#advanced-usage) section for more details. - -## Manage authentication state - -You can manage the user's authentication state using the following functions: - -```ts -import { connect, disconnect, isConnected } from '@stacks/connect'; - -// Check if user is connected -const authenticated = isConnected(); - -// Connect to wallet -await connect(); - -// Disconnect user -disconnect(); // clears local storage and selected wallet -``` - -## Access user data - -Once connected, you can access the user's data using the `getLocalStorage` function or make specific requests using the `request` method: - -```ts -import { getLocalStorage, request } from '@stacks/connect'; - -// Get stored user data -const userData = getLocalStorage(); -// { -// "addresses": { -// "stx": [ -// { "address": "SP2MF04VAGYHGAZWGTEDW5VYCPDWWSY08Z1QFNDSN" }, -// ], -// "btc": [ -// { "address": "bc1pp3ha248m0mnaevhp0txfxj5xaxmy03h0j7zuj2upg34mt7s7e32q7mdfae" }, -// ] -// } -// } - -// Get detailed account information -const accounts = await request('stx_getAccounts'); -// { -// "addresses": [ -// { -// "address": "SP2MF04VAGYHGAZWGTEDW5VYCPDWWSY08Z1QFNDSN", -// "publicKey": "02d3331cbb9f72fe635e6f87c2cf1a13cd...", -// "gaiaHubUrl": "https://hub.hiro.so", -// "gaiaAppKey": "0488ade4040658015580000000dc81e3a5..." -// } -// ] -// } -``` - -For a list of all available methods, see the [reference](/stacks/connect/packages/connect) page. - ---- - -## Next steps - - - - - \ No newline at end of file diff --git a/content/docs/stacks/connect/guides/broadcast-transactions.mdx b/content/docs/stacks/connect/guides/broadcast-transactions.mdx deleted file mode 100644 index 1b6e147b4..000000000 --- a/content/docs/stacks/connect/guides/broadcast-transactions.mdx +++ /dev/null @@ -1,185 +0,0 @@ ---- -title: Broadcast transactions -description: Prompt users to sign transactions and broadcast them to the Stacks blockchain. ---- - -import { Badge } from '@/components/ui/badge'; -import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; - -import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; -import { ChevronRight, Code, Terminal } from 'lucide-react'; -import { File, Folder, Files } from 'fumadocs-ui/components/files'; - -The process of broadcasting transactions is fundamental for interacting with blockchains, whether you're transferring tokens, deploying contracts, or executing contract functions. - -In this guide, you will learn how to: - -1. [Install the necessary packages](#setup-and-installation) -2. [Connect to a user's wallet](#connect-to-a-users-wallet) -3. [Sign and broadcast transactions](#sign-and-broadcast-transactions) -4. [Handle transaction results](#handle-transaction-results) - ---- - -## Setup and installation - -Install the required packages to start building and broadcasting transactions: - -```package-install -@stacks/connect @stacks/transactions -``` - -## Connect to a user's wallet - -Before signing transactions, users need to connect their wallet to your application. Use the `connect` function to initiate a wallet connection: - -```ts -import { connect, isConnected } from '@stacks/connect'; - -async function connectWallet() { - if (!isConnected()) { - const response = await connect(); - console.log('Connected with addresses:', response); - } -} -``` - - - For more details on wallet connection, see the [authentication guide](/stacks/connect/guides/authenticate-users). - - -## Sign and broadcast transactions - -There are three types of transactions you can create: STX transfers, contract deployments, and contract calls. - - - - - STX transfer - - - Contract deployment - - - Contract execution - - - - To transfer STX tokens, use the `request` method with `stx_transferStx`: - - ```ts - import { request } from '@stacks/connect'; - - async function transferStx() { - const response = await request('stx_transferStx', { - recipient: 'ST2EB9WEQNR9P0K28D2DC352TM75YG3K0GT7V13CV', - amount: '100', // in micro-STX (1 STX = 1,000,000 micro-STX) - memo: 'Reimbursement', // optional - }); - - console.log('Transaction ID:', response.txId); - } - ``` - - - To deploy a smart contract, use the `request` method with `stx_deployContract`: - - ```ts - import { request } from '@stacks/connect'; - - async function deployContract() { - const codeBody = '(define-public (say-hi) (ok "hello world"))'; - - const response = await request('stx_deployContract', { - name: 'my-contract', - code: codeBody, - clarityVersion: 3, // optional, defaults to latest version - }); - - console.log('Transaction ID:', response.txId); - } - ``` - - Contracts will deploy to the Stacks address of the connected wallet. - - - To call a contract function, use the `request` method with 'stx_callContract'. Here's an example using a simple contract: - - ```clarity - (define-public (say-hi) - (print "hi") - (ok u0) - ) - ``` - - Here's how to call this function: - - ```ts - import { request } from '@stacks/connect'; - import { Cl } from '@stacks/transactions'; - - async function callContract() { - const response = await request('stx_callContract', { - contractAddress: 'ST22T6ZS7HVWEMZHHFK77H4GTNDTWNPQAX8WZAKHJ', - contractName: 'my-contract', - functionName: 'say-hi', - functionArgs: [], // array of Clarity values - }); - - console.log('Transaction ID:', response.txId); - } - ``` - - For functions that take arguments, you can use the `Cl` namespace to construct Clarity values: - - ```ts - const functionArgs = [ - Cl.uint(123), - Cl.stringAscii("hello"), - Cl.standardPrincipalCV("ST1X.."), - ]; - ``` - - - -## Handle transaction results - -When a transaction is signed and broadcast, the `request` method returns a response object containing information about the transaction: - -```ts -interface TransactionResponse { - txId: string; // The transaction ID - txRaw: string; // The raw transaction hex -} -``` - -You can use the transaction ID to create a link to view the transaction in the explorer: - -```ts -async function handleTransaction() { - const response = await request('stx_transferStx', { - recipient: 'ST2EB9WEQNR9P0K28D2DC352TM75YG3K0GT7V13CV', - amount: '100', - }); - - const explorerUrl = `https://explorer.stacks.co/txid/${response.txId}`; - console.log('View transaction in explorer:', explorerUrl); -} -``` - ---- - -## Next steps - - - - - diff --git a/content/docs/stacks/connect/guides/migration.mdx b/content/docs/stacks/connect/guides/migration.mdx deleted file mode 100644 index 7e0736162..000000000 --- a/content/docs/stacks/connect/guides/migration.mdx +++ /dev/null @@ -1,103 +0,0 @@ ---- -title: 'Migration Guide' -description: 'How to migrate from v7.x.x to v8.x.x of @stacks/connect' ---- - -import { Steps, Step } from 'fumadocs-ui/components/steps' - - -For a while now, the Stacks community has been working on a new standard for wallet-to-dapp communication. -Stacks Connect and related projects now use standards like [WBIPs](https://wbips.netlify.app/) and [SIP-030](https://github.com/janniks/sips/blob/main/sips/sip-030/sip-030-wallet-interface.md) to allow wallets to communicate with dapps in a more simplified and flexible way. - - -Please be patient during this latest migration. -There has been a long-running effort together with wallets to modernize and move forward the Stacks web ecosystem. -It is now culminating in [SIP-030](https://github.com/janniks/sips/blob/main/sips/sip-030/sip-030-wallet-interface.md) and the new `request` method in Stacks Connect `8.x.x`. -Bear with us during this migration. -Wallets are still working through some bugs, details, and improvements. - -_Feel free to continue using Stacks Connect `7.x.x` while things stabilize._ -The `7.x.x` version may still be more well supported by some wallets. - -For the legacy version of `@stacks/connect` using JWT tokens, you can use: - -```sh -npm install @stacks/connect@7.10.1 -``` - - - -## Deprecations - -The following classes, methods, and types are deprecated in favor of the new `request` RPC methods: - -- `show...` and `open...` methods -- `authenticate` method -- `UserSession` class and related functionality -- `AppConfig` class -- `SessionOptions` interface -- `SessionData` interface -- `UserData` interface -- `SessionDataStore` class -- `InstanceDataStore` class -- `LocalStorageStore` class - - -To make migrating easier, the familiar `UserSession` & `AppConfig` class still exists and is semi-backwards compatible for the `8.x.x` release. -It will "cache" the user's address in local storage and allow access to it via the `loadUserData` method (as previously done). - - -## Migration Steps - -To update from `<=7.x.x` to latest/`8.x.x`, follow these steps: - - - - ```sh - npm install @stacks/connect@latest - ``` - - - - Switch from `showXyz`, `openXyz`, `doXyz` methods to the `request` method: - - - `request` follows the pattern `request(method: string, params: object)`, see [Usage](#usage) for more details - - `request` is an async function, so replace the `onFinish` and `onCancel` callbacks with `.then().catch()` or `try & await` - - Examples: - - `showConnect()`, `authenticate()` → `connect()` - - `useConnect().doContractCall({})` → `request("stx_callContract", {})` - - `openContractDeploy()` → `request("stx_deployContract", {})` - - - - Switch from `showConnect` or `authenticate` to `connect()` methods: - - - `connect()` is an alias for `request({forceWalletSelect: true}, 'getAddresses')` - - `connect()` by default caches the user's address in local storage - - - - - Switch from `UserSession.isSignedIn()` to `isConnected()` - - Switch from `UserSession.signUserOut()` to `disconnect()` - - - - - Remove code referencing deprecated methods (`AppConfig`, `UserSession`, etc.) - - Remove the `@stacks/connect-react` package - - You may need to manually reload a component to see local storage updates - - No custom hooks are needed to use Stacks Connect anymore - - We are working on a new `@stacks/react` package that will make usage even easier in the future (e.g., tracking transaction status, reloading components when a connection is established, updating the page when the network changes, and more) - - - -## Address Access - -Previously, the `UserSession` class was used to access the user's addresses and data, which abstracted away the underlying implementation details. -Now, the `request` method is used to directly interact with the wallet, giving developers more explicit control and clarity over what's happening under the hood. -This manual approach makes the wallet interaction more transparent and customizable. -Developers can manually manage the currently connected user's address in e.g. local storage, jotai, etc. or use the `connect()`/`request()` method to cache the address in local storage. - - -For security reasons, the `8.x.x` release only returns the current network's address (where previously both mainnet and testnet addresses were returned). - diff --git a/content/docs/stacks/connect/guides/sign-messages.mdx b/content/docs/stacks/connect/guides/sign-messages.mdx deleted file mode 100644 index 283a4b81c..000000000 --- a/content/docs/stacks/connect/guides/sign-messages.mdx +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: Sign messages -description: Prompt users to sign a message to prove they control an address or authorize an in-app action. ---- - -import { Badge } from '@/components/ui/badge'; -import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; - -import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; -import { ChevronRight, Code, Terminal } from 'lucide-react'; -import { File, Folder, Files } from 'fumadocs-ui/components/files'; - -With Stacks Connect, users can sign a cryptographic message to prove ownership of a particular address. This is helpful for a wide range of use cases. For example, you can use message signing to create token-gated features (a user signs a message to prove they control an address holding the corresponding token requirements) or to prove the user agreed to your terms of service. - -In this guide, you will learn how to: - -1. [Set up and install necessary packages](#setup-and-installation). -2. [Connect to a user's wallet](#connect-to-a-users-wallet). -3. [Sign messages](#sign-messages). -4. [Verify signatures](#verify-signatures). - ---- - -## Setup and installation - -Using your preferred package manager, install the following packages: - -```package-install -@stacks/connect @stacks/encryption -``` - -## Connect to a user's wallet - -Before signing messages, users need to connect their wallet to your application. Use the `connect` function to initiate a wallet connection: - -```ts -import { connect, isConnected } from '@stacks/connect'; - -async function connectWallet() { - if (!isConnected()) { - const response = await connect(); - console.log('Connected with addresses:', response); - } -} -``` - - - For more details on wallet connection, see the [authentication guide](/stacks/connect/guides/authenticate-users). - - -## Sign messages - -To request a message signature, use the `request` method with `stx_signMessage`: - -```ts -import { request } from '@stacks/connect'; - -async function signMessage() { - const message = 'Hello World'; - - const response = await request('stx_signMessage', { - message, - }); - - console.log('Signature:', response.signature); - console.log('Public key:', response.publicKey); -} -``` - -For structured messages, you can use `stx_signStructuredMessage`: - -```ts -import { request } from '@stacks/connect'; -import { Cl } from '@stacks/transactions'; - -async function signStructuredMessage() { - const message = Cl.tuple({ - structured: Cl.stringAscii('message'), - num: Cl.uint(3) - }); - - const domain = Cl.tuple({ - name: Cl.stringAscii('My App'), - version: Cl.stringAscii('1.0.0'), - 'chain-id': Cl.uint(1) - }); - - const response = await request('stx_signStructuredMessage', { - message, - domain - }); - - console.log('Signature:', response.signature); - console.log('Public key:', response.publicKey); -} -``` - -## Verify signatures - -To verify a signature, use the `verifyMessageSignatureRsv` function from the `@stacks/encryption` package: - -```ts -import { verifyMessageSignatureRsv } from '@stacks/encryption'; - -async function verifySignature() { - const message = 'Hello World'; - - const response = await request('stx_signMessage', { - message - }); - - const { signature, publicKey } = response; - - const verified = verifyMessageSignatureRsv({ - message, - signature, - publicKey - }); - - if (verified) { - console.log('Signature verified!'); - } -} -``` - ---- - -## Next steps - - - - - diff --git a/content/docs/stacks/connect/index.mdx b/content/docs/stacks/connect/index.mdx deleted file mode 100644 index 02f21d467..000000000 --- a/content/docs/stacks/connect/index.mdx +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Overview -description: A JavaScript library for authenticating users as well as signing transactions and messages. ---- - -import { SecondaryCard } from '@/components/card'; - -Stacks Connect is a JavaScript library that can authenticate the identity of your users and prompt them to sign transactions and messages. In other words, Stacks Connect handles some of the most basic functions you need in a web app, including enabling users to log in to your app as well as broadcasting in-app transactions to the Stacks network. - -## Installation - -```package-install -@stacks/connect -``` - -## Guides - - - - - - - -## Related tools - -- **[Clarinet](/stacks/clarinet)**: Build your app in the go-to development environment on Stacks. -- **[Stacks Blockchain API](/stacks/api)**: Fetch data and broadcast transactions with the Stacks Blockchain API. -- **[Stacks.js](/stacks/stacks.js)**: A collection of JavaScript libraries to build web applications on Stacks. - -
- - -Reach out to us on the #stacks-js channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET. - \ No newline at end of file diff --git a/content/docs/stacks/connect/meta.json b/content/docs/stacks/connect/meta.json deleted file mode 100644 index 85203efaa..000000000 --- a/content/docs/stacks/connect/meta.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "title": "Stacks Connect", - "root": true, - "pages": [ - "---Stacks Connect---", - "index", - "quickstart", - "support", - "---Guides---", - "guides/migration", - "guides/authenticate-users", - "guides/broadcast-transactions", - "guides/sign-messages", - "---Reference---", - "...packages" - ] -} diff --git a/content/docs/stacks/connect/quickstart.mdx b/content/docs/stacks/connect/quickstart.mdx deleted file mode 100644 index 64b5c81ee..000000000 --- a/content/docs/stacks/connect/quickstart.mdx +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: Quickstart -description: Learn how to transfer STX tokens via a web wallet using Stacks Connect. ---- - -import { ChevronRight, Code, Terminal, Folder as FolderIcon } from 'lucide-react'; -import { File, Folder, Files } from 'fumadocs-ui/components/files'; -import { Steps, Step } from 'fumadocs-ui/components/steps'; - -In this quickstart guide, you will learn how to set up your project, authenticate users with a web wallet, and initiate a STX token transfer. - -For a deeper dive into the authentication process, check out the [authenticate users](/stacks/connect/guides/authenticate-users) guide. - ---- - - - - ## Install package dependencies - - Add the necessary packages to your project using your preferred package manager. - - ```package-install - @stacks/connect - ``` - - - ## Connect to a wallet - - The `connect` function stores the user's address in local storage by default, making it easy to persist the user's session across page reloads and browser sessions. - - ```ts connect.ts - import { connect } from '@stacks/connect'; - - const response = await connect(); - ``` - - To access the user's addresses, you can use the `getLocalStorage` function. - - ```ts storage.ts - import { getLocalStorage } from '@stacks/connect'; - - const data = getLocalStorage(); - ``` - - You can manage the connection's state using the following: - - ```ts connect.ts - import { connect, disconnect, isConnected } from '@stacks/connect'; - - isConnected(); // false - await connect(); // similar to the `getAddresses` method - isConnected(); // true - disconnect(); // clears local storage and selected wallet - isConnected(); // false - ``` - - - ## Use `request` to trigger a transfer - - The process of connecting to a wallet gives the web app information about the wallet account, which enables interactions with the Stacks blockchain, like calling smart contracts. - - Using the `request` function, you can trigger wallet interactions using the `stx_transferStx` method. - - ```tsx connect.tsx - const response = await request('stx_transferStx', { - amount: '1000', // amount in micro-STX (1 STX = 1,000,000 micro-STX) - recipient: 'SP2MF04VAGYHGAZWGTEDW5VYCPDWWSY08Z1QFNDSN', // recipient address - network: 'mainnet', // optional, defaults to mainnet - memo: 'Optional memo', // optional memo field - }); - ``` - - - -## Next steps - - - - - - diff --git a/content/docs/stacks/connect/support.mdx b/content/docs/stacks/connect/support.mdx deleted file mode 100644 index 2c06f1cf0..000000000 --- a/content/docs/stacks/connect/support.mdx +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: 'Wallet Support' -description: 'Compatibility information for different wallet providers' ---- - -import { - Table, - TableBody, - TableCell, - TableHead, - TableHeader, - TableRow -} from "@/components/ui/table"; - -This page provides detailed information about which methods and events are supported by different wallet providers in the Stacks ecosystem. - -## Method Compatibility - - - - - Method - Leather - Xverse-like - - - - - getAddresses - 🟡 No support for experimental purposes - 🟡 Use wallet_connect instead - - - sendTransfer - 🟡 Expects amount as string - 🟡 Expects amount as number - - - signPsbt - 🟡 Uses signing index array only - 🟡 Uses signInputs record instead of array - - - stx_getAddresses - 🟢 - 🔴 - - - stx_getAccounts - 🔴 - 🟢 - - - stx_getNetworks - 🔴 - 🔴 - - - stx_transferStx - 🟢 - 🟢 - - - stx_transferSip10Ft - 🟢 - 🔴 - - - stx_transferSip9Nft - 🟢 - 🔴 - - - stx_callContract - 🟡 Hex-encoded Clarity values only - 🟡 Hex-encoded Clarity values only, no support for postConditions - - - stx_deployContract - 🟡 Hex-encoded Clarity values only - 🟡 Hex-encoded Clarity values only, no support for postConditions - - - stx_signTransaction - 🟡 Hex-encoded Clarity values only - 🟡 Hex-encoded Clarity values only - - - stx_signMessage - 🟡 Hex-encoded Clarity values only - 🟡 Hex-encoded Clarity values only - - - stx_signStructuredMessage - 🟡 Hex-encoded Clarity values only - 🟡 Hex-encoded Clarity values only - - - stx_updateProfile - 🔴 - 🔴 - - -
- -## Event Compatibility - - - - - Event - Leather - Xverse - - - - - stx_accountChange - 🔴 - 🔴 - - - stx_networkChange - 🔴 - 🔴 - - -
- -**Legend** - -- 🔴 No support (yet) -- 🟡 Partial support -- 🟢 Supported - -## Compatibility Layer - -The `request` method in `@stacks/connect` adds a layer of auto-compatibility for different wallet providers. This helps unify the interface where wallet providers may implement methods and results differently. - -| Method | Status | Notes | -| --------------------------- | ------ | ---------------------------------------------------------------------------------------------------- | -| `getAddresses` | 🔵 | Maps to `wallet_connect` for Xverse-like wallets | -| `sendTransfer` | 🔵 | Converts `amount` to number for Xverse, string for Leather | -| `signPsbt` | 🟡 | Transforms PSBT format for Leather (base64 to hex) with lossy restructure of `signInputs` | -| `stx_getAddresses` | 🔵 | Maps to `wallet_connect` for Xverse-like wallets | -| `stx_callContract` | 🔵 | Transforms Clarity values to hex-encoded format for compatibility | -| `stx_deployContract` | 🔵 | Transforms Clarity values to hex-encoded format for compatibility | -| `stx_signTransaction` | 🔵 | Transforms Clarity values to hex-encoded format for compatibility | -| `stx_signMessage` | 🔵 | Transforms Clarity values to hex-encoded format for compatibility | -| `stx_signStructuredMessage` | 🔵 | Transforms Clarity values to hex-encoded format for compatibility | - -- 🟢 No overrides needed for any wallet -- 🔵 Has compatibility overrides that maintain functionality -- 🟡 Has breaking overrides that may lose some information diff --git a/content/docs/stacks/contributors-guide.mdx b/content/docs/stacks/contributors-guide.mdx deleted file mode 100644 index 1848ec856..000000000 --- a/content/docs/stacks/contributors-guide.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: Contributors guide -description: Learn how to contribute to Hiro's documentation and content. ---- - -import ContributorsGuideContent from '@/snippets/contributors-guide.mdx'; - - diff --git a/content/docs/stacks/explorer/guides/build-explorer.mdx b/content/docs/stacks/explorer/guides/build-explorer.mdx deleted file mode 100644 index 5fd4a7480..000000000 --- a/content/docs/stacks/explorer/guides/build-explorer.mdx +++ /dev/null @@ -1,38 +0,0 @@ ---- -title: Build a Stacks Explorer -description: Run a local instance of the Stacks Explorer. ---- - -The Stacks Explorer frontend user interface is built with [React](https://reactjs.org/), [next.js](https://github.com/vercel/next.js) and [@stacks/ui](https://github.com/hirosystems/ui). - -Before you can run the explorer on your machine locally, you must first clone the [Stacks Explorer](https://github.com/hirosystems/explorer) repository to obtain all of the necessary files and libraries needed. - -# Project dependencies - -Once you have cloned the Stacks Explorer repositories, you will need to install the following project dependencies: - -- [NodeJS](https://nodejs.dev/en/) that includes `npm` -- [PNPM](https://pnpm.io/installation/) -- [Homebrew](https://brew.sh/) - -> **_NOTE:_** -> -> Although Homebrew is not required to install and operate the Stacks Explorer, it is highly recommended. - -Open your terminal window, and make sure you are in the `/explorer` folder. Run the below command to install the dependencies: - -`pnpm i` - -After installing and configuring your environment, you can run the Stacks Explorer locally if you wish by running the following command: - -`pnpm dev` - -## Building for production - -You may also build a production version of the Stacks Explorer. To do that, simply run the following command: - -`pnpm build` - -> **NOTE:** -> -> Running `pnpm build` also run the default next.js build task. diff --git a/content/docs/stacks/explorer/index.mdx b/content/docs/stacks/explorer/index.mdx deleted file mode 100644 index 83218217c..000000000 --- a/content/docs/stacks/explorer/index.mdx +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: Overview -description: Explore and verify data on the Stacks blockchain. -toc: false ---- - -import Link from "next/link"; -import { Button } from "@/components/ui/button" - -The Stacks Explorer lets you explore on-chain data, troubleshoot pending transactions, edit and deploy contracts via the sandbox, discover new tokens, and more. We maintain and support the [Stacks Explorer](https://explorer.hiro.so) as a service for the community, but you can also run your own instance of the explorer. - -
- - {/* */} -
- -## Related tools - -- **[Stacks Blockchain API](/stacks/api)**: Looking for on-chain data without the front end? Leverage the Stacks Blockchain API. -- **[Ordinals Explorer](/bitcoin/explorer)**: Explore Bitcoin Ordinals and BRC-20 tokens via the Ordinals Explorer. - ---- - -Need help building with Stacks Explorer? Reach out to us on the `#stacks-explorer` channel on Discord under the [Hiro Developer Tools section](https://stacks.chat/). There’s also a [weekly office hours](https://events.stacks.co/event/HD16484710) on Discord every Thursday at 11am ET. diff --git a/content/docs/stacks/explorer/meta.json b/content/docs/stacks/explorer/meta.json deleted file mode 100644 index 71e330837..000000000 --- a/content/docs/stacks/explorer/meta.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "title": "Explorer", - "root": true, - "pages": [ - "---Stacks Explorer---", - "index" - ] -} diff --git a/content/docs/stacks/get-started.mdx b/content/docs/stacks/get-started.mdx deleted file mode 100644 index 566d3d918..000000000 --- a/content/docs/stacks/get-started.mdx +++ /dev/null @@ -1,117 +0,0 @@ ---- -title: Get started -description: The following guides cover ways to use Hiro tools to build apps on Stacks. -icon: Play -toc: false ---- - -import { Database, Ticket } from 'lucide-react'; -import { Blockchain, BitcoinIcon, Clarinet, Container, DAO, Js, Plant, Shapes, StacksIcon } from '@/components/ui/icon'; -import { SecondaryCard, SmallCard } from '@/components/card'; - -
- - - } - href="/stacks/clarinet/quickstart" - title="Create your first smart contract" - description="Build a simple counter contract using Clarinet." - tag='Clarinet' - /> - } - href="/stacks/clarinet-js-sdk/quickstart" - title="Write unit tests for your smart contracts" - description="Learn how run unit tests with Clarinet JS SDK." - tag='Clarinet JS SDK' - /> - } - href="/stacks/stacks.js/quickstart" - title="Make a contract call with Stacks.js" - description="Learn how to integrate smart contracts into your app." - tag='Stacks.js' - /> - } - href="/stacks/chainhook/quickstart" - title="Stream custom blockchain events" - description="Use Chainhook to filter & stream for contract deployments." - tag='Chainhook' - /> - - -
- -

- Learn by example -

- ---- - - - } - href="/guides/build-an-nft-marketplace" - title="Build an NFT Marketplace" - description="Learn how to create and deploy your own NFT marketplace." - /> - {/* } - href="/stacks/clarinet" - title="Launch a Decentralized Autonomous Organization (DAO)" - description="Discover the steps to creating your own DAO." - /> */} - } - href="/guides/no-loss-lottery" - title="Create a no-loss lottery pool" - description="Build a no-loss lottery pool that leverages stacking yield." - /> - } - href="/guides/build-a-decentralized-kickstarter" - title="Build a decentralized Kickstarter" - description="Learn how to create a crowdfunding app, enabling creators to fund their projects without a third party." - /> - - -
- -
- -

- Installation guides -

- ---- - - - } - href="/guides/sync-a-bitcoin-node" - title="Sync a Bitcoin node" - description="Set up and run a Bitcoin node to run tools like Chainhook as a service." - /> - } - href="/guides/sync-a-stacks-node" - title="Sync a Stacks node" - description="Set up and run a Stacks node to use tools like Chainhook or spin up your own API." - /> - } - href="/guides/installing-docker" - title="Install and run Docker on your machine" - description="Essential for running a local development with Clarinet" - /> - - -
- - -For more, check out our [guides](/guides) section. - - -
diff --git a/content/docs/stacks/hacks/archive/ai.mdx b/content/docs/stacks/hacks/archive/ai.mdx deleted file mode 100644 index 130a4b16f..000000000 --- a/content/docs/stacks/hacks/archive/ai.mdx +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: AI x Stacks -description: Build something that combines AI capabilities with Stacks. ---- - -## January: AI x Stacks - -*Build something that combines AI capabilities with Stacks blockchain technology* - -**Timeline**: January 22-28, 2025 - -This month's challenge invites you to explore the intersection of artificial intelligence and blockchain technology. Create innovative solutions that leverage both AI capabilities and the Stacks blockchain. - -Submit your project [here](https://hirohacks25.paperform.co/). - - - -## Example project ideas - -### 1. AI Contract Analyzer -- Build a tool that uses LLMs to audit and explain [Clarity contracts](/stacks/clarity) -- Help developers understand and improve their smart contracts through AI-powered analysis -- Provide suggestions for security improvements and optimizations - -### 2. Smart Wallet Assistant -- Create an AI-powered [wallet](/stacks/stacks.js) that helps users make informed decisions -- Analyze transaction history and provide personalized insights -- Offer predictive analytics and spending recommendations - -### 3. Chain Detective -- Develop an AI tool that analyzes on-chain data to discover interesting patterns -- Use [Chainhook](/stacks/chainhook) to stream and analyze blockchain events in real-time -- Generate visualizations and reports of blockchain activity - -_Review the [submission guidelines](/stacks/hacks/#rules) for project requirements and join the [Stacks Discord](https://stacks.chat) to connect with other builders._ - ---- - -## Resources - -- [Clarity Codex](https://github.com/leahjlou/clarity-codex/) -- [Stacks Discord](https://stacks.chat) \ No newline at end of file diff --git a/content/docs/stacks/hacks/archive/build-a-custom-api.mdx b/content/docs/stacks/hacks/archive/build-a-custom-api.mdx deleted file mode 100644 index cefed38dc..000000000 --- a/content/docs/stacks/hacks/archive/build-a-custom-api.mdx +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: Build a custom blockchain API -description: Learn how to build a custom API with Chainhook. ---- - -import { HackBadge } from "@/components/badge"; - - -This hack has been archived. Feel free to continue to use the code in this guide as a reference for your own projects. - - -## Introduction - -In the previous hacks, you built some pretty complex smart contracts. But building a robust UI/UX around these smart contracts and their on-chain data can be challenging due to the nature of blockchains. - -Let's take the [decentralized grants program](/stacks/hacks/build-a-decentralized-grants-program) hack as an example. In this project, anyone can propose a grant, and these proposals are voted on by token holders. The details of each proposal, including the title, description, and the proposal contract, are stored on the blockchain. - -However, directly querying the blockchain for this data every time you want to display it in your application's UI can be slow and inefficient. And that information might not always be formatted and organized in a way that makes sense for your use case. - -This is where [Chainhook](/stacks/chainhook) comes in. Chainhook allows you to listen for specific on-chain events, such as the submission of a new grant proposal, and trigger actions in response - like inserting specific data into a database to query off-chain. - -In this guide, you'll build a custom API with Chainhook using the [Hiro Platform](https://platform.hiro.so/), with a focus on integrating it with the contracts you built for the decentralized grants program hack. - -## Creating a server - -In this section, we'll briefly discuss setting up an Express server to handle incoming event data from Chainhook. While a detailed walkthrough of setting up an Express server is beyond the scope of this guide, you can reference an example app [here](https://github.com/hirosystems/examples/tree/main/apps/chainhook). - -To illustrate how to handle this event data, here is an example `server.ts` file: - -```typescript -const express = require("express") -const app = express() -app.use(express.json()) - -app.post("/api/events", (req, res) => { - const events = req.body - // Process the event data here - res.status(200).send({ message: "Event received" }) -}) - -app.listen(3000, () => { - console.log("Server is running on port 3000") -}) -``` - -In this example, the server listens for POST requests at the `/api/events` route. When a request is received from your chainhook (which you will set up in the next section), you can extract the event data from the request body and process it. - -## Parsing the event data - -The Chainhook payload comes with a lot of information, so let's break down some of the more important parts inside of the `req.body` for this guide. - -Here is a truncated look at the payload structure from Chainhook: - -```json -{ - "apply": [ - { - "transactions": [ - { - "metadata": { - "receipt": "..." - }, - "operations": [ - { - "...": "..." - } - ] - } - ] - } - ] -} -``` - -Each item in the `apply` array should contain a `transactions` array. Each `transaction` object should have a `metadata` object with a `receipt` attribute and an `operations` array. - -- `transaction.metadata.receipt`: This attribute contains information about any events that were triggered from the function. -- `transaction.operations`: This is an array that contains more specific information about what happened as a result of the function call. For instance if a _token transfer_ occured, each object inside this array would contain various attributes and information regarding the account, amount, type, and status of the token transfer. - -Here's what your POST route might look like after filtering for the relevant data in your `server.ts` file: - -```typescript -app.post("/api/events", async (req, res) => { - const events = req.body - // Loop through each item in the apply array - events.apply.forEach((item: any) => { - // Loop through each transaction in the item - item.transactions.forEach((transaction: any) => { - // If the transaction has operations, loop through them - if (transaction.operations) { - transaction.operations.forEach((operation: any) => { - // Log the operation - console.log({ operation }) - }) - } - }) - }) - - // Send a response back to Chainhook to acknowledge receipt of the event - res.status(200).send({ message: "Proposal added!" }) -}) -``` - -For the next section, you will need to expose your local server via `https` so that Chainhook can deliver the `payload`. To do that, run the following command: - -```terminal -$ npx localtunnel --port -``` - -> _**Note**_ -> -> There are several tools for exposing localhost to the world so choose the one you prefer. For more information on `localtunnel`, click [here](https://github.com/localtunnel/localtunnel). - -## Integrating with Chainhook - -In this section, you will integrate Chainhook with your smart contracts. This involves creating a chainhook predicate that matches the specific on-chain events you want to respond to. For this process, you'll use the [Hiro Platform](https://platform.hiro.so/), which provides a user-friendly interface for creating and managing your chainhooks. By the end of this section, you'll have a chainhook set up and ready to trigger actions in response to on-chain events. - -## Deploying your contracts to testnet - -In order to create your chainhook, you need to deploy your contracts to `testnet`. From your projects page, click on the Deploy button near the top right of your screen. You'll see your deployment options: choose "Generate for Testnet." - -> _**Note**_ -> -> The Platform will provide a step for requesting Testnet STX, but you can also go straight to the [Stacks Testnet Faucet](https://explorer.hiro.so/sandbox/faucet?chain=testnet). Once you have testnet STX tokens, you can deploy your contracts to testnet using the same methods you used for devnet, but with the network parameter set to testnet. - -## Creating a Chainhook - -Now it's time to create your first Chainhook. Start by creating a predicate that matches the `propose` function in your `proposal-submission` contract. This function is called when a new grant proposal is submitted. - -Here's an example of how you might define this `predicate.json` file for your contract: - -```json -{ - "chain": "stacks", - "uuid": "1", - "name": "New Grant Proposal", - "version": 1, - "networks": { - "testnet": { - "if_this": { - "scope": "contract_call", - "contract_identifier": "ST2BSV94A650WGZ2YZ5Y8HM93W01NGT4GY0MGJECG.proposal-submission", - "method": "propose" - }, - "then_that": { - "http_post": { - "url": "", - "authorization_header": "Bearer 12345" - } - }, - "start_block": 138339 - } - } -} -``` - - - Make sure to swap out the details in your `predicate.json` file to match your - contracts ABI. - - -The `if_this` section specifies the conditions for the events that this Chainhook will respond to. In this case, it's looking for calls to the `propose` method in the `proposal-submission` contract on the Stacks testnet. - -The `then_that` section specifies what action the Chainhook should take when it detects an event that matches the `if_this` conditions. Here, it's set up to send a POST request to your specified URL with the event data. - -The `start_block` field is used to specify the starting block for the Chainhook to start listening from. This is useful for ignoring blocks that were mined before the Chainhook was set up. - -Once you have created a similar file for your specific contract. select the _Chainhooks_ tab inside your project and upload your predicate file using the _Upload Chainhook_ option. For more information, you can follow the [Create Chainhooks](/stacks/platform/guides/create-chainhooks) section. - -## Testing your chainhook - -Once you've successfully uploaded your chainhook predicate, it's time to test it out. You can do this by performing an action that aligns with your `if_this` - `then_that` logic. - -For instance, if your Chainhook is set up to respond to a specific contract call, you can trigger that call and then check your `/api/post` endpoint. If everything is set up correctly, you should see any information you've requested to be logged. - -The next section presents several challenges that will help you put the finishing touches on your API. With the foundation you've built, you're well-equipped to take on these challenges and continue your journey in building robust, decentralized applications. - -Congratulations on reaching this point! You now have all the building blocks needed to create a custom API using Chainhook and integrate it with your smart contracts. This is a significant step towards enhancing the functionality and user experience of your decentralized applications. - - - This is a crucial step in verifying that your Chainhook is working as - expected. If you don't see the expected output, you may need to revisit your - predicate and ensure it's correctly configured. - - -## Challenges - -The following challenges are additional features you can implement to further explore building on Stacks. Feel free to add any other features you want. - - - -**Create more than 1 chainhook**: Don't stop at just 1! Follow the process above to create more than 1 chainhook for your dApp and parse the data accordingly. - - - -**Create consumer-facing API endpoints**: Up until now, we've shown you how to capture and process the initial `payload` data sent from a chainhook. However, to provide a robust user experience, you'll want to do more than just output raw data. The challenge here is to create additional API endpoints that present the filtered and extracted data from the initial `/api/events` payload in a consumer-friendly format. This could involve adding a database layer for organizing the data, adding additional context, or transforming the data to match the needs of your application's frontend. For a quick db setup, you can try using something like [Supabase](https://supabase.com/docs/guides/getting-started/quickstarts/reactjs). - -```typescript -// Example using Supabase - -const supabase = createClient( - "https://.supabase.co", - "" -) - -app.post("/api/events", async (req, res) => { - // ... - - item.transactions.forEach((transaction: any) => { - if (transaction.operations) { - transaction.operations.forEach((operation: any) => { - const data = operation // Parse out the data you want - // Insert and save it to db - const { error } = await supabase.from("proposals").insert(data) - }) - } - }) - - // ... -}) -``` - - - -**UI integration**: The final challenge is to integrate your consumer-facing API into your frontend. This involves taking the data you've processed and organized in your API and displaying it in a meaningful and user-friendly way in your application. This could involve creating dynamic components that update in response to new data, adding interactive elements that allow users to explore the data, or incorporating visualizations to help users understand the data. diff --git a/content/docs/stacks/hacks/archive/build-a-decentralized-grants-program.mdx b/content/docs/stacks/hacks/archive/build-a-decentralized-grants-program.mdx deleted file mode 100644 index cedf78db5..000000000 --- a/content/docs/stacks/hacks/archive/build-a-decentralized-grants-program.mdx +++ /dev/null @@ -1,594 +0,0 @@ ---- -title: Build a decentralized grants program -description: Learn how to build a decentralized grants program with governance, submissions, and voting. ---- - -import { HackBadge } from "@/components/badge"; - - -This hack has been archived. Feel free to continue to use the code in this guide as a reference for your own projects. - - -## Introduction - -Welcome to a world where funding for innovative projects is fluid and controlled by a community of token holders, not just a select few. This is the value proposition of a decentralized grants program. In this guide, you will build such a program using the [ExecutorDAO](https://github.com/MarvinJanssen/executor-dao) protocol on the Stacks blockchain. - -Key features of this project include: - -**Decentralized Governance**: Anyone holding a `membership-token` can vote on grant proposals. - -**Open Proposal Submission**: Anyone can propose a grant, encouraging a wide range of ideas and projects. - -**Smart Contract Automation**: All aspects of the grants program, from proposal submission to voting and fund distribution, are automated through smart contracts, ensuring transparency and tamper-proof processes. - -This Hack walks you through the basics of building a decentralized grants program. Over the course of this hack, you will deploy your own functioning grants program. - -There are also optional challenges at the end to further stretch your skills. - -Now it's time to hack. First, we'll cover the basics of the core functionalities of our grants program and look at 4 contracts. Let's dive in. - -## Understanding the ExecutorDAO protocol - -ExecutorDAO is a powerful and flexible protocol that allows for the creation of decentralized autonomous organizations (DAOs) with a high degree of modularity and customization. ExecutorDAO operates on three core tenets: - -**Proposals are smart contracts**: -Proposals in ExecutorDAO are expressed as smart contracts, allowing for precise, logical descriptions of the operations, duties, and members of the DAO. In our case, each grant application is a proposal expressed as a smart contract. - -**The core executes, the extensions give form**: -ExecutorDAO starts with a single core contract whose sole purpose is to execute proposals and keep a list of authorized `extensions`. Extensions are contracts that can be enabled or disabled by proposals and add specific features to the DAO - like _proposing grants_, _voting on grants_, _distributing funds_, and more. - -**Ownership control happens via sending context**: -ExecutorDAO follows a single-address ownership model. The core contract is the de facto owner of external ownable contracts. This allows any proposal or extension to act upon it, like the `membership-token` we will build out in the sections below. - -For more details, you can [view the standard contracts](https://github.com/MarvinJanssen/executor-dao/tree/main/contracts) in the ExecutorDAO repository. - -## Clone the starter template - -Start by setting up your development environment. We've prepared a repository that includes an initialized Clarinet project and a React frontend with some boilerplate code and all the required packages. - -To clone the repository, open your terminal and run the following command: - -```terminal -$ git clone https://github.com/hirosystems/hiro-hacks-template.git -$ cd hiro-hacks-template -``` - -## Establishing your core contract - -Before creating your core contract, you need to create `trait` contracts that you'll be implementing for your grants program. - -Traits in Clarity define a set of functions that a contract must implement. In this case, any contract that wants to be a `proposal` or an `extension` must implement the functions defined in the `proposal-trait` and `extension-trait` respectively. - -In your project's directory, run the following command: - -```terminal -$ clarinet contract new extension-trait && clarinet contract new proposal-trait -``` - -Now in your contracts, respectively, add the following code: - -```clarity extension-trait.clar -(define-trait extension-trait - ( - (callback (principal (buff 34)) (response bool uint)) - ) -) -``` - -```clarity proposal-trait.clar -(define-trait proposal-trait - ( - (execute (principal) (response bool uint)) - ) -) -``` - -Now that you've defined how your set of functions must be implemented, you can begin to create your core contract. First run the following command: - -```terminal -$ clarinet contract new core -``` - -This will create a new contract in the `contracts` directory called `core.clar`. - -Inside your `core.clar` contract, add the two trait contracts you've just created from the steps above: - -```clarity core.clar -(use-trait proposal-trait .proposal-trait.proposal-trait) -(use-trait extension-trait .extension-trait.extension-trait) -``` - -## Error handling and state management - -Next, you need to define some basic error handling and variables for managing your contracts: - -```clarity core.clar -(define-constant ERR_UNAUTHORIZED (err u1000)) -(define-constant ERR_ALREADY_EXECUTED (err u1001)) -(define-constant ERR_INVALID_EXTENSION (err u1002)) - -(define-data-var executive principal tx-sender) -(define-map executedProposals principal uint) -(define-map extensions principal bool) -``` - -These constants represent error codes that the contract can return. The variables store the executive principal (the owner of the grants program), a map of executed proposals, and a map of authorized extensions. - -## Authorization check - -The `is-self-or-extension` function is a private function that checks if the caller of a function is the contract itself or an authorized extension: - -```clarity core.clar -(define-private (is-self-or-extension) - (ok (asserts! (or (is-eq tx-sender (as-contract tx-sender)) (is-extension contract-caller)) ERR_UNAUTHORIZED)) -) - -(define-read-only (is-extension (extension principal)) - (default-to false (map-get? extensions extension)) -) - -(define-read-only (executed-at (proposal )) - (map-get? executedProposals (contract-of proposal)) -) -``` - -## Extension management - -Here's a function to enable or disable an extension (`set-extension`): - -```clarity core.clar -(define-public (set-extension (extension principal) (enabled bool)) - (begin - (try! (is-self-or-extension)) - (print {event: "extension", extension: extension, enabled: enabled}) - (ok (map-set extensions extension enabled)) - ) -) -``` - -## Proposal execution - -The `execute` function allows for the execution of a proposal: - -```clarity core.clar -(define-public (execute (proposal ) (sender principal)) - (begin - (try! (is-self-or-extension)) - (asserts! (map-insert executedProposals (contract-of proposal) block-height) ERR_ALREADY_EXECUTED) - (print {event: "execute", proposal: proposal}) - (as-contract (contract-call? proposal execute sender)) - ) -) -``` - -This function checks if the caller is authorized, inserts the proposal into the `executedProposals` map, and then calls the `execute` function of the proposal contract. - -## Bootstrap - -The `construct` function is used to bootstrap the grants program: - -```clarity core.clar -(define-public (construct (proposal )) - (let - ( - (sender tx-sender) - ) - (asserts! (is-eq sender (var-get executive)) ERR_UNAUTHORIZED) - (var-set executive (as-contract tx-sender)) - (as-contract (execute proposal sender)) - ) -) -``` - -This function checks if the caller is the executive, sets the executive to the contract itself, and then executes the provided proposal. - -## Extension requests - -The request-extension-callback function allows an extension to request a callback: - -```clarity core.clar -(define-public (request-extension-callback (extension ) (memo (buff 34))) - (let - ( - (sender tx-sender) - ) - (asserts! (is-extension contract-caller) ERR_INVALID_EXTENSION) - (asserts! (is-eq contract-caller (contract-of extension)) ERR_INVALID_EXTENSION) - (as-contract (contract-call? extension callback sender memo)) - ) -) -``` - -This function checks if the caller is an authorized extension and then calls the `callback` function of the extension contract. - -These are the key components of the ExecutorDAO core contract. Understanding these will help you in building your own extensions and proposals. - -## Create your membership token - -In this section, you will create your first `extension`, a non-transferable membership token, which will be used to grant voting rights on proposals. The token will be initially distributed to certain addresses during the bootstrapping process. However, new minting (distribution) and burning (removal) of tokens can be managed through proposals. - -To create your membership token, navigate to your project's directory and run the following command: - -```terminal -$ clarinet contract new membership-token -``` - -This will create a new contract in the contracts directory called `membership-token.clar`. - -Let's walk through the key components of this contract. - -## Constants and variables - -The contract defines some constants and variables: - -```clarity membership-token.clar -(define-constant ERR_UNAUTHORIZED (err u2000)) -(define-constant ERR_NOT_TOKEN_OWNER (err u2001)) -(define-constant ERR_MEMBERSHIP_LIMIT_REACHED (err u2002)) - -(define-fungible-token sGrant) - -(define-data-var tokenName (string-ascii 32) "sGrant") -(define-data-var tokenSymbol (string-ascii 10) "SGT") -(define-data-var tokenUri (optional (string-utf8 256)) none) -(define-data-var tokenDecimals uint u6) -``` - -These constants represent error codes that the contract can return. The variables store the token name, symbol, URI, and decimals. The define-fungible-token function is used to define our sGrant token. - -## Authorization check - -The `is-dao-or-extension`, function is a private function that checks if the caller of a function is the core contract itself or an authorized extension: - -```clarity membership-token.clar -(define-public (is-dao-or-extension) - (ok (asserts! (or (is-eq tx-sender .core) (contract-call? .core is-extension contract-caller)) ERR_UNAUTHORIZED)) -) -``` - -This function will allow you to distribute (or burn) tokens to new members, granting them the ability to vote on future grant proposals. - -## Token minting and burning - -The contract provides functions to `mint` and `burn` tokens: - -```clarity membership-token.clar -(define-public (mint (amount uint) (recipient principal)) - (begin - (try! (is-dao-or-extension)) - (ft-mint? sGrant amount recipient) - ) -) - -(define-public (burn (amount uint) (owner principal)) - (begin - (try! (is-dao-or-extension)) - (ft-burn? sGrant amount owner) - ) -) -``` - -These functions check if the caller is authorized and then mint or burn the specified amount of sGrant tokens. And as you can see, these functions must be executed either through an approved grant proposal or an enabled `extension` (more on this later). - -## Token information - -The contract provides functions to get the token's name (`get-name`), symbol (`get-symbol`), decimals (`get-decimals`), balance (`get-balance`), total supply (`get-total-supply`), and URI (`get-token-uri`): - -```clarity membership-token.clar -(define-read-only (get-name) - (ok (var-get tokenName)) -) - -(define-read-only (get-symbol) - (ok (var-get tokenSymbol)) -) - -(define-read-only (get-decimals) - (ok (var-get tokenDecimals)) -) - -(define-read-only (get-balance (who principal)) - (ok (ft-get-balance sGrant who)) -) - -(define-read-only (get-total-supply) - (ok (ft-get-supply sGrant)) -) - -(define-read-only (get-token-uri) - (ok (var-get tokenUri)) -) -``` - -These functions return the corresponding information about the `sGrant` token. - -These are the key components of the `sGrant` token contract. Understanding these will help you in managing the distribution and burning of tokens through proposals. - -## Proposal submission contract (extension) - -In this section, you will create your second `extension`, a proposal submission contract. This contract will allow anyone to propose a grant, which will then be voted on by the token holders. - -To create your proposal submission contract, navigate to your project's directory and run the following command: - -```terminal -$ clarinet contract new proposal-submission -``` - -This will create a new contract in the contracts directory called proposal-submission.clar. - -Let's walk through the key components of this contract. - -## Traits and constants - -First, you need to implement the `extension-trait` and use the `proposal-trait`: - -```clarity proposal-submission.clar -(impl-trait .extension-trait.extension-trait) -(use-trait proposal-trait .proposal-trait.proposal-trait) -``` - -Next, define some constants that represent error codes: - -```clarity proposal-submission.clar -(define-constant ERR_UNAUTHORIZED (err u3000)) -(define-constant ERR_UNKNOWN_PARAMETER (err u3001)) -``` - -## Variables - -First, define a map to store the parameters of your contract: - -```clarity proposal-submission.clar -(define-map parameters (string-ascii 34) uint) -``` - -Set the proposal-duration parameter to a default value. This value represents the duration of a proposal in blocks. For example, if a block is mined approximately every 10 minutes, a proposal-duration of 1440 would be approximately 10 days. - -```clarity proposal-submission.clar -(map-set parameters "proposal-duration" u1440) ;; ~10 days based on a ~10 minute block time. -``` - -## Authorization check - -The `is-dao-or-extension` function is a private function that checks if the caller of a function is the core contract itself or an authorized extension: - -```clarity proposal-submission.clar -(define-public (is-dao-or-extension) - (ok (asserts! (or (is-eq tx-sender .core) (contract-call? .core is-extension contract-caller)) ERR_UNAUTHORIZED)) -) -``` - -## Parameters - -The get-parameter function is a read-only function that returns the value of a parameter: - -```clarity proposal-submission.clar -(define-read-only (get-parameter (parameter (string-ascii 34))) - (ok (unwrap! (map-get? parameters parameter) ERR_UNKNOWN_PARAMETER)) -) -``` - -## Proposals - -The propose function allows anyone to propose a grant: - -```clarity proposal-submission.clar -(define-public (propose (proposal ) (title (string-ascii 50)) (description (string-utf8 500))) - (begin - (contract-call? .proposal-voting add-proposal - proposal - { - end-block-height: (+ block-height (try! (get-parameter "proposal-duration"))), - proposer: tx-sender, - title: title, - description: description - } - ) - ) -) -``` - -This function calls the add-proposal function of the proposal-voting contract, passing the proposal contract, the current block height as the start block height, the current block height plus the proposal-duration as the end block height, the sender as the proposer, and the title and description of the proposal. - -## Extension callback - -The callback function allows the core contract to request a callback: - -```clarity proposal-submission.clar -(define-public (callback (sender principal) (memo (buff 34))) - (ok true) -) -``` - -These are the key components of the proposal submission contract. Understanding these will help you in managing the submission of proposals. - -## Proposal voting contract (extension) - -In this section, you will create your third extension, a proposal voting contract. This contract will allow token holders to vote on the proposed grants. - -To create your proposal voting contract, navigate to your project's directory and run the following command: - -```terminal -$ clarinet contract new proposal-voting -``` - -This will create a new contract in the contracts directory called proposal-voting.clar. - -Let's walk through the key components of this contract. - -## Traits and constants - -First, you need to implement the extension-trait and use the proposal-trait: - -```clarity proposal-voting.clar -(impl-trait .extension-trait.extension-trait) -(use-trait proposal-trait .proposal-trait.proposal-trait) -``` - -Next, define some constants that represent error codes: - -```clarity proposal-voting.clar -(define-constant ERR_UNAUTHORIZED (err u3000)) -(define-constant ERR_PROPOSAL_ALREADY_EXECUTED (err u3002)) -(define-constant ERR_PROPOSAL_ALREADY_EXISTS (err u3003)) -(define-constant ERR_UNKNOWN_PROPOSAL (err u3004)) -(define-constant ERR_PROPOSAL_ALREADY_CONCLUDED (err u3005)) -(define-constant ERR_PROPOSAL_INACTIVE (err u3006)) -(define-constant ERR_PROPOSAL_NOT_CONCLUDED (err u3007)) -(define-constant ERR_NO_VOTES_TO_RETURN (err u3008)) -(define-constant ERR_END_BLOCK_HEIGHT_NOT_REACHED (err u3009)) -(define-constant ERR_DISABLED (err u3010)) -``` - -## Variables - -You need to define a map to store the proposals and another map to store the total votes of each member: - -```clarity proposal-voting.clar -(define-map proposals - principal - { - votes-for: uint, - votes-against: uint, - end-block-height: uint, - concluded: bool, - passed: bool, - proposer: principal, - title: (string-ascii 50), - description: (string-utf8 500) - } -) - -(define-map member-total-votes {proposal: principal, voter: principal} uint) -``` - -## Authorization check - -The `is-dao-or-extension` function is a private function that checks if the caller of a function is the core contract itself or an authorized extension: - -```clarity proposal-voting.clar -(define-public (is-dao-or-extension) - (ok (asserts! (or (is-eq tx-sender .core) (contract-call? .core is-extension contract-caller)) ERR_UNAUTHORIZED)) -) -``` - -## Proposals - -The add-proposal function allows the core contract or an authorized extension to add a new proposal: - -```clarity proposal-voting.clar -(define-public (add-proposal (proposal ) (data {end-block-height: uint, proposer: principal, title: (string-ascii 50), description: (string-utf8 500)})) - (begin - (try! (is-dao-or-extension)) - (asserts! (is-none (contract-call? .core executed-at proposal)) ERR_PROPOSAL_ALREADY_EXECUTED) - (print {event: "propose", proposal: proposal, proposer: tx-sender}) - (ok (asserts! (map-insert proposals (contract-of proposal) (merge {votes-for: u0, votes-against: u0, concluded: false, passed: false} data)) ERR_PROPOSAL_ALREADY_EXISTS)) - ) -) -``` - -## Votes - -The vote function allows a token holder to vote on a proposal. It checks if the voter has at least 1 membership-token: - -```clarity proposal-voting.clar -(define-public (vote (amount uint) (for bool) (proposal principal)) - (let - ( - (proposal-data (unwrap! (map-get? proposals proposal) ERR_UNKNOWN_PROPOSAL)) - ) - (asserts! (>= (unwrap-panic (contract-call? .membership-token get-balance tx-sender)) u1) ERR_UNAUTHORIZED) - (map-set member-total-votes {proposal: proposal, voter: tx-sender} - (+ (get-current-total-votes proposal tx-sender) amount) - ) - (map-set proposals proposal - (if for - (merge proposal-data {votes-for: (+ (get votes-for proposal-data) amount)}) - (merge proposal-data {votes-against: (+ (get votes-against proposal-data) amount)}) - ) - ) - (ok (print {event: "vote", proposal: proposal, voter: tx-sender, for: for, amount: amount})) - ) -) - -(define-read-only (get-current-total-votes (proposal principal) (voter principal)) - (default-to u0 (map-get? member-total-votes {proposal: proposal, voter: voter})) -) -``` - -## Conclusion - -The `conclude` function allows the core contract or an authorized extension to conclude a proposal: - -```clarity proposal-voting.clar -(define-public (conclude (proposal )) - (let - ( - (proposal-data (unwrap! (map-get? proposals (contract-of proposal)) ERR_UNKNOWN_PROPOSAL)) - (passed (> (get votes-for proposal-data) (get votes-against proposal-data))) - ) - (asserts! (not (get concluded proposal-data)) ERR_PROPOSAL_ALREADY_CONCLUDED) - (asserts! (>= block-height (get end-block-height proposal-data)) ERR_END_BLOCK_HEIGHT_NOT_REACHED) - (map-set proposals (contract-of proposal) (merge proposal-data {concluded: true, passed: passed})) - (print {event: "conclude", proposal: proposal, passed: passed}) - (and passed (try! (contract-call? .core execute proposal tx-sender))) - (ok passed) - ) -) -``` - -This function concludes a proposal. It first retrieves the proposal data and checks if the proposal has more votes for than against. It then asserts that the proposal has not already been concluded and that the current block height is greater than or equal to the end block height of the proposal. If these conditions are met, it sets the concluded and passed fields of the proposal data and prints an event. If the proposal passed, it also tries to execute the proposal. The function returns whether the proposal passed. - -## Extension callback - -The callback function allows the core contract to request a callback: - -```clarity proposal-voting.clar -(define-public (callback (sender principal) (memo (buff 34))) - (ok true) -) -``` - -Congratulations! You've successfully created the foundations for a decentralized grants program! - -## Challenges - -The following challenges are additional features you can implement to continue building and sharpening your skills. - - - -**Initialize your grants program**: Now that you have your core extension contracts, you can initialize the project. The way you do this is through the `construct` function you wrote inside your `core.clar` contract. Create your first proposal enabling your extensions (`membership-token`, `proposal-submission`, `proposal-voting`) and distribute the initial token allocation to addresses responsible for voting on grants. If you need a little more guidance, check out the example [here](https://github.com/MarvinJanssen/executor-dao/blob/main/contracts/proposals/edp000-bootstrap.clar). - - - -**Create grant proposals**: After initializing your grants program, the next step is to create grant proposals. This involves using the `propose` function in the `proposal-submission` contract. This function allows anyone to propose a grant, which will then be voted on by the token holders. The proposal includes details such as the title, description, and the proposal contract. Once a proposal is submitted, it can be voted on during the voting period defined by the `proposal-duration` parameter. - - - -**Implement milestone-based funding**: To implement milestone-based funding, you'll need to create a new extension contract that tracks the progress of each grant proposal. This extension will manage the milestones for each grant, allowing funds to be released as each milestone is achieved. To enable this extension, you'll need to create a proposal using the propose function in the `proposal-submission` contract. Once enabled, the milestone-based funding extension will provide a more structured and accountable way to distribute funds, ensuring that the grant recipients are making progress before they receive their next round of funding. - - - -**UI integration**: Using the provided starter template, integrate your contracts using Stacks.js. This will allow users to submit proposals, vote on them, and view the status of their proposals directly from the UI. - -```tsx -import { callReadOnlyFunction, standardPrincipalCV } from "@stacks/transactions" - -const senderAddress = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM" -const contractAddress = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM" -const contractName = "core" -const functionName = "is-extension" -const extensionAddress = - "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.membership-token" - -const functionArgs = [standardPrincipalCV(extensionAddress)] - -await callReadOnlyFunction({ - network, - contractAddress, - contractName, - functionName, - functionArgs, - senderAddress -}) -``` diff --git a/content/docs/stacks/hacks/archive/build-a-friend-tech-clone.mdx b/content/docs/stacks/hacks/archive/build-a-friend-tech-clone.mdx deleted file mode 100644 index 9c46d8b54..000000000 --- a/content/docs/stacks/hacks/archive/build-a-friend-tech-clone.mdx +++ /dev/null @@ -1,307 +0,0 @@ ---- -title: Build a Friend.tech clone -description: Learn how to build a decentralized social network. ---- - -import { HackBadge } from "@/components/badge"; - - -This hack has been archived. Feel free to continue to use the code in this guide as a reference for your own projects. - - -## Introduction - -What if we could gamify—and reward—being a friend? That's the idea behind Friend.tech, the decentralized social network that took Web3 by storm. In this hack, you'll recreate Friend.tech on the Stacks blockchain. - -There are a few key components to this hack: namely, **subjects** that have **keys** that anyone can buy. These keys start off low in price, but as people buy more keys, the price goes up faster and faster, rewarding friends who bought keys early. Key owners can sell their keys for a profit, or they can hold on to them to signal their friendship and build reputation. These keys can also be used to access exclusive chatrooms with their corresponding subject, receive exclusive airdrops, and more - -This Hack walks you through the basics of building a Friend.tech clone. There are also challenges at the end, which are opportunities to stretch your skills and keep learning. - -## Clone the starter template - -Start by setting up your development environment. We've prepared a repository that includes an initialized Clarinet project and a React frontend with some boilerplate code and all the required packages. - -To clone the repository, open your terminal and run the following command: - -```terminal -$ git clone https://github.com/hirosystems/hiro-hacks-template.git -$ cd hiro-hacks-template -``` - -## Create your contract - -Before you begin, we're assuming that you have `clarinet` installed and a basic understanding of how to use it. If you haven't installed `clarinet` yet, you can do so by referring to our [installation guide](/stacks/clarinet/installation). - -To create your contract, navigate to your project's directory and run the following command: - -```terminal -$ clarinet contract new keys -``` - -This will create a new contract in the `contracts` directory called `keys.clar`. - - - If you don't want to clone the provided starter template, you can create your - `Clarinet` project manually by running `clarinet new friendtech && cd - friendtech`. - - -## Defining `key` balances and supply - -Inside your `keys.clar` contract, you need to keep track of the balance of `keys` for each user (or _holder_) and the total supply of `keys` for each subject. You can do this using Clarity's `define-map` function: - -```clarity keys.clar -(define-map keysBalance { subject: principal, holder: principal } uint) -(define-map keysSupply { subject: principal } uint) -``` - -The `keysBalance` stores each holder's `key` balance for a given subject and the `keysSupply` stores the total supply for each subject. These maps will be used in your contract's functions to manage the creation, buying, and selling of `keys`. - -## Calculating `key` prices - -The next thing you need to do is define a function that calculates the price of `keys` for a given a `supply` and `amount`. You can do this by defining a `get-price` function: - -```clarity keys.clar -(define-read-only (get-price (supply uint) (amount uint)) - (let ( - (base-price u10) ;; Base price per key in micro-STX - (price-change-factor u100) ;; Factor to control the rate of price change - ) - ;; Average price per token over the range of supply - (/ - (+ - (* base-price amount) - (* amount (/ (+ (* supply supply) (* supply amount) (* amount amount)) (* u3 price-change-factor))) - ) - amount - ) -)) -``` - -The `get-price` function calculates the price of `keys` using a formula that calculates the average price per token over the range of supply affected. This can be done by integrating the price function over the range of supply and dividing by the amount. - -## Creating, buying, and selling `keys` - -These functions form the core of the contract's operations, enabling users to manage keys through buying and selling. - -Let's first take a look at the `buy-keys` function: - -```clarity keys.clar -(define-public (buy-keys (subject principal) (amount uint)) - (let - ( - (supply (default-to u0 (map-get? keysSupply { subject: subject }))) - (price (get-price supply amount)) - ) - (if (or (> supply u0) (is-eq tx-sender subject)) - (begin - (match (stx-transfer? price tx-sender (as-contract tx-sender)) - success - (begin - (map-set keysBalance { subject: subject, holder: tx-sender } - (+ (default-to u0 (map-get? keysBalance { subject: subject, holder: tx-sender })) amount) - ) - (map-set keysSupply { subject: subject } (+ supply amount)) - (ok true) - ) - error - (err u2) - ) - ) - (err u1) - ) - ) -) -``` - -This function allows subjects to create their first `keys`, initiating their supply in the contract. The transaction only succeeds if the _subject_ is creating the initial `keys` or if there are already `keys` in circulation, ie `principal-a` cannot buy the initial `keys` for `principal-b`. - -Next up, the `sell-keys` function: - -```clarity keys.clar -(define-public (sell-keys (subject principal) (amount uint)) - (let - ( - (balance (default-to u0 (map-get? keysBalance { subject: subject, holder: tx-sender }))) - (supply (default-to u0 (map-get? keysSupply { subject: subject }))) - (price (get-price (- supply amount) amount)) - (recipient tx-sender) - ) - (if (and (>= balance amount) (or (> supply u0) (is-eq tx-sender subject))) - (begin - (match (as-contract (stx-transfer? price tx-sender recipient)) - success - (begin - (map-set keysBalance { subject: subject, holder: tx-sender } (- balance amount)) - (map-set keysSupply { subject: subject } (- supply amount)) - (ok true) - ) - error - (err u2) - ) - ) - (err u1) - ) - ) -) -``` - -This is more or less the same logic as the `buy-keys` function, but instead you deduct the `keysBalance` and `keysSupply` and check if the seller owns enough keys and if they are authorized to sell. - -## Verifying keyholders - -Now that you have the ability to buy and sell `keys`, you need a way to verify if a user is a keyholder. You can do this by defining an `is-keyholder` read-only function: - -```clarity keys.clar -(define-read-only (is-keyholder (subject principal) (holder principal)) - (>= (default-to u0 (map-get? keysBalance { subject: subject, holder: holder })) u1) -) -``` - -This function checks if the `keysBalance` for a given `subject` and `holder` is greater than or equal to 1. If it is, then the user `is-keyholder`. - -## Testing locally - -Make sure your contract is valid and doesn't have any errors. To do this, run the following command: - -```terminal -$ clarinet check -``` - -Next, check some of your contract functionality inside `clarinet console`: - -```clarity keys.clar -;; Get the price of 100 keys when the supply is 0 -(contract-call? .keys get-price u0 u100) ;; u10010 - -;; Initial purchase of keys -(contract-call? .keys buy-keys tx-sender u100) - -;; Check if the sender is a keyholder -(contract-call? .keys is-keyholder tx-sender tx-sender) ;; true - -(contract-call? .keys is-keyholder tx-sender 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5) ;; false -``` - -Congratulations! You've successfully created your contract. You've laid the groundwork for a decentralized social network, just like Friend.tech. - -## Challenges - -The following challenges are additional features you can implement to keep learning and building on Stacks. - - - -**Balance and supply query functions**: Add two new read-only functions: `get-keys-balance` and `get-keys-supply`. These functions will provide valuable information to users about the distribution and availability of `keys`, and can be used in various parts of your application to display this information to users. - -```clarity keys.clar -(define-read-only (get-keys-balance (subject principal) (holder principal)) - ;; Return the keysBalance for the given subject and holder -) - -(define-read-only (get-keys-supply (subject principal)) - ;; Return the keysSupply for the given subject -) -``` - - - -**Price query functions**: Add two new read-only functions: `get-buy-price` and `get-sell-price`. These helper functions will allow users to query the current price for buying or selling a specific amount of `keys` for a given `subject`. - -```clarity keys.clar -(define-read-only (get-buy-price (subject principal) (amount uint)) - ;; Implement buy price logic -) - -(define-read-only (get-sell-price (subject principal) (amount uint)) - ;; Implement sell price logic -) -``` - - - -**Fee management**: When a user buys or sells `keys`, you might want to introduce a fee, either at the protocol or subject level that can be distributed accordingly. Add a `protocolFeePercent` and/or `subjectFeePercent` variable, as well as a destination Stacks principal `protocolFeeDestination` for this new revenue. Now make sure to update the `buy-keys` and `sell-keys` functions to incorporate these fees and `stx-transfer?` into the buying and selling logic. - -```clarity keys.clar -;; Change the fee values as you wish -(define-data-var protocolFeePercent uint u200) ;; or subjectFeePercent -(define-data-var protocolFeeDestination principal tx-sender) -``` - - - -**Access control**: In a real-world application, you might need to adjust the `protocolFeePercent`, `subjectFeePercent`, or `protocolFeeDestination` values over time. However, you wouldn't want just anyone to be able to make these changes. This is where access control comes in. Specifically, you should add a set-fee function (or functions) that allows only a designated `contractOwner` to change the `protocolFeePercent`, `subjectFeePercent`, or `protocolFeeDestination` values. - -```clarity keys.clar -(define-public (set-protocol-fee-percent (feePercent uint)) - ;; Check if the caller is the contractOwner - ;; Update the protocolFeePercent value -) -``` - -Think about how you can verify whether the caller of the function is indeed the `contractOwner`. Also, consider what kind of feedback the function should give when someone else tries to call it. Test your implementation to ensure it works as expected. - - - -**UI integration**: Using the provided [starter template](#clone-the-starter-template), integrate your contract using [Stacks.js](/stacks/stacks.js). For example, if you were calling the `is-keyholder` function, your code might look something like this: - -```tsx -import { callReadOnlyFunction, standardPrincipalCV } from "@stacks/transactions" - -const senderAddress = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM" -const contractAddress = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM" -const contractName = "keys" -const functionName = "is-keyholder" - -const functionArgs = [standardPrincipalCV(senderAddress)] - -await callReadOnlyFunction({ - network, - contractAddress, - contractName, - functionName, - functionArgs, - senderAddress -}) -``` - -By using a similar pattern to the code above, you will be able to **show/hide chatrooms based on keyholdings**, **create an exchange for buying/selling keys**, or **add a search for displaying subject keyholdings**. - -> _**Note**_ -> -> If you are planning to experiment with your contract on `devnet`, make sure to run `clarinet devnet start` [to deploy and test your contract locally](/stacks/clarinet/guides/run-a-local-devnet). You can then use the `devnet` network when calling your contract in the [Leather wallet](https://leather.io/install-extension). - - - -**Message signature**: To further enhance the security and authenticity of your app, try to implemement a _login_ feature using [message signing](/stacks/connect/guides/sign-messages). - -```tsx -import { openSignatureRequestPopup } from "@stacks/connect" -import { verifyMessageSignatureRsv } from "@stacks/encryption" -import { StacksMocknet } from "@stacks/network" -import { getAddressFromPublicKey } from "@stacks/transactions" - -const message = "Log in to chatroom" -const network = new StacksMocknet() - -openSignatureRequestPopup({ - message, - network, - onFinish: async ({ publicKey, signature }) => { - const verified = verifyMessageSignatureRsv({ - message, - publicKey, - signature - }) - if (verified) { - // The signature is verified, so now we can check if the user is a keyholder - const address = getAddressFromPublicKey(publicKey, network.version) - const isKeyHolder = await checkIsKeyHolder(address) - if (isKeyHolder) { - // The user is a keyholder, so they are authorized to access the chatroom - } - } - } -}) -``` - -The signed message will serve as a _proof of identity_ - similar to a login, verifying that the user is indeed who they claim to be. This can be particularly useful in a chatroom setting, where only `is-keyholder` users are allowed to send messages. diff --git a/content/docs/stacks/hacks/archive/recipes.mdx b/content/docs/stacks/hacks/archive/recipes.mdx deleted file mode 100644 index 9d634211b..000000000 --- a/content/docs/stacks/hacks/archive/recipes.mdx +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Create a recipe for the Hiro Cookbook -description: Create your own recipe for the Hiro Cookbook and share it with the community. ---- - -## February: Create your own recipe for the Hiro Cookbook - -*Create your own recipe that you think will help other developers build on Stacks* - -**Timeline**: February 19-25, 2025 - -This month's challenge invites you to create your own recipe for the [Hiro Cookbook](/cookbook) and share it with the community. Each recipe is a reusable code snippet that handles some specific function, and each recipe has written annotations, so readers know exactly how the code in a given recipe works and what parameters you can customize. Your submission should be a recipe that you think will help other developers build on Stacks. - -Submit your project [here](https://hirohacks25.paperform.co/). - - - -## Some example recipe ideas to explore - -- Using the `Cl` parse helper function to convert string values into Clarity Values -- Creating and signing a message for smart contract verification -- How to construct a non-sequential multisig transaction -- Create a helper function to determine if a transaction has been signed - -_For this month's submission, provide a link to your recipe in a PR to the [Recipes](https://github.com/hirosystems/recipes) repo. To review the general submission guidelines, see the [Hiro Hacks](/stacks/hacks) page._ - ---- - -## Resources - -- [Hiro Cookbook](/cookbook) -- [Recipes repo](https://github.com/hirosystems/recipes) -- [Submission form](https://hirohacks25.paperform.co/) -- [Stacks Discord](https://stacks.chat) diff --git a/content/docs/stacks/hacks/build-with-sbtc.mdx b/content/docs/stacks/hacks/build-with-sbtc.mdx deleted file mode 100644 index 2d81be2f8..000000000 --- a/content/docs/stacks/hacks/build-with-sbtc.mdx +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: Interact with sBTC -description: Build an app or feature that integrates with sBTC. Compete for your scholarship. ---- - -**Timeline**: March 26 - April 1, 2025 - -This month's challenge is to build with [sBTC](https://www.stacks.co/sbtc), the new programmable Bitcoin-backed asset on Stacks. Since its launch in December, sBTC has brought $260M+ of BTC liquidity directly to Stacks. With sBTC withdrawals going live on March 31st, there's never been a better time to start building with sBTC, and this is your perfect opportunity to get started. - -We will be awarding 2 developer scholarships to 2 different winners this month. Each scholarship will receive **hotel accommodations**, a **$1,000 travel stipend**, and tickets to **Bitcoin 2025** in Las Vegas. - -Submit your project [here](https://hirohacks25.paperform.co/). - -Your submission can be a full-fledged application, or a new feature in your existing project. The only requirements are that it has to interact with sBTC in some way and that you build something new during the window of this hack. - -## Some hack ideas to get you started - -- A cli command for transferring sBTC -- An analytics dashboard for sBTC activity -- Any kind of smart contract functionality that interacts with sBTC ---- - -## Resources - -- [Working with sBTC in Clarinet](/stacks/clarinet/guides/working-with-sbtc) -- [sBTC package](/stacks/stacks.js/packages/sbtc) -- [Submission form](https://hirohacks25.paperform.co/) -- [Stacks Discord](https://stacks.chat) diff --git a/content/docs/stacks/hacks/index.mdx b/content/docs/stacks/hacks/index.mdx deleted file mode 100644 index 0c1cb49a1..000000000 --- a/content/docs/stacks/hacks/index.mdx +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Overview -description: A series of coding challenges to sharpen your skills. ---- - -import { Code } from 'lucide-react'; -import { SecondaryCard } from '@/components/card'; - -Hiro Hacks are monthly hackathons designed to bring together the most innovative builders in the Stacks ecosystem. Each month features a unique theme, challenging you to stretch your creativity, show off your skills, and learn from other devs in the process. - -Have fun. Build something new. Compete against other devs for a scholarship to Bitcoin 2025 in Las Vegas this May (scroll down for details). - -To submit your projects each month, [complete this form](https://hirohacks25.paperform.co/) before midnight ET on the last day of that month's hack. - -## Schedule - -| Week | Theme | Description | -| --- | --- | --- | -| Jan 22-28 | [AI x Stacks](/stacks/hacks/archive/ai) | Build something that combines AI capabilities with Stacks. | -| Feb 19-25 | [Create your own recipe](/stacks/hacks/recipes) | Create your own recipe for the Hiro Cookbook and share it with the community. | -| Mar 26 - Apr 1 | [Build with sBTC](/stacks/hacks/build-with-sbtc) | Build an app or feature that interacts with sBTC. | -| Apr 23-29 | TBA | Coming soon | -| May 21-27 | TBA | Coming soon | -| Jun 18-24 | TBA | Coming soon | -| ??? | ??? | ??? | - -## Prizes - -For March's hack, we will be awarding 2 developer scholarships to 2 different winners. Each developer scholarship includes **hotel accommodations**, a **$1,000 travel stipend**, and **tickets to [Bitcoin 2025](https://b.tc/conference/2025)** in Las Vegas this May. - -Code your way to Vegas and spend time with Stacks builders while diving into the zany world of the biggest Bitcoin conference of the year. - -## Resources - -Need help hacking on your project? [Join the Stacks Discord](https://stacks.chat) and get help from other devs in the #builder-general channel. If you're having problems using Hiro tools, you can also reach out to our team in the relevant tool channel in the Hiro Developer Tools section. - -And don't forget to take advantage of all of the resources in our docs as well as [Stacks docs](https://docs.stacks.co/). - -## Rules - -To be eligible for swag and the hacker house, you must submit your project through [this paperform](https://hirohacks25.paperform.co/) before midnight ET on the last day of that month's hack. - -In that submission, we expect to see: - -- A link to your project (if applicable) -- A link to your code with a clear README (or link to a PR if submitting a recipe) -- A description that covers the problem being solved, the technical approach, and future improvements for the project - -In terms of selecting winners, submissions will be evaluated on their technical implementation, their innovation/creativity, and their documentation/presentation. To learn more about the rules, read [Hiro Hacks Terms & Conditions](https://www.hiro.so/hiro-hacks-rules). diff --git a/content/docs/stacks/hacks/meta.json b/content/docs/stacks/hacks/meta.json deleted file mode 100644 index e42d126f1..000000000 --- a/content/docs/stacks/hacks/meta.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "title": "Hiro Hacks", - "root": true, - "pages": [ - "---Hiro Hacks---", - "index", - "---Hacks---", - "build-with-sbtc", - "---Archive---", - "archive/recipes", - "archive/ai", - "archive/build-a-friend-tech-clone", - "archive/build-a-decentralized-grants-program", - "archive/build-a-custom-api" - ] -} diff --git a/content/docs/stacks/index.mdx b/content/docs/stacks/index.mdx deleted file mode 100644 index e70cf7344..000000000 --- a/content/docs/stacks/index.mdx +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Home -icon: StacksIcon -toc: false ---- - -import { Card as MainCard, SmallCard } from '@/components/card'; -import { ImageZoom } from 'fumadocs-ui/components/image-zoom'; -import { PageFooter } from '@/components/footer'; -import { MessageCircle, Braces, ChevronRight, Code, Database, Play, Rocket, Star, Terminal, Wallet } from 'lucide-react'; -import { API, Backend, BugIcon, Clarinet, Cloud, Chainhook, Frontend, Hiro, Js, Newspaper, Pulse, QuestionIcon } from '@/components/ui/icon'; -import heroImage from '@/public/stacks-hero.svg'; - -
- -
- - -
- - ## Build with Stacks - - Find all the guides and resources you need to build on Stacks. - -
-
- - - } - href="/stacks/get-started" - title="Get Started" - description="Get started with our end-to-end tutorials and quickstart guides across all Hiro tools." - /> - } - href="/stacks/api" - title="Stacks API Reference" - description="Explore API endpoints for interacting with the Stacks Blockchain." - /> - - -
- -

- Explore by category -

- ---- - - - } - href="/stacks/platform" - title="Quickstart App Templates" - description="Full-stack starter-kits, including front-end, back-end, and smart contract components." - /> - } - href="/stacks/clarinet" - title="Smart Contract Development" - description="Kickstart your smart contract journey with Clarinet and the Clarinet JS SDK." - /> - } - href="/stacks/chainhook" - title="Data Streaming & Events" - description="Create custom event streams for real-time data with Chainhook." - /> - } - href="/stacks/stacks.js" - title="Frontend Web Development" - description="Interact with smart contracts on the web with the Stacks.js library." - /> - } - href="/stacks/api" - title="Backend Development" - description="Explore our hosted APIs offering a familiar REST interface." - /> - } - href="/stacks/token-metadata-api" - title="Token Management" - description="Explore our hosted API for fetching token metadata on Stacks." - /> - - -
- - -
- -

- Explore by tool -

- ---- - - - } - href="/stacks/platform" - title="Hiro Platform" - description="A developer platform for building, deploying and scaling Bitcoin apps." - /> - } - href="/stacks/clarinet" - title="Clarinet" - description="Create, test, and deploy smart contracts on the Stacks blockchain." - /> - } - href="/stacks/api" - title="Stacks Blockchain API" - description="Interact with the Stacks blockchain from your backend via our hosted API." - /> - } - href="/stacks/stacks.js" - title="Stacks.js" - description="A collection of JavaScript libraries to build web applications on Stacks." - /> - } - href="/stacks/chainhook" - title="Chainhook" - description="Create customizable, lightweight databases for on-chain events for Bitcoin and Stacks." - /> - - -
- -
- - \ No newline at end of file diff --git a/content/docs/stacks/meta.json b/content/docs/stacks/meta.json deleted file mode 100644 index 69801d3da..000000000 --- a/content/docs/stacks/meta.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "title": "stacks", - "root": true, - "pages": [ - "index", - "get-started", - "---Tools---", - "clarinet", - "clarinet-js-sdk", - "stacks.js", - "connect", - "chainhook", - "platform", - "---APIs---", - "api", - "token-metadata-api", - "platform-api", - "rpc-api", - "signer-metrics-api", - "api-keys", - "rate-limiting", - "------", - "clarity", - "nakamoto", - "archive", - "hacks", - "contributors-guide" - ] -} diff --git a/content/docs/stacks/nakamoto/guides/clarinet.mdx b/content/docs/stacks/nakamoto/guides/clarinet.mdx deleted file mode 100644 index f0949dde9..000000000 --- a/content/docs/stacks/nakamoto/guides/clarinet.mdx +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: Updates for Clarinet -description: Discover Clarinet upgrades related to the Nakamoto release. ---- - -## Setting up a project for Nakamoto - -As of [version 2.11.0](https://github.com/hirosystems/clarinet/releases/tag/v2.11.0), Clarinet runs -in epoch 3.0 (Nakamoto) by default. - -- Contracts are set to be deployed in epoch 3.0 and support Clarity 3. -- The Devnet runs the latest Stacks blockchain version by default, enabling Nakamoto and support - Clarity 3 contracts. - -Once the Devnet reaches the right block height, (Bitcoin block #108 by default), it will deploy the -_`pox-4.clar`_ contract and run in Epoch 2.5. From there, Clarinet will send _`stack-stx`_ and -_`stack-extend`_ requests to the new PoX contract. Eventually, you can observe the -_`vote-for-aggregate-public-key`_ transactions that they send. - -**At Bitcoin block #142, the Devnet will switch the epoch 3.0.** - -At the end of the _`Devnet.toml`_ file, you must make sure that the _`pox_stacking_orders`_ are properly -set. You should have 3 stacking orders from 3 different accounts. All should start at **cycle 1** -and take at least **2 slots**. You also need to enable the _`auto-extend`_ property. Because Nakamoto -relies on the Stackers to sign blocks, these settings ensure that there are engouh stacked STX for -each cycles. Here is what it looks like by default in new projects: - -```toml -# settings/Devnet.toml -[[devnet.pox_stacking_orders]] -start_at_cycle = 1 -duration = 10 -auto_extend = true -wallet = "wallet_1" -slots = 2 -btc_address = "mr1iPkD9N3RJZZxXRk7xF9d36gffa6exNC" - -[[devnet.pox_stacking_orders]] -start_at_cycle = 1 -duration = 10 -auto_extend = true -wallet = "wallet_2" -slots = 2 -btc_address = "muYdXKmX9bByAueDe6KFfHd5Ff1gdN9ErG" - -[[devnet.pox_stacking_orders]] -start_at_cycle = 1 -duration = 10 -auto_extend = true -wallet = "wallet_3" -slots = 2 -btc_address = "mvZtbibDAAA3WLpY7zXXFqRa3T4XSknBX7" -``` - -Set a contract to be deployed in epoch 3.0 with Clarity 3. You can create a new one with -`$ clarinet contract new `). It needs to be manually update in the project manifest -(Clarinet.toml) - -```toml -# Clarinet.toml -[contracts.nakademo] -path = 'contracts/nakademo.clar' -clarity_version = 3 -epoch = 3.0 -``` - -Start Devnet with `clarinet devnet start`, you should see epoch 3.0 and fast blocks at Bitcoin -block 142. - - -Clarity 3 introduces two new keywords after the Nakamoto hard fork: - -- `tenure-height`: Returns the number of tenures passed. -- `stacks-block-height`: Returns the current Stacks block height. - -Note: `block-height` is removed. - -For more details on these and other Clarity keywords, see the [Clarity Keywords Reference](https://docs.stacks.co/reference/keywords). - \ No newline at end of file diff --git a/content/docs/stacks/nakamoto/guides/explorer.mdx b/content/docs/stacks/nakamoto/guides/explorer.mdx deleted file mode 100644 index c8fca1ffa..000000000 --- a/content/docs/stacks/nakamoto/guides/explorer.mdx +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Updates for Stacks Explorer -description: Discover Stacks Explorer updates related to the Nakamoto upgrade. ---- - -## What's new - -### Introducing a fresh view for blocks - -The Stacks Explorer now features a new way to display blocks, aligning with the Nakamoto upgrade's approach of multiple STX blocks settling into one BTC block. - -![Block View](../images/nakamoto-explorer.png) - -### Tailored viewing experience - -This new view is now live on both [testnet](https://explorer.hiro.so/?chain=testnet) and [mainnet](https://explorer.hiro.so/?chain=mainnet), accessible via the network dropdown. - -#### Two distinctive display modes - -1. **Independent Display:** Focuses on STX blocks progress. -2. **COMING SOON—Grouped by Bitcoin Block:** Shows BTC blocks flow alongside STX blocks. - -![Block View](../images/group-by-block.png) - -### Stay in the loop with live view - -Keep up-to-date with blocks in real-time with our new live view option. diff --git a/content/docs/stacks/nakamoto/guides/stacks-api.mdx b/content/docs/stacks/nakamoto/guides/stacks-api.mdx deleted file mode 100644 index 54f9982fa..000000000 --- a/content/docs/stacks/nakamoto/guides/stacks-api.mdx +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Updates for Stacks API -description: Discover Stacks Blockchain API updates related to the Nakamoto upgrade. ---- - -## What's new - - - The `/extended/v2/*` endpoints represent the modern API that is being - continually expanded to support the Nakamoto upgrade. We encourage developers - to use v2 endpoints for new developments. Be aware that `/extended/v1/*` are - the older set of endpoints. Though they continue to function alongside v2, they will be deprecated in the coming months. - - -### Nakamoto endpoints - -The Stacks Blockchain API has a series of new endpoints to support the upcoming Nakamoto upgrade: - -- Get Proof-of-Transfer details per Cycle, including Signers and Stackers, with information about stacked STX amounts, payout addresses and signer weights -- Get a list of Stacks blocks per Bitcoin block to support the new Nakamoto mining mechanism -- Get all transactions relevant to a STX address or contract ID, including filters for FT and NFT transfers -- Support for the new Nakamoto `tenure_change` transaction type across all our transaction endpoints -- Get a summary of current network mempool transaction fees, including statistics for expected confirmation priorities -- Get the deployment status of multiple smart contracts in one call - -All of these endpoints are backwards compatible with Stacks nodes running version 2.4 or earlier - -### Event replay optimizations - -- Optimize replay speed by creating a new parquet-based ingestion that optimizes for canonical chain information -- Optimize classic TSV event replay by improving block ingestion times - -### New transaction type `tenure_change` - -This new type affects the following endpoints: - -- `/extended/v1/address/{principal}/transactions` -- `/extended/v1/tx` -- `/extended/v1/tx/{tx_id}` -- `/extended/v1/tx/{tx_id}/raw` -- `/extended/v1/tx/mempool` -- `/extended/v1/tx/multiple` - -### New endpoints: `/extended/v2/*` - -One important difference to note between the `/extended/v1` vs the `/extended/v2` endpoints is that the /extended/v2/_ endpoints represent the current API that is being continually expanded to support the Nakamoto upgrade. We encourage developers to use v2 endpoints for new developments. Be aware that /extended/v1/_ are the older set of endpoints. Though they continue to function alongside v2, they will be deprecated in the coming months. - -- `/extended/v2/mempool/fees` -- `/extended/v2/burn-blocks` -- `/extended/v2/burn-blocks/{height_or_hash}` -- `/extended/v2/burn-blocks/{height_or_hash}/blocks` -- `/extended/v2/blocks` -- `/extended/v2/blocks/{height_or_hash}` -- `/extended/v2/blocks/{height_or_hash}/transactions` -- `/extended/v2/addresses/{address}/transactions:` -- `/extended/v2/addresses/{address}/transactions/{tx_id}/events:` -- `/extended/v2/smart-contracts/status` -- `/extended/v2/pox/cycles` -- `/extended/v2/pox/cycles/{cycle_number}` -- `/extended/v2/pox/cycles/{cycle_number}/signers` -- `/extended/v2/pox/cycles/{cycle_number}/signers/{signer_key}` -- `/extended/v2/pox/cycles/{cycle_number}/signers/{signer_key}/stackers` - -### Deprecated endpoints - -- `/extended/v1/block` -- `/extended/v1/block/{hash}` -- `/extended/v1/block/by_height/{height}` -- `/extended/v1/block/by_burn_block_hash/{burn_block_hash}` -- `/extended/v1/block/by_burn_block_height/{burn_block_height}` -- `/extended/v1/address/{principal}/transactions` -- `/extended/v1/address/{principal}/{tx_id}/with_transfers` -- `/extended/v1/address/{principal}/transactions_with_transfers` -- `/extended/v1/fee_rate` -- `/extended/v1/tx/block/{block_hash}` -- `/extended/v1/tx/block_height/{height}` - -View the [API reference](/stacks/api/info). diff --git a/content/docs/stacks/nakamoto/guides/stacks-js.mdx b/content/docs/stacks/nakamoto/guides/stacks-js.mdx deleted file mode 100644 index 3e104d7f3..000000000 --- a/content/docs/stacks/nakamoto/guides/stacks-js.mdx +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Updates for Stacks.js -description: Discover Stacks.js changes related to the Nakamoto upgrade. ---- - -## What's new - -### StackingClient - -Install the latest nakamoto version with `npm install @stacks/stacking@latest`. - -The StackingClient in `@stacks/stacking` was updated to match the latest `pox-4` contract. - -- Added `StackingClient.signPoxSignature()` -- Added `Pox4SignatureTopic` enum -- New stacking arguments for `StackingClient.stack`, `StackingClient.stackExtend`, `StackingClient.stackIncrease`, `StackingClient.stackAggregationCommit`, `StackingClient.stackAggregationCommitIndexed`, and `StackingClient.stackAggregationIncrease` - -### Nakamoto network - -To test using the Nakamoto testnet, you can use the `StacksTestnet` network with a custom URL. The Nakamoto testnet is being hosted at https://api.testnet.hiro.so. Use this URL like this: - -```tsx -import { StacksTestnet } from "@stacks/network" - -const network = new StacksTestnet({ - url: "https://api.testnet.hiro.so" -}) -``` - -#### Example snippets - -**`StackingClient.signPoxSignature`** - -```ts -const client = StackingClient(MY_ADDRESS, new StacksTestnet()) -``` - -```ts -const signature = client.signPoxSignature({ - topic: "stack-stx", - rewardCycle: await client.getPoxInfo().reward_cycle_id, - poxAddress: MY_BTC_ADDRESS, - period: 2, - maxAmount: 10_000_000_000_000, - authId: 123n, - - signerPrivateKey: MY_SIGNER_PRIVATE_KEY -}) -``` - -**New arguments for e.g. `StackingClient.stack`** - -```ts -const { txid } = await client.stack({ - amountMicroStx: 10_000_000_000_000, // this can be at most the signature `maxAmount` - poxAddress: MY_BTC_ADDRESS, - cycles: 2, // this needs to match signature `period` - burnBlockHeight: CURRENT_BURN_BLOCK_HEIGHT, - - // NEW ARGS - signerKey: MY_SIGNER_PUBLIC_KEY, - signerSignature: signature, - maxAmount: 10_000_000_000_000, - authId: 123n, - - privateKey: MY_STX_PRIVATE_KEY -}) -``` diff --git a/content/docs/stacks/nakamoto/images/group-by-block.png b/content/docs/stacks/nakamoto/images/group-by-block.png deleted file mode 100644 index 3dd875857..000000000 Binary files a/content/docs/stacks/nakamoto/images/group-by-block.png and /dev/null differ diff --git a/content/docs/stacks/nakamoto/images/nakamoto-explorer.png b/content/docs/stacks/nakamoto/images/nakamoto-explorer.png deleted file mode 100644 index 5300e568a..000000000 Binary files a/content/docs/stacks/nakamoto/images/nakamoto-explorer.png and /dev/null differ diff --git a/content/docs/stacks/nakamoto/index.mdx b/content/docs/stacks/nakamoto/index.mdx deleted file mode 100644 index bea5cba74..000000000 --- a/content/docs/stacks/nakamoto/index.mdx +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Overview -description: Discover updates to Hiro tools related to the Nakamoto upgrade. ---- - -Nakamoto is an upcoming upgrade to Stacks that brings faster blocks and paves the way for sBTC. [Start here](https://docs.stacks.co/nakamoto-upgrade/nakamoto-upgrade-start-here) if you need an overview of how Nakamoto impacts the network. This document is about how Nakamoto impacts your applications and Hiro tooling specifically. - -The good news for you is that the Nakamoto upgrade does not bring breaking changes to applications on Stacks. Your app will continue to work as expected post-upgrade, apart from you and your users experiencing the better UX of faster block times. - -In terms of what you need to do to prepare for Nakamoto, just make sure you are running the latest versions of our tooling. We are shipping updates across all Hiro tools to make sure they support Nakamoto and that you can stay focused on building. - -Below find a list of how Hiro tools have been updated to support Nakamoto: - -## Stacks Explorer: What's new - -### Introducing a fresh view for blocks - -The Stacks Explorer now features a new way to display blocks, aligning with the Nakamoto upgrade's approach of multiple STX blocks settling into one BTC block. - -![Block View](./images/nakamoto-explorer.png) - -### Tailored viewing experience - -This new view is now live on both [testnet](https://explorer.hiro.so/?chain=testnet) and [mainnet](https://explorer.hiro.so/?chain=mainnet), accessible via the network dropdown. - -#### Two distinctive display modes - -1. **Independent Display:** Focuses on STX blocks progress. -2. **COMING SOON—Grouped by Bitcoin Block:** Shows BTC blocks flow alongside STX blocks. - -![Block View](./images/group-by-block.png) - -### Stay in the loop with live view - -Keep up-to-date with blocks in real-time with our new live view option. - ---- - -## Stacks.js: What’s new - -### StackingClient - -Install the latest nakamoto version with `npm install @stacks/stacking@6.13.0`. - -The StackingClient in `@stacks/stacking` was updated to match the latest pox-4 contract. - -- Added `StackingClient.signPoxSignature()` -- Added `Pox4SignatureTopic` enum -- New stacking arguments for `StackingClient.stack`, `StackingClient.stackExtend`, `StackingClient.stackIncrease`, `StackingClient.stackAggregationCommit`, and `StackingClient.stackAggregationCommitIndexed` - -[Learn more](/stacks/nakamoto/guides/stacks-js) about the new Stacks.js updates. - ---- - -## Clarinet: What’s new - -Make sure to install [Clarinet 2.8.0](https://github.com/hirosystems/clarinet/releases/tag/v2.8.0) or above. - -- Clarinet's devnet can now be used to test Nakamoto functionality. -- The devnet now starts 2 signer nodes in Nakamoto mode. -- Running `clarinet check --enable-clarity-wasm` now runs the current interpreter and clarity wasm side-by-side to allow comparing outputs. -- `clarinet console --enable-clarity-wasm` now automatically runs the current interpreter and clarity wasm side-by-side and logs any difference in outputs. - -By default, the Devnet won't start in epoch 3.0, [see this guide](/stacks/nakamoto/guides/clarinet) to configure it. - ---- - -## Stacks Blockchain API: What’s new - -> **_NOTE:_** -> -> The `/extended/v2/*` endpoints represent the modern API that is being continually expanded to support the Nakamoto upgrade. We encourage developers to use v2 endpoints for new developments. Be aware that `/extended/v1/*` are the older set of endpoints. Though they continue to function alongside v2, they will be deprecated in the coming months. - -### Nakamoto endpoints - -The Stacks Blockchain API has a series of new endpoints to support the upcoming Nakamoto upgrade: - -- Get Proof-of-Transfer details per Cycle, including Signers and Stackers, with information about stacked STX amounts, payout addresses and signer weights -- Get a list of Stacks blocks per Bitcoin block to support the new Nakamoto mining mechanism -- Get all transactions relevant to a STX address or contract ID, including filters for FT and NFT transfers -- Support for the new Nakamoto `tenure_change` transaction type across all our transaction endpoints -- Get a summary of current network mempool transaction fees, including statistics for expected confirmation priorities -- Get the deployment status of multiple smart contracts in one call - -All of these endpoints are backwards compatible with Stacks nodes running version 2.4 or earlier - -### Event replay optimizations - -- Optimize replay speed by creating a new parquet-based ingestion that optimizes for canonical chain information -- Optimize classic TSV event replay by improving block ingestion times - -### New transaction type `tenure_change` - -Affects endpoints: - -- `/extended/v1/address/{principal}/transactions` -- `/extended/v1/tx` -- `/extended/v1/tx/{tx_id}` -- `/extended/v1/tx/{tx_id}/raw` -- `/extended/v1/tx/mempool` -- `/extended/v1/tx/multiple` - -### New endpoints: `/extended/v2/*` - -- `/extended/v2/mempool/fees` -- `/extended/v2/burn-blocks` -- `/extended/v2/burn-blocks/{height_or_hash}` -- `/extended/v2/burn-blocks/{height_or_hash}/blocks` -- `/extended/v2/blocks` -- `/extended/v2/blocks/{height_or_hash}` -- `/extended/v2/blocks/{height_or_hash}/transactions` -- `/extended/v2/addresses/{address}/transactions:` -- `/extended/v2/addresses/{address}/transactions/{tx_id}/events:` -- `/extended/v2/smart-contracts/status` -- `/extended/v2/pox/cycles` -- `/extended/v2/pox/cycles/{cycle_number}` -- `/extended/v2/pox/cycles/{cycle_number}/signers` -- `/extended/v2/pox/cycles/{cycle_number}/signers/{signer_key}` -- `/extended/v2/pox/cycles/{cycle_number}/signers/{signer_key}/stackers` - -### Deprecated endpoints - -- `/extended/v1/block` -- `/extended/v1/block/{hash}` -- `/extended/v1/block/by_height/{height}` -- `/extended/v1/block/by_burn_block_hash/{burn_block_hash}` -- `/extended/v1/block/by_burn_block_height/{burn_block_height}` -- `/extended/v1/address/{principal}/transactions` -- `/extended/v1/address/{principal}/{tx_id}/with_transfers` -- `/extended/v1/address/{principal}/transactions_with_transfers` -- `/extended/v1/fee_rate` -- `/extended/v1/tx/block/{block_hash}` -- `/extended/v1/tx/block_height/{height}` - -View the [API reference](/stacks/api/info). diff --git a/content/docs/stacks/nakamoto/meta.json b/content/docs/stacks/nakamoto/meta.json deleted file mode 100644 index bc129f3ac..000000000 --- a/content/docs/stacks/nakamoto/meta.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "title": "Nakamoto support", - "root": true, - "pages": [ - "---Nakamoto---", - "index", - "---Nakamoto Updates By Product---", - "guides/clarinet", - "guides/explorer", - "guides/stacks-js", - "guides/stacks-api" - ] -} diff --git a/content/docs/stacks/platform-api/chainhooks/create.mdx b/content/docs/stacks/platform-api/chainhooks/create.mdx deleted file mode 100644 index 3e6eb6f4d..000000000 --- a/content/docs/stacks/platform-api/chainhooks/create.mdx +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: Create a chainhook -description: Create a chainhook through the Hiro Platform. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - ObjectCollapsible, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Create a chainhook - -### Request Body - - - -Chainhook predicate configuration - - - -```json -{ - "name": "platform-api", - "uuid": "aa3626dc-2090-49cd-8f1e-8f9994393aed", - "chain": "stacks", - "version": 1, - "networks": { - "mainnet": { - "if_this": { - "scope": "block_height", - "higher_than": 161620 - }, - "end_block": null, - "then_that": { - "http_post": { - "url": "https://webhook.site", - "authorization_header": "12345" - } - }, - "start_block": 161620, - "decode_clarity_values": true, - "expire_after_occurrence": null - } - } -} -``` - - - - - -### Path Parameters - - - -Hiro API key - -Pattern: `"0941f307fd270ace19a5bfed67fbd3bc"` - - - -| Status code | Description | -| :----------- | :----------- | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X POST "https://api.platform.hiro.so/v1/ext/{apiKey}/chainhooks" \ - -d '{chainhookPredicate}' -``` - - - - - -```js -fetch("https://api.platform.hiro.so/v1/ext/{apiKey}/chainhooks", { - method: "POST" -}); -``` - - - - - - - - - - - - - -```json -{ - "status": "string", - "chainhookUuid": "string" -} -``` - - - - - -```ts -export interface Response { - status: string; - chainhookUuid: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/platform-api/chainhooks/delete.mdx b/content/docs/stacks/platform-api/chainhooks/delete.mdx deleted file mode 100644 index 3e37ef0aa..000000000 --- a/content/docs/stacks/platform-api/chainhooks/delete.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Delete a chainhook -description: Delete a chainhook through the Hiro Platform. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Delete a chainhook - -### Path Parameters - - - -Hiro API key - -Pattern: `"0941f307fd270ace19a5bfed67fbd3bc"` - - - - - -Chainhook UUID - -Pattern: `"aa3626dc-2090-49cd-8f1e-8f9994393aed"` - - - -| Status code | Description | -| :----------- | :----------- | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X DELETE "https://api.platform.hiro.so/v1/ext/{apiKey}/chainhooks/{chainhookUuid}" -``` - - - - - -```js -fetch("https://api.platform.hiro.so/v1/ext/{apiKey}/chainhooks/{chainhookUuid}", { - method: "DELETE" -}); -``` - - - - - - - - - - - - - -```json -{ - "status": "string", - "chainhookUuid": "string", - "message": "string" -} -``` - - - - - -```ts -export interface Response { - status: string; - chainhookUuid: string; - message?: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/platform-api/chainhooks/get.mdx b/content/docs/stacks/platform-api/chainhooks/get.mdx deleted file mode 100644 index 4ab3ae2a5..000000000 --- a/content/docs/stacks/platform-api/chainhooks/get.mdx +++ /dev/null @@ -1,153 +0,0 @@ ---- -title: Get a specific chainhook -description: Get a specific chainhook through the Hiro Platform. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Retrieve a chainhook - -### Path Parameters - - - -Hiro API key - -Pattern: `"0941f307fd270ace19a5bfed67fbd3bc"` - - - - - -Chainhook UUID - -Pattern: `"aa3626dc-2090-49cd-8f1e-8f9994393aed"` - - - -| Status code | Description | -| :----------- | :----------- | -| `200` | Default Response | -| `404` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.platform.hiro.so/v1/ext/{apiKey}/chainhooks/{chainhookUuid}" -``` - - - - - -```js -fetch("https://api.platform.hiro.so/v1/ext/{apiKey}/chainhooks/{chainhookUuid}", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "property1": null, - "property2": null -} -``` - - - - - -```ts -export interface Response { - [k: string]: unknown; -} -``` - - - - - - - - - - - - - -```json -{ - "status": "string", - "message": "string", - "error": null -} -``` - - - - - -```ts -export interface Response { - status: string; - message?: string; - error?: unknown; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/platform-api/chainhooks/index.mdx b/content/docs/stacks/platform-api/chainhooks/index.mdx deleted file mode 100644 index cb864e0d6..000000000 --- a/content/docs/stacks/platform-api/chainhooks/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Chainhooks -index: true -toc: false -description: Retrieves information about the Platform Chainhooks API. ---- diff --git a/content/docs/stacks/platform-api/chainhooks/list.mdx b/content/docs/stacks/platform-api/chainhooks/list.mdx deleted file mode 100644 index a4850ae2a..000000000 --- a/content/docs/stacks/platform-api/chainhooks/list.mdx +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Get all chainhooks -description: Get all of your chainhooks through the Hiro Platform. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## List all chainhooks - -### Path Parameters - - - - - -| Status code | Description | -| :----------- | :----------- | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.platform.hiro.so/v1/ext/{apiKey}/chainhooks" -``` - - - - - -```js -fetch("https://api.platform.hiro.so/v1/ext/{apiKey}/chainhooks", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -[ - null -] -``` - - - - - -```ts -export type Response = unknown[]; -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/platform-api/chainhooks/status.mdx b/content/docs/stacks/platform-api/chainhooks/status.mdx deleted file mode 100644 index 59098382c..000000000 --- a/content/docs/stacks/platform-api/chainhooks/status.mdx +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: Get a chainhook status -description: Retrieve the status of a specific chainhook through the Hiro Platform. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Retrieve a chainhook status - -### Path Parameters - - - -Hiro API key - -Pattern: `"0941f307fd270ace19a5bfed67fbd3bc"` - - - - - -Chainhook UUID - -Pattern: `"aa3626dc-2090-49cd-8f1e-8f9994393aed"` - - - -| Status code | Description | -| :----------- | :----------- | -| `200` | Successfully retrieved chainhook status | -| `404` | Chainhook not found | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.platform.hiro.so/v1/ext/{apiKey}/chainhooks/{chainhookUuid}/status" -``` - - - - - -```js -fetch("https://api.platform.hiro.so/v1/ext/{apiKey}/chainhooks/{chainhookUuid}/status", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "status": { - "info": { - "expired_at_block_height": 162515, - "last_evaluated_block_height": 162515, - "last_occurrence": 1724075618, - "number_of_blocks_evaluated": 4, - "number_of_times_triggered": 3 - }, - "type": "confirmed_expiration" - }, - "enabled": false -} -``` - - - - - -```ts -export interface Response { - status: { - info: { - expired_at_block_height: number; - last_evaluated_block_height: number; - last_occurrence: number; - number_of_blocks_evaluated: number; - number_of_times_triggered: number; - }; - type: string; - }; - enabled: boolean; -} -``` - - - - - - - - - - - - - -```json -{ - "status": "string", - "message": "string", - "error": null -} -``` - - - - - -```ts -export interface Response { - status: string; - message?: string; - error?: unknown; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/platform-api/chainhooks/update.mdx b/content/docs/stacks/platform-api/chainhooks/update.mdx deleted file mode 100644 index 903f68933..000000000 --- a/content/docs/stacks/platform-api/chainhooks/update.mdx +++ /dev/null @@ -1,196 +0,0 @@ ---- -title: Update a chainhook -description: Update a chainhook through the Hiro Platform. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Update a chainhook - -### Request Body - - - -Chainhook predicate configuration - - - -### Path Parameters - - - -Hiro API key - -Pattern: `"0941f307fd270ace19a5bfed67fbd3bc"` - - - - - -Chainhook UUID - -Pattern: `"aa3626dc-2090-49cd-8f1e-8f9994393aed"` - - - -| Status code | Description | -| :----------- | :----------- | -| `200` | Default Response | -| `404` | Default Response | -| `500` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X PUT "https://api.platform.hiro.so/v1/ext/{apiKey}/chainhooks/{chainhookUuid}" \ - -d 'string' -``` - - - - - -```js -fetch("https://api.platform.hiro.so/v1/ext/{apiKey}/chainhooks/{chainhookUuid}", { - method: "PUT" -}); -``` - - - - - - - - - - - - - -```json -{ - "status": "string", - "chainhookUuid": "string" -} -``` - - - - - -```ts -export interface Response { - status: string; - chainhookUuid: string; -} -``` - - - - - - - - - - - - - -```json -{ - "status": "string", - "message": "string", - "error": null -} -``` - - - - - -```ts -export interface Response { - status: string; - message?: string; - error?: unknown; -} -``` - - - - - - - - - - - - - -```json -{ - "status": "string", - "message": "string", - "error": null -} -``` - - - - - -```ts -export interface Response { - status: string; - message?: string; - error?: unknown; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/platform-api/devnet/bitcoin-node.mdx b/content/docs/stacks/platform-api/devnet/bitcoin-node.mdx deleted file mode 100644 index 253be449f..000000000 --- a/content/docs/stacks/platform-api/devnet/bitcoin-node.mdx +++ /dev/null @@ -1,217 +0,0 @@ ---- -title: Bitcoin node -description: Proxy for the Bitcoin node on a development network (devnet). -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Bitcoin node - -This endpoint is designed to proxy requests to the Bitcoin node on a development network (devnet). - -It is accessible only with an API key and supports various HTTP methods (GET, POST, PUT, DELETE, PATCH, OPTIONS). - -### Path parameters - - - -Hiro API key - -Pattern: `"0941f307fd270ace19a5bfed67fbd3bc"` - - - - - -The path (endpoint) for the Bitcoin node RPC - -Pattern: `"rest/chaininfo"` - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.platform.hiro.so/v1/ext/{apiKey}/bitcoin-node/extended/v1/tx" -``` - - - - - -```js -fetch("https://api.platform.hiro.so/v1/ext/{apiKey}/bitcoin-node/extended/v1/tx", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{} -``` - - - - - -```ts -export interface Response { - [k: string]: unknown; -} -``` - - - - - - - - - - - - - - - - - -## Bitcoin node - -This endpoint is designed to proxy requests to the Bitcoin node on a development network (devnet). - -It is accessible only with an API key and supports various HTTP methods (GET, POST, PUT, DELETE, PATCH, OPTIONS). - -### Path parameters - - - -Hiro API key - -Pattern: `"0941f307fd270ace19a5bfed67fbd3bc"` - - - - - -The path (endpoint) for the Bitcoin node RPC - -Pattern: `"rest/chaininfo"` - - - -| Status code | Description | -| :----------- | :----------- | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X POST "https://api.platform.hiro.so/v1/ext/{apiKey}/bitcoin-node/rest/chaininfo" -``` - - - - - -```js -fetch("https://api.platform.hiro.so/v1/ext/{apiKey}/bitcoin-node/rest/chaininfo", { - method: "POST" -}); -``` - - - - - - - - - - - - - -```json -{} -``` - - - - - -```ts -export interface Response { - [k: string]: unknown; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/platform-api/devnet/index.mdx b/content/docs/stacks/platform-api/devnet/index.mdx deleted file mode 100644 index 221ed9d46..000000000 --- a/content/docs/stacks/platform-api/devnet/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Devnet -index: true -toc: false -description: Retrieves information about the Platform Devnet services such as Stacks Blockchain API, Bitcoin node, and more. ---- diff --git a/content/docs/stacks/platform-api/devnet/stacks-blockchain-api.mdx b/content/docs/stacks/platform-api/devnet/stacks-blockchain-api.mdx deleted file mode 100644 index 46488207b..000000000 --- a/content/docs/stacks/platform-api/devnet/stacks-blockchain-api.mdx +++ /dev/null @@ -1,217 +0,0 @@ ---- -title: Stacks Blockchain API -description: Proxy for the Stacks Blockchain API on a development network (devnet). -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Stacks Blockchain API - -This endpoint is designed to proxy requests to the Stacks blockchain API on a development network (devnet). - -It is accessible only with an API key and supports various HTTP methods (GET, POST, PUT, DELETE, PATCH, OPTIONS). - -### Path Parameters - - - -Hiro API key - -Pattern: `"0941f307fd270ace19a5bfed67fbd3bc"` - - - - - -The path (endpoint) for the Stacks Blockchain API - -Pattern: `"extended/v1/tx"` - - - -| Status code | Description | -| :----------- | :----------- | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.platform.hiro.so/v1/ext/{apiKey}/stacks-blockchain-api/extended/v1/tx" -``` - - - - - -```js -fetch("https://api.platform.hiro.so/v1/ext/{apiKey}/stacks-blockchain-api/extended/v1/tx", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{} -``` - - - - - -```ts -export interface Response { - [k: string]: unknown; -} -``` - - - - - - - - - - - - - - - - - -## Stacks Blockchain API - -This endpoint is designed to proxy requests to the Stacks blockchain API on a development network (devnet). - -It is accessible only with an API key and supports various HTTP methods (GET, POST, PUT, DELETE, PATCH, OPTIONS). - -### Path Parameters - - - -Hiro API key - -Pattern: `"0941f307fd270ace19a5bfed67fbd3bc"` - - - - - -The path (endpoint) for the Stacks Blockchain API - -Pattern: `"extended/v1/tx"` - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X POST "https://api.platform.hiro.so/v1/ext/{apiKey}/stacks-blockchain-api/v2/transactions" -``` - - - - - -```js -fetch("https://api.platform.hiro.so/v1/ext/{apiKey}/stacks-blockchain-api/v2/transactions", { - method: "POST" -}); -``` - - - - - - - - - - - - - -```json -{} -``` - - - - - -```ts -export interface Response { - [k: string]: unknown; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/platform-api/devnet/start.mdx b/content/docs/stacks/platform-api/devnet/start.mdx deleted file mode 100644 index 6119895c5..000000000 --- a/content/docs/stacks/platform-api/devnet/start.mdx +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Start devnet -description: Start a development network (devnet). -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Start devnet - -This endpoint starts a devnet service. - -### Request Body - - - -JSON file containing the devnet plan. The file can be created using `clarinet devnet package`. - -Example: `@default.devnet-plan.json` - - - -### Path Parameters - - - -Hiro API key - -Pattern: `"0941f307fd270ace19a5bfed67fbd3bc"` - - - - - -Project name - -Pattern: `"clarity-bitcoin-197s"` - - - -| Status code | Description | -| :----------- | :----------- | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X PUT -F "file=@default.devnet-plan.json" "https://api.platform.hiro.so/v1/ext/{apiKey}/devnet/{projectName}" -``` - - - - - -```js -const devnetPlan = { - // Your devnet plan object here -}; - -fetch("https://api.platform.hiro.so/v1/ext/{apiKey}/devnet/{projectName}", { - method: "PUT", - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(devnetPlan) -}); -``` - - - - - - - - - - - - - -```json -{} -``` - - - - - -```ts -export interface Response {} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/platform-api/devnet/stop.mdx b/content/docs/stacks/platform-api/devnet/stop.mdx deleted file mode 100644 index e67da7cc4..000000000 --- a/content/docs/stacks/platform-api/devnet/stop.mdx +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: Stop devnet -description: Stop a development network (devnet). -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Stop devnet - -### Path Parameters - - - -Hiro API key - -Pattern: `"0941f307fd270ace19a5bfed67fbd3bc"` - - - -| Status code | Description | -| :----------- | :----------- | -| `200` | Default Response | - - - - - - - - - - - - - -```terminal -$ curl -X DELETE "https://api.platform.hiro.so/v1/ext/{apiKey}/devnet" -``` - - - - - -```js -fetch("https://api.platform.hiro.so/v1/ext/{apiKey}/devnet", { - method: "DELETE" -}); -``` - - - - - - - - - - - - - -```json -Ok -``` - - - - - -```ts -export interface Response {} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/platform-api/index.mdx b/content/docs/stacks/platform-api/index.mdx deleted file mode 100644 index 81faeb6e3..000000000 --- a/content/docs/stacks/platform-api/index.mdx +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Overview -description: Leverage programmatic API access in order to seamlessly interact with devnet and manage chainhooks. ---- - -import { SecondaryCard } from '@/components/card'; - -The Platform API unlocks powerful automation opportunities in your application code, development and CI scripts, and more, via a familiar REST interface. - -In particular, this API lets you programmatically create, update, query, and delete chainhooks as well as interact with a platform-hosted devnet from your local machine. - -When you create a Platform account, you'll automatically receive an API key that's required to use these endpoints. You can also create additional API keys in the [Hiro Platform](/stacks/api-keys) as needed. - -## Popular endpoints - - - - - - - - -## Related tools - -- **[Hiro Platform](/stacks/platform)**: A developer platform for building, deploying and scaling Bitcoin apps. -- **[Chainhook](/stacks/chainhook)**: You don't need the platform to create event streams. Leverage chainhook independently, so your app can react to on-chain events in real time. -- **[Stacks Blockchain API](/stacks/api)**: Fetch on-chain data from the Stacks blockchain. -- **[Token Metadata API](/stacks/token-metadata-api)**: Fetch fungible and non-fungible token data on the Stacks blockchain. - -
- - -Reach out to us on the #hiro-platform channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET. - - - - diff --git a/content/docs/stacks/platform-api/meta.json b/content/docs/stacks/platform-api/meta.json deleted file mode 100644 index 034c590e9..000000000 --- a/content/docs/stacks/platform-api/meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "title": "Platform API", - "root": true, - "pages": [ - "---Platform API---", - "index", - "---API Reference---", - "chainhooks", - "devnet" - ] -} diff --git a/content/docs/stacks/platform/guides/archive-project.mdx b/content/docs/stacks/platform/guides/archive-project.mdx deleted file mode 100644 index 7522547ac..000000000 --- a/content/docs/stacks/platform/guides/archive-project.mdx +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Archive a project -description: Discover how to archive your projects in the Hiro Platform. ---- - -## Archive a project - -Sometimes, you may find it necessary to archive a project from your project list. It is important to understand that archiving a project is not the same as deleting a project. Archiving a project means you wish to move the project status from an active project to one that is not active and visible in your project list. - -Follow the steps below to archive a project: - -1. Sign in to the [Hiro Platform](https://platform.hiro.so/). -2. Once you are authenticated, you will be redirected to the project page. -3. From your list of projects, find the project you wish to archive. -4. Click on the far-right three dots and select "Archive." This will remove the project from the project list and place it into an archive folder. - -![Archive project](../images/archive-project/archive.png) - -## Unarchive a project - -Follow the steps below to unarchive a project: - -1. From the projects page in the Hiro Platform, select the "Archive" button at the top right. and select the far-right three dots and select "Unarchive." -2. You will now see a list of archived projects. Select three-dots on the far right and click "Unarchive" for any project you want to unarchive. -3. You will now see any unarchived projects back in your project list. - -![Unarchive project](../images/archive-project/unarchive.png) - - - Deleting a project is not yet available in the BETA version. - diff --git a/content/docs/stacks/platform/guides/contract-monitoring.mdx b/content/docs/stacks/platform/guides/contract-monitoring.mdx deleted file mode 100644 index 4928c3dbf..000000000 --- a/content/docs/stacks/platform/guides/contract-monitoring.mdx +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Monitor contracts -description: Learn how to monitor your contract with custom alerts after you deploy to mainnet. ---- - -This feature goes beyond just security—it's also a way to better understand how your contracts are being used. You can also set up alerts for various public functions in your smart contract to gain insight on which functions are receiving the most calls and how users are interacting with your contract. - -## Set up contract monitoring - - - Make sure to have successfully deployed your contracts to the Stacks mainnet if you plan on setting up alert monitoring for your own contracts. - - -If you have successfully deployed your contracts or want to set up alert monitoring for other contracts on mainnet, toggle to the Monitor tab after logging into the [Hiro Platform](https://platform.hiro.so). - -![Start monitoring](../images/contract-monitoring/start-monitoring.png) - -## Add contract for monitoring - -After clicking on the 'Add contract' button, a slideout modal will appear with fields for you to look up any smart contract on mainnet using the contract's principal and contract name. All contracts deployed to mainnet are public, and you can monitor and set up alerts for any of them, regardless of whether you are the deployer. - -Alternatively, you can also connect your wallet to view your deployment history and choose any contracts you’ve previously deployed in order to set up alerts for them. - -![Add contract](../images/contract-monitoring/add-contract.png) - -Your contract will then appear under Contract Monitoring. Once you are monitoring a particular contract, you can view its transaction history and any pending transactions in the mempool. Click on "Create an alert" to create a specific alert you want to monitor for. - -![Added contract](../images/contract-monitoring/added-contract.png) - -## Add custom alert - -You can configure alerts for any contract calls on mainnet, whether that’s a `set-contract-owner` function, a transfer/mint/burn function, or anything else you’ve implemented that you want to monitor. - -Once you identify the function calls you want to monitor, you can further hone in on the specific calls by creating filters for argument values and the address of the wallet which called the function. - -The specific conditions you can choose to monitor for include: - -- When a particular function is called -- When a particular function is called with a specified argument -- When a particular function is called by a specified address - -You can monitor these alerts in the Hiro Platform, and you can also choose to receive email alerts every time one of those alerts is triggered. Alternatively, you can configure webhook calls, which can be used for all kinds of customized alerting flows. - -![Create alert form](../images/contract-monitoring/create-alert-form.png) - -## Monitor your alerts - -With each alert you set up, you can view the alert’s history and the response status from any webhook calls made. You also have the ability to edit existing alerts to change your alert conditions or notification preferences at any time. - -![View alerts page](../images/contract-monitoring/view-alerts-page.png) - -## What to expect from alerts - -If you've specified an email as the notification type, alert notification emails will come from Hiro Platform ``. - -If you've specified a webhook to send an alert to an API endpoint, then the alert payload will look like `sample-alert-payload.json` below. - - - Note that `tx_status` will always return a "pending" status for monitor alert notifications. This is because contract monitoring alerts will only send notifications when your custom notification alert on a particular function hits the mempool, but not when it gets confirmed in the blockchain. - - - - - ```json sample-alert-payload.json - { - "tx_id": "0xa7f511b3f379efef6fe71d0de57712ed13a89c5b6e24dd049eb2cc9a7c24fcb5", - "nonce": 5, - "fee_rate": "250", - "sender_address": "SP2W9QYAHJNS7YTQY9EK2MSTQGX9E2NDMV766JP9Z", - "sponsored": false, - "post_condition_mode": "deny", - "post_conditions": [ - { - "type": "stx", - "condition_code": "sent_equal_to", - "amount": "3000000", - "principal": { - "type_id": "principal_standard", - "address": "SP2W9QYAHJNS7YTQY9EK2MSTQGX9E2NDMV766JP9Z" - } - } - ], - "anchor_mode": "any", - "tx_status": "pending", - "receipt_time": 1726104636, - "receipt_time_iso": "2024-09-12T01:30:36.000Z", - "tx_type": "contract_call", - "contract_call": { - "contract_id": "SPHW0EJK5KPDMK03ZX792EMP0Q5J3A39ZMTVZZCY.sample-contract", - "function_name": "donate", - "function_signature": "(define-public (donate (amount uint)))", - "function_args": [ - { - "hex": "0x01000000000000000000000000002dc6c0", - "repr": "u3000000", - "name": "amount", - "type": "uint" - } - ] - } - } - ``` - - - ```ts title="sample-alert-interface.ts" - interface Body { - tx_id: string; - nonce: number; - fee_rate: string; - sender_address: string; - sponsored: boolean; - post_condition_mode: string; - post_conditions: Postcondition[]; - anchor_mode: string; - tx_status: string; - receipt_time: number; - receipt_time_iso: string; - tx_type: string; - contract_call: Contractcall; - } - interface Contractcall { - contract_id: string; - function_name: string; - function_signature: string; - function_args: Functionarg[]; - } - interface Functionarg { - hex: string; - repr: string; - name: string; - type: string; - } - interface Postcondition { - type: string; - condition_code: string; - amount: string; - principal: Principal; - } - interface Principal { - type_id: string; - address: string; - } - ``` - - \ No newline at end of file diff --git a/content/docs/stacks/platform/guides/create-chainhooks.mdx b/content/docs/stacks/platform/guides/create-chainhooks.mdx deleted file mode 100644 index 7d488cb70..000000000 --- a/content/docs/stacks/platform/guides/create-chainhooks.mdx +++ /dev/null @@ -1,117 +0,0 @@ ---- -title: Create a chainhook -description: Create a chainhook using the Hiro Platform. ---- - -With Chainhook, you can automatically trigger an action in response to on-chain events on Stacks and Bitcoin, enabling you to use IFTTT (if_this, then_that) logic to power your applications. To learn more about Chainhook, refer to the [Chainhook overview](/stacks/chainhook). - - - You can also create and manage chainhooks via the [Platform API](/stacks/platform-api/chainhooks). - - -To get started in the Hiro Platform, login and toggle to the Chainhook page. There are two ways to create a chainhook. You can either create a chainhook from scratch using the platform UI, or you can upload chainhooks that you have already defined in JSON. - -![Create Chainhook Window](../images/chainhook/select-chainhook-tab.png) - -Select the "New Chainhook" button. - -![Create Chainhook Window](../images/chainhook/create-chainhook-window.png) - -This will open a panel on the right to create a chainhook. Use the following fields to create a Chainhook: - -**Name**: Input the name of your chainhook. - -**Chain**: Select which chain you want to build a chainhook for (Bitcoin or Stacks). - -**Network**: Choose which network the chainhook will observe. - -**If-this**: Based on the selected chain, you will see a list of available scopes for the `If-this` condition (also called a "predicate"). - - - -For Bitcoin, the available predicate options are `txid`,`outputs`, and - `stacks_protocols`. - - -For Stacks, the available predicate options are - `txid`, `block_height`, `fungible_token_event`, `non-fungible_token_event`, - `stx_event`, `print_event`, and `contract_deployment`. - -_Refer to the [Bitcoin predicates](/stacks/chainhook/concepts/bitcoin-predicates) and [Stacks predicates](/stacks/chainhook/concepts/stacks-predicates) documents to understand the available predicates and how to use them._ - - - -**Then-that**: This action is defaulted to `http_post` to allow the chainhook to post events to the URL specified in the next field below. - -**URL**: Specify a URL to post chainhook events to the HTTP_post method. - -**Authorization Header**: This field is optional to add a Secret to the `authorization` header when posting payloads. - -**Start Block**: This field must specify the start block to search the chain. - -**End Block**: It is optional to specify the end block. However, to optimize your scan time, we recommended you specify this field. - -**Expire After Occurrence**: You can specify the chainhook to expire after a specific number of occurrences (a number greater than or equal to 1). You can leave this blank if you don't want to set any limit. - -**Decode Clarity Values**: This is enabled by default for Stacks predicates to help you decode Clarity values in your contract. - -You'll also see the following options for Bitcoin chainhooks: - -**Include Proof**: Enable this option when you have evidence that the transaction or block has been verified and authorized by the sender using their private key. This proof is generally a cryptographic signature to a transaction or block on the Bitcoin blockchain. - -**Include Inputs**: Enable this option to include Bitcoin transaction inputs in the payload. In a Bitcoin transaction, inputs are references to previous transactions' outputs (also known as unspent transaction outputs or UTXOs) that are being spent in the current transaction. These inputs provide evidence that the sender has the right to spend the funds. - -**Include Outputs**: Enable this option to include Bitcoin transaction outputs in the payload. Including outputs in a Bitcoin transaction refers to specifying the destinations and amounts of Bitcoin being sent as part of a transaction. Outputs in a Bitcoin transaction represent the recipients' addresses and the corresponding amounts of Bitcoin they are receiving. - -**Include Witness**: Enable this option to include Bitcoin transaction witness in the payload. The witness data for a transaction includes the cryptographic signatures and other related information placed alongside the transaction data in the block. - -Once you define all the required fields, you can select "Create Chainhook", and you can now see your created chainhook on the Chainhook page. - -![Chainhook created](../images/chainhook/created.png) - -The `NAME`, `CHAIN`, `START BLOCK`, `NETWORK`, `STATUS`, and `LAST UPDATED` headers are updated based on the selected fields used to create a Chainhook. - -Based on the chosen network, the respective status columns in the Chainhook list page will be updated to "Deployed." - -Note: there may be other fields in the UI to create a Chainhook based on the predicates defined above. - -## Upload a chainhook - -To upload a chainhook, you can either select the "Upload Chainhook" button and choose the .json file that has the chainhook(s) you want to upload, or you can drag and drop the .json file into the file upload area. - -![Upload Chainhook](../images/chainhook/upload.png) - -The upload file must be a .json file containing either a single json object representing a Chainhook predicate, or an array of json objects representing one or more Chainhook predicates. - -Refer to the [Bitcoin predicates](/stacks/chainhook/concepts/bitcoin-predicates) and [Stacks predicates](/stacks/chainhook/concepts/stacks-predicates) documents to understand the available predicates and how to prepare your Chainhook predicate JSON for upload. - -## Edit a chainhook - -Once a chainhook is created, you can edit the chainhook by clicking the ellipse on the specific chainhook you want to edit. - -![Edit chainhook](../images/chainhook/edit-chainhook.png) - -Update the fields to reflect your desired changes and then select "Update chainhook." - -## Duplicate a chainhook - -Select the ellipse on the chainhook you want to duplicate and select "Duplicate." This opens a right pane with all the fields populated to use to create a duplicate Chainhook. - -You can update any fields or publish a direct copy by clicking "Create Chainhook." - -## Delete a chainhook - -Select the ellipse on the chainhook you wish to delete and select "Delete." You will see a confirmation window to confirm if you want to delete the Chainhook. - -## Chainhook status - -The Chainhook page has a `STATUS` column that displays whether your chainhooks are in an active, inactive, or error state. Active means the Chainhook is actively scanning blocks against its defined predicate, inactive means the Chainhook has reached a terminal state (e.g. its end block has been reached, and it is no longer scanning blocks), and error means the Chainhook ran into an error during its execution. - -More status info can be found by hovering over the status element. For example, to understand why the Chainhook is in an error state, hover over the status element to find out. - -![Chainhook status](../images/chainhook/status-info.png) - -## References - -- [Use Chainhooks with Bitcoin](/stacks/chainhook/concepts/bitcoin-predicates) -- [Use Chainhooks with Stacks](/stacks/chainhook/concepts/stacks-predicates) -- [Run Chainhook as a service using Bitcoind](/stacks/chainhook/guides/chainhook-as-a-service) -- [Run Chainhook as a service using Stacks](/stacks/chainhook/guides/chainhook-as-a-service-with-stacks-node) diff --git a/content/docs/stacks/platform/guides/create-project.mdx b/content/docs/stacks/platform/guides/create-project.mdx deleted file mode 100644 index 45f30f0b0..000000000 --- a/content/docs/stacks/platform/guides/create-project.mdx +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Create a project -description: Learn how to create or import a project in the Hiro Platform. ---- - -import { Code, Terminal } from "lucide-react" -import { SmallCard } from "@/components/card" - -import { Callout } from "@/components/callout" -import { Card, Cards } from "@/components/card" - -The Hiro Platform offers multiple ways to create projects, whether you're starting from scratch with a template or importing an existing repository. This guide will walk you through both approaches. - -## Using templates - -From the main projects page, click the "Add a project" button to begin creating a new project. - -![template selection](../images/create-project/c2.png) - -The Platform provides 2 types of pre-built templates to help you get started quickly: - -1. App templates -2. Contract-only templates - -**App templates** are feature rich templates pre-configured with a frontend and smart contracts. - -**Contract-only templates** are pre-configured with just that: a smart contract to help you start building. - -Simply select the template you want to get started with to open up a more detailed view of the app. - -![template selection](../images/create-project/c1.png) - -Once you are ready, click the "Clone" button to copy the template to your GitHub account. From there, you will see instructions on how to clone the repository locally to start development. - -## Importing existing projects - -If you have an existing project on GitHub, you can import it directly into the Hiro Platform: - -1. If you haven't already, authorize your GitHub account with the Hiro Platform -2. You'll see a list of your repositories that can be imported -3. Select the repository you want by clicking the "Import" button - -![import from github](../images/create-project/c3.png) - - -The Platform requires specific Clarinet-generated files and a directory structure to import projects successfully. Your project should include: - -- `.clar` files containing your smart contracts -- A `Clarinet.toml` configuration file -- A specific directory structure with contracts in a `contracts` folder - - -Once your project is ready, you will see instructions on next steps to get started. - -## Next steps - - - - - diff --git a/content/docs/stacks/platform/guides/deploy-contracts.mdx b/content/docs/stacks/platform/guides/deploy-contracts.mdx deleted file mode 100644 index f132a76e6..000000000 --- a/content/docs/stacks/platform/guides/deploy-contracts.mdx +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Deploy contracts -description: Learn how to deploy contracts in the Hiro Platform. ---- - -## Prerequisites - -- Follow the [create project](/stacks/platform/guides/create-project) guide to create or import a project. -- Make sure you have installed and connected a Stacks wallet to deploy your contracts. - -## Use the deploy button - -Once your project is setup, you can deploy the contracts to testnet or mainnet using the "Deploy" button on the Hiro Platform. - -![deploy contracts](../images/deploy-contracts/d1.png) - -The following are the steps to deploy your contracts using the deploy button. - -1. On the projects page, select the project you want to deploy contracts from. -2. Use the "Deploy Contracts" button available at the top right of the page. -3. Choose the network you want to deploy to. Note: for devnet, [reference this guide](/stacks/platform/guides/devnet). The steps below are specific to testnet and mainnet. -4. Once you choose a network, you will see a button to generate a deployment plan. -5. Once the deployment plan is generated, you will see the list of contracts to be deployed - you can now connect your wallet and click "Deploy" to deploy your contracts. - -![deploy contracts](../images/deploy-contracts/d2.png) - -If you find issues with your deployment process, you can reach out to us on the [#hiro-platform channel](https://stacks.chat) on Discord under the Hiro Developer Tools section or file an issue [here](https://hiro-pbc.canny.io/hiro-platform). diff --git a/content/docs/stacks/platform/guides/devnet.mdx b/content/docs/stacks/platform/guides/devnet.mdx deleted file mode 100644 index eddbe6aaf..000000000 --- a/content/docs/stacks/platform/guides/devnet.mdx +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Using devnet -description: Test and validate your code using devnet's private blockchain environment. ---- - -Devnet is a personal blockchain environment that lets you test and validate your contract code before deploying on a public network like testnet or mainnet. In this guide, you'll learn how to interact with devnet in the Hiro Platform to expedite your development. - -## What is devnet? - -Devnet is a private blockchain environment that lets you test and validate smart contracts quickly. Think of it as your personal sandbox: no one else can see your devnet instance, you don't have to worry about breaking it, and you can stop and restart it as many times as you need. - -While developers can run devnet locally using Clarinet, the Hiro Platform provides a hosted version that eliminates the need to manage blockchain nodes and miners on your machine. The Platform-hosted devnet still produces blocks and processes transactions, but offloads the computational overhead to our infrastructure while providing a more intuitive interface for development. - -Devnet provides a risk-free testing ground with the convenience of rapid prototyping, cost savings, and privacy. - -## Benefits of devnet on the Hiro Platform - -The Platform-hosted devnet offers several advantages: - -- **Zero local setup**: No need to configure or maintain blockchain nodes locally -- **Resource-efficient**: Offloads computational demands to our infrastructure -- **Rapid prototyping**: Quick iterations with immediate feedback -- **Cost-efficiency**: No real cryptocurrency expenses for testing -- **Seamless local integration**: Connect your local development environment to the hosted devnet -- **Isolated development**: A personal sandbox for confidential and secure testing - -## Using devnet in the Hiro Platform - -First, log into the [Hiro Platform](https://platform.hiro.so/). After [setting up your project](/stacks/platform/guides/create-project), navigate to the project page where you can select the "Devnet" tab to manage your devnet instance. - -## Starting and managing devnet - -In your project page, you'll click on the "Devnet" tab to start and manage your devnet instance. Initially, it should read "Inactive." Click on the "Start Devnet" button to start your private devnet instance. - -![Dashboard](../images/devnet/dev1.png) - - - You can also start and stop devnet programmatically via the [Platform API](/stacks/platform-api/devnet). - - -If you want to configure your devnet (like you can locally using `clarinet devnet start` in the terminal), open your project's `devnet.toml` file in the platform VS Code editor before you start devnet. From there, you can configure the settings to match your development needs. - -Once you start devnet, it will take a few moments to spin up. The status indicator on the project dashboard will keep you updated on the progress. - -## Active session management - -When devnet is ready, the status will change to 'Active'. - -If needed, you can restart devnet to refresh the timer. Keep in mind that only one devnet instance can run at a time per user account. If you need to work on a different project, simply start devnet within that project to seamlessly transition your session. There is also a monthly limit of 100 devnet sessions per account, so plan your development schedule accordingly. - -## Exploring the devnet dashboard - -The Platform's devnet dashboard provides a comprehensive interface for monitoring and interacting with your private blockchain. You can: - -- Track real-time block production through the visual "assembly line" -- Inspect block contents and transaction details -- Search through blocks efficiently -- Monitor contract deployments and function calls -- Mint new blocks on demand - -![Devnet Dashboard](../images/devnet/dev2.png) - -## Additional devnet features - -On the dashboard, you can also click the "Interact with devnet" button to call contract functions, make API requests, view devnet wallets, and more. - -For more information on devnet features, [start here](https://www.hiro.so/blog/5-ways-to-interact-with-devnet-in-the-hiro-platform). diff --git a/content/docs/stacks/platform/guides/faucet.mdx b/content/docs/stacks/platform/guides/faucet.mdx deleted file mode 100644 index 2942c7535..000000000 --- a/content/docs/stacks/platform/guides/faucet.mdx +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Request testnet STX -description: Easily request testnet STX, so you can deploy and interact with Stacks testnet. ---- - -The Stacks Testnet Faucet is a dedicated utility for developers building on the Stacks blockchain. To aid you in deploying and running smart contracts on Stacks testnet, we've provided this faucet that offers easy access to testnet STX tokens. - -![Create Chainhook Window](../images/faucet/request.png) - -## Why use the Stacks Testnet Faucet? - -Building and testing on a blockchain requires a certain amount of native tokens to facilitate various operations, from contract deployments to transaction executions. However, sourcing these tokens can often be cumbersome. The Stacks Testnet Faucet simplifies this by offering a hassle-free way to acquire STX tokens for testing purposes. - -## How to request testnet STX - -1. **Visit the faucet page**: Navigate to [platform.hiro.so/faucet](https://platform.hiro.so/faucet). -2. **Select the token**: Select which token you want, either STX or sBTC. -3. **Request tokens**: You'll find a straightforward interface with a button to request tokens. Simply click on the button "Receive x STX/sBTC." -4. **Receive 500 STX tokens or 1 sBTC**: By clicking the button, you'll receive 500 STX tokens or 1 sBTC to your testnet account. - -## Frequently Asked Questions - - - - -A faucet is an application that dispenses free tokens on a Testnet (a blockchain network used for development and testing). The Stacks faucet provides developers with free test tokens for deploying, testing, and optimizing smart contracts that leverage STX and sBTC. - -**It's important to remember that Testnet tokens have no real-world value and cannot be sold or used on the main Stacks network.** - - -Select the type of test token you wish to receive and enter the wallet address where you want to receive them. The faucet will create a transaction on the Stacks Testnet that sends a small amount of test tokens to the provided address. - -If you're curious, you can track the transaction's status using [Stacks Explorer](https://explorer.stacks.so/). - - -We securely handle the wallet address you provide while processing your request. This data is not used or shared with any other Hiro services. - - -You can make up to 5 requests every 5 minutes. For more details, see our [rate limiting policies](/stacks/rate-limiting). - - -The time for tokens to arrive to your wallet depends on how busy the network is. On average, it should take x amount of time. If the transaction seems stuck, feel free to reach out to us on our [support channel](https://stacks.chat/). - - - - - **Daily Limit**: To ensure fair distribution and availability for all - developers, there's a limit of one request per day. Plan your testing - accordingly! -{" "} diff --git a/content/docs/stacks/platform/guides/migrate-legacy-projects.mdx b/content/docs/stacks/platform/guides/migrate-legacy-projects.mdx deleted file mode 100644 index 2edf7d3d1..000000000 --- a/content/docs/stacks/platform/guides/migrate-legacy-projects.mdx +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Migrate legacy projects to GitHub -description: Learn how to migrate your legacy projects from the Hiro Platform to GitHub. ---- - -If you have legacy projects in the Hiro Platform that you want to migrate to GitHub, you can follow these steps to move your project while maintaining its version history. - -1. Sign in to the [Hiro Platform](https://platform.hiro.so/). Once you are authenticated, you will be redirected to the project page. -2. From your list of projects, find the project you wish to migrate. -3. Click on the top right dropdown to open the web editor. ![Open web editor](../images/migrate-legacy-projects/open-web-editor.png) -4. Select the Source Control Menu on the right and click 'Initialize Repository'. ![Initialize repository](../images/migrate-legacy-projects/init-repo.png) -5. Open the terminal and configure your GitHub user information. Make sure to use the email associated with your GitHub account: ![Configure Git](../images/migrate-legacy-projects/configure-git.png) - ```terminal - $ git config user.email your@email.com - $ git config user.name username - ``` -6. Commit your changes under the Source Control menu by clicking the 'Commit' button. ![Commit changes](../images/migrate-legacy-projects/commit-changes.png) -7. Click the 'Publish Branch' button to publish the branch to GitHub. ![Publish branch](../images/migrate-legacy-projects/publish-branch.png) -8. You will be prompted to sign in with GitHub. Follow the authentication process to complete pushing your project to your GitHub account. ![Sign in with GitHub](../images/migrate-legacy-projects/publish.png) - - - Make sure you have the necessary permissions and access to the GitHub repository where you want to migrate your project. - diff --git a/content/docs/stacks/platform/images/archive-project/archive.png b/content/docs/stacks/platform/images/archive-project/archive.png deleted file mode 100644 index 9b840418f..000000000 Binary files a/content/docs/stacks/platform/images/archive-project/archive.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/archive-project/unarchive.png b/content/docs/stacks/platform/images/archive-project/unarchive.png deleted file mode 100644 index 97a32efc6..000000000 Binary files a/content/docs/stacks/platform/images/archive-project/unarchive.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/chainhook/create-chainhook-window.png b/content/docs/stacks/platform/images/chainhook/create-chainhook-window.png deleted file mode 100644 index f7025cbcd..000000000 Binary files a/content/docs/stacks/platform/images/chainhook/create-chainhook-window.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/chainhook/created.png b/content/docs/stacks/platform/images/chainhook/created.png deleted file mode 100644 index ea4100331..000000000 Binary files a/content/docs/stacks/platform/images/chainhook/created.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/chainhook/edit-chainhook.png b/content/docs/stacks/platform/images/chainhook/edit-chainhook.png deleted file mode 100644 index ebf9812eb..000000000 Binary files a/content/docs/stacks/platform/images/chainhook/edit-chainhook.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/chainhook/select-chainhook-tab.png b/content/docs/stacks/platform/images/chainhook/select-chainhook-tab.png deleted file mode 100644 index eec82c1ae..000000000 Binary files a/content/docs/stacks/platform/images/chainhook/select-chainhook-tab.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/chainhook/status-info.png b/content/docs/stacks/platform/images/chainhook/status-info.png deleted file mode 100644 index 8dc61fc5a..000000000 Binary files a/content/docs/stacks/platform/images/chainhook/status-info.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/chainhook/upload.png b/content/docs/stacks/platform/images/chainhook/upload.png deleted file mode 100644 index d6fe45e7a..000000000 Binary files a/content/docs/stacks/platform/images/chainhook/upload.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/contract-monitoring/add-contract.png b/content/docs/stacks/platform/images/contract-monitoring/add-contract.png deleted file mode 100644 index 2765d93f6..000000000 Binary files a/content/docs/stacks/platform/images/contract-monitoring/add-contract.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/contract-monitoring/added-contract.png b/content/docs/stacks/platform/images/contract-monitoring/added-contract.png deleted file mode 100644 index c910ab9ff..000000000 Binary files a/content/docs/stacks/platform/images/contract-monitoring/added-contract.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/contract-monitoring/create-alert-form.png b/content/docs/stacks/platform/images/contract-monitoring/create-alert-form.png deleted file mode 100644 index efd3278da..000000000 Binary files a/content/docs/stacks/platform/images/contract-monitoring/create-alert-form.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/contract-monitoring/start-monitoring.png b/content/docs/stacks/platform/images/contract-monitoring/start-monitoring.png deleted file mode 100644 index 6f3e1b79d..000000000 Binary files a/content/docs/stacks/platform/images/contract-monitoring/start-monitoring.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/contract-monitoring/view-alerts-page.png b/content/docs/stacks/platform/images/contract-monitoring/view-alerts-page.png deleted file mode 100644 index 632abeb50..000000000 Binary files a/content/docs/stacks/platform/images/contract-monitoring/view-alerts-page.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/create-project/c1.png b/content/docs/stacks/platform/images/create-project/c1.png deleted file mode 100644 index f40a3b992..000000000 Binary files a/content/docs/stacks/platform/images/create-project/c1.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/create-project/c2.png b/content/docs/stacks/platform/images/create-project/c2.png deleted file mode 100644 index f5e309673..000000000 Binary files a/content/docs/stacks/platform/images/create-project/c2.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/create-project/c3.png b/content/docs/stacks/platform/images/create-project/c3.png deleted file mode 100644 index 41f0d7bf8..000000000 Binary files a/content/docs/stacks/platform/images/create-project/c3.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/deploy-contracts/d1.png b/content/docs/stacks/platform/images/deploy-contracts/d1.png deleted file mode 100644 index 00243c068..000000000 Binary files a/content/docs/stacks/platform/images/deploy-contracts/d1.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/deploy-contracts/d2.png b/content/docs/stacks/platform/images/deploy-contracts/d2.png deleted file mode 100644 index 2d61d1aa9..000000000 Binary files a/content/docs/stacks/platform/images/deploy-contracts/d2.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/devnet/dev1.png b/content/docs/stacks/platform/images/devnet/dev1.png deleted file mode 100644 index 4adabfa77..000000000 Binary files a/content/docs/stacks/platform/images/devnet/dev1.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/devnet/dev2.png b/content/docs/stacks/platform/images/devnet/dev2.png deleted file mode 100644 index 686e7d02d..000000000 Binary files a/content/docs/stacks/platform/images/devnet/dev2.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/faucet/request.png b/content/docs/stacks/platform/images/faucet/request.png deleted file mode 100644 index 5b7b5f554..000000000 Binary files a/content/docs/stacks/platform/images/faucet/request.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/migrate-legacy-projects/commit-changes.png b/content/docs/stacks/platform/images/migrate-legacy-projects/commit-changes.png deleted file mode 100644 index 015455524..000000000 Binary files a/content/docs/stacks/platform/images/migrate-legacy-projects/commit-changes.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/migrate-legacy-projects/configure-git.png b/content/docs/stacks/platform/images/migrate-legacy-projects/configure-git.png deleted file mode 100644 index c7f7697b0..000000000 Binary files a/content/docs/stacks/platform/images/migrate-legacy-projects/configure-git.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/migrate-legacy-projects/init-repo.png b/content/docs/stacks/platform/images/migrate-legacy-projects/init-repo.png deleted file mode 100644 index 677c7ce58..000000000 Binary files a/content/docs/stacks/platform/images/migrate-legacy-projects/init-repo.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/migrate-legacy-projects/open-web-editor.png b/content/docs/stacks/platform/images/migrate-legacy-projects/open-web-editor.png deleted file mode 100644 index 0f7c96ab7..000000000 Binary files a/content/docs/stacks/platform/images/migrate-legacy-projects/open-web-editor.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/migrate-legacy-projects/publish-branch.png b/content/docs/stacks/platform/images/migrate-legacy-projects/publish-branch.png deleted file mode 100644 index f07f2a1a7..000000000 Binary files a/content/docs/stacks/platform/images/migrate-legacy-projects/publish-branch.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/migrate-legacy-projects/publish.png b/content/docs/stacks/platform/images/migrate-legacy-projects/publish.png deleted file mode 100644 index 81b734425..000000000 Binary files a/content/docs/stacks/platform/images/migrate-legacy-projects/publish.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/o1.png b/content/docs/stacks/platform/images/o1.png deleted file mode 100644 index 60aef878c..000000000 Binary files a/content/docs/stacks/platform/images/o1.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/project/counter.png b/content/docs/stacks/platform/images/project/counter.png deleted file mode 100644 index ae6204fa6..000000000 Binary files a/content/docs/stacks/platform/images/project/counter.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/project/create-or-import.png b/content/docs/stacks/platform/images/project/create-or-import.png deleted file mode 100644 index 9398759f2..000000000 Binary files a/content/docs/stacks/platform/images/project/create-or-import.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/project/import-from-clarinet.png b/content/docs/stacks/platform/images/project/import-from-clarinet.png deleted file mode 100644 index 662a55034..000000000 Binary files a/content/docs/stacks/platform/images/project/import-from-clarinet.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/project/import-from-github.png b/content/docs/stacks/platform/images/project/import-from-github.png deleted file mode 100644 index 41a248cbf..000000000 Binary files a/content/docs/stacks/platform/images/project/import-from-github.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/project/new-project.png b/content/docs/stacks/platform/images/project/new-project.png deleted file mode 100644 index 32a13ee0d..000000000 Binary files a/content/docs/stacks/platform/images/project/new-project.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/quickstart/q1.png b/content/docs/stacks/platform/images/quickstart/q1.png deleted file mode 100644 index b07348c89..000000000 Binary files a/content/docs/stacks/platform/images/quickstart/q1.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/quickstart/q2.png b/content/docs/stacks/platform/images/quickstart/q2.png deleted file mode 100644 index b5f0ee8ac..000000000 Binary files a/content/docs/stacks/platform/images/quickstart/q2.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/quickstart/q3.png b/content/docs/stacks/platform/images/quickstart/q3.png deleted file mode 100644 index a6b080eee..000000000 Binary files a/content/docs/stacks/platform/images/quickstart/q3.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/quickstart/q4.png b/content/docs/stacks/platform/images/quickstart/q4.png deleted file mode 100644 index 240a848cc..000000000 Binary files a/content/docs/stacks/platform/images/quickstart/q4.png and /dev/null differ diff --git a/content/docs/stacks/platform/images/quickstart/q5.png b/content/docs/stacks/platform/images/quickstart/q5.png deleted file mode 100644 index f40a3b992..000000000 Binary files a/content/docs/stacks/platform/images/quickstart/q5.png and /dev/null differ diff --git a/content/docs/stacks/platform/index.mdx b/content/docs/stacks/platform/index.mdx deleted file mode 100644 index f7d2496c1..000000000 --- a/content/docs/stacks/platform/index.mdx +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Overview -description: A developer platform for building, deploying, and scaling Bitcoin apps. ---- - -import Link from "next/link"; -import { Button } from "@/components/ui/button" - -The Hiro Platform is your all-in-one solution for building and scaling Bitcoin applications. It provides essential tools including API key management, customizable data streams, production-ready app templates, dedicated testing environments, and onchain monitoring and analytics - everything developers need to bring their Bitcoin apps to life. - - - -![Projects](./images/o1.png) - -## Guides - - - - - -{" "} - - - - - - - - -## Related tools - -- **[Clarinet](/stacks/clarinet)**: Build and deploy smart contracts locally on your device with Clarinet. -- **[Chainhook](/stacks/chainhook)**: You don’t need the platform to create event streams. Leverage chainhook independently, so your app can react to on-chain events in real time. -- **[Stacks.js](/stacks/stacks.js)**: Don’t reinvent the wheel. Build faster with a JS library that handles basic functions. - -
- - -Reach out to us on the #hiro-platform channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET. - diff --git a/content/docs/stacks/platform/meta.json b/content/docs/stacks/platform/meta.json deleted file mode 100644 index f997458d5..000000000 --- a/content/docs/stacks/platform/meta.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "title": "Hiro Platform", - "root": true, - "pages": [ - "---Hiro Platform---", - "index", - "quickstart", - "---Guides---", - "guides/create-project", - "guides/devnet", - "guides/faucet", - "guides/create-chainhooks", - "guides/deploy-contracts", - "guides/contract-monitoring", - "guides/archive-project", - "guides/migrate-legacy-projects" - ] -} diff --git a/content/docs/stacks/platform/quickstart.mdx b/content/docs/stacks/platform/quickstart.mdx deleted file mode 100644 index 488004255..000000000 --- a/content/docs/stacks/platform/quickstart.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: Quickstart -description: Create and deploy your first app in the Hiro Platform. ---- - -import { Code, Terminal } from "lucide-react" -import { SmallCard } from "@/components/card" - -In this quickstart guide, you will create a simple fundraising app using one of the app templates available. This app features a single page that displays a fundraising campaign, and functionality that handles campaign contributions, refunds, and withdrawal by the fundraiser. - -## Create your account - -Start by creating an account in the Hiro Platform. You can create an account with: - -- Email -- Google -- GitHub -- Discord - -![Platform Login](./images/quickstart/q1.png) - -Once signed in, you will see an onboarding screen showing all the Hiro Platform has to offer: - -![Platform Welcome Screen](./images/quickstart/q2.png) - -## Create your project - -If you do not have any existing projects, you will be prompted to create one on the projects page. Click the "Add a project" button to get started. - - -If you already have projects, you can find the "Add a project" button at the top right of the page. - - -From here, you have the option to choose from a set of templates or import an existing project from your GitHub account. For this quickstart, select the "Fundraising App" template, which is a starter project that comes equipped with both a frontend and smart contracts. - -![choose template](./images/quickstart/q5.png) - - -To see a list of your repositories and import an existing project, you will first need to authorize with GitHub. - - -## Clone your project - -Once you have selected your project, you will be presented with the full set of details for the project. From here, you can clone the project to your GitHub account by clicking the "Clone" button. - -![template details](./images/quickstart/q3.png) - - -You will need to authorize with Github before being able to clone the project. - - -Once the project is ready and available in your GitHub account, you will see instructions on how to clone the project to your local machine or develop in the browser via Github Codespaces. - -![template ready](./images/quickstart/q4.png) - -You are now ready to start building! - -## Next steps - - - - - - diff --git a/content/docs/stacks/rate-limiting.mdx b/content/docs/stacks/rate-limiting.mdx deleted file mode 100644 index 8f07a848b..000000000 --- a/content/docs/stacks/rate-limiting.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: Rate limiting -description: Understand the rate limits for Hiro APIs and testnet faucets. ---- - -import RateLimitingContent from '@/snippets/rate-limiting.mdx'; - - diff --git a/content/docs/stacks/rpc-api/accounts/index.mdx b/content/docs/stacks/rpc-api/accounts/index.mdx deleted file mode 100644 index bfd9e48f5..000000000 --- a/content/docs/stacks/rpc-api/accounts/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Accounts -index: true -toc: false -description: Get account information. ---- \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/accounts/info.mdx b/content/docs/stacks/rpc-api/accounts/info.mdx deleted file mode 100644 index 11525e77f..000000000 --- a/content/docs/stacks/rpc-api/accounts/info.mdx +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Get account info -description: Retrieves the account data for a given account or contract identifier. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get account info - -Get the account data for the provided principal - -Where balance is the hex encoding of a unsigned 128-bit integer (big-endian), nonce is a unsigned 64-bit integer, and the proofs are provided as hex strings. - -For non-existent accounts, this does not 404, rather it returns an object with balance and nonce of 0. - - -### Path Parameters - - - -Stacks address or a Contract identifier (e.g. `SP31DA6FTSJX2WGTZ69SFY11BH51NZMB0ZW97B5P0.get-info`) - - - -### Query Parameters - - - -Returns object without the proof field if set to 0 - - - - - -The Stacks chain tip to query from. If tip == latest, the query will be run from the latest known tip (includes unconfirmed state). - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "http://localhost:20443/v2/accounts/string?proof=0&tip=string" -``` - - - - - -```js -fetch("http://localhost:20443/v2/accounts/string?proof=0&tip=string", { - method: "GET" -}); -``` - - - - - - - - - -GET request for account data - - - - - -```json -{ - "balance": "string", - "locked": "string", - "unlock_height": 0, - "nonce": 0, - "balance_proof": "string", - "nonce_proof": "string" -} -``` - - - - - -```ts -/** - * GET request for account data - */ -export interface AccountDataResponse { - balance: string; - locked: string; - unlock_height: number; - nonce: number; - balance_proof: string; - nonce_proof: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/rpc-api/accounts/meta.json b/content/docs/stacks/rpc-api/accounts/meta.json deleted file mode 100644 index d2bf1632c..000000000 --- a/content/docs/stacks/rpc-api/accounts/meta.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "title": "Accounts", - "pages": [ - "info" - ], - "defaultOpen": false -} \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/blocks/block-proposal.mdx b/content/docs/stacks/rpc-api/blocks/block-proposal.mdx deleted file mode 100644 index 4ae7a3157..000000000 --- a/content/docs/stacks/rpc-api/blocks/block-proposal.mdx +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: Validate proposed block -description: Validate a proposed Stacks block. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Validate a proposed Stacks block - -Used by stackers to validate a proposed Stacks block from a miner. - -**This API endpoint requires a basic Authorization header.** - - -### Request Body (Optional) - - - - - - - - - -| Status code | Description | -| ----------- | ----------- | -| `202` | Block proposal has been accepted for processing. The result will be returned via the event observer. | -| `403` | Request not over loopback interface | -| `429` | There is an ongoing proposal validation being processed, the new request cannot be accepted until the prior request has been processed. | - - - - - - - - - - - - - -```terminal -$ curl -X POST "http://localhost:20443/v2/block_proposal" \ - -d '{ - "block": "string", - "chain_id": 0 -}' -``` - - - - - -```js -fetch("http://localhost:20443/v2/block_proposal", { - method: "POST" -}); -``` - - - - - - - - - - - - - -```json -{ - "message": "string", - "result": "string" -} -``` - - - - - -```ts -export interface Response { - message?: string; - result?: string; -} -``` - - - - - - - - - - - - - -```json -{ - "message": "string", - "result": "string" -} -``` - - - - - -```ts -export interface Response { - message?: string; - result?: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/rpc-api/blocks/index.mdx b/content/docs/stacks/rpc-api/blocks/index.mdx deleted file mode 100644 index 12bb3f083..000000000 --- a/content/docs/stacks/rpc-api/blocks/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Blocks -index: true -toc: false -description: Get block proposal information. ---- \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/blocks/meta.json b/content/docs/stacks/rpc-api/blocks/meta.json deleted file mode 100644 index aa59a6d39..000000000 --- a/content/docs/stacks/rpc-api/blocks/meta.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "title": "Blocks", - "pages": [ - "block-proposal" - ], - "defaultOpen": false -} \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/burn-ops/get-burn-operations.mdx b/content/docs/stacks/rpc-api/burn-ops/get-burn-operations.mdx deleted file mode 100644 index 2d324008e..000000000 --- a/content/docs/stacks/rpc-api/burn-ops/get-burn-operations.mdx +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: Get burn operations -description: Get all burn operations of type `op_type` successfully read at `burn_height`. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get burn operations - -Get all burn operations of type `op_type` successfully read at `burn_height`. Valid `op_type`s are `peg_in`, `peg_out_request` and `peg_out_fulfill`. - -### Path Parameters - - - -height of the burnchain (Bitcoin) - - - - - -name of the burnchain operation type - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Burn operations list | - - - - - - - - - - - - - -```terminal -$ curl -X GET "http://localhost:20443/v2/burn_ops/0/string" -``` - - - - - -```js -fetch("http://localhost:20443/v2/burn_ops/0/string", { - method: "GET" -}); -``` - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/burn-ops/index.mdx b/content/docs/stacks/rpc-api/burn-ops/index.mdx deleted file mode 100644 index 5ec824da9..000000000 --- a/content/docs/stacks/rpc-api/burn-ops/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Burn operations -index: true -toc: false -description: Get burn operations of type `op_type` successfully read at `burn_height`. ---- \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/burn-ops/meta.json b/content/docs/stacks/rpc-api/burn-ops/meta.json deleted file mode 100644 index 57bb43431..000000000 --- a/content/docs/stacks/rpc-api/burn-ops/meta.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "title": "Burn operations", - "pages": [ - "get-burn-operations" - ], - "defaultOpen": false -} - diff --git a/content/docs/stacks/rpc-api/fees/estimate.mdx b/content/docs/stacks/rpc-api/fees/estimate.mdx deleted file mode 100644 index c6fcf5699..000000000 --- a/content/docs/stacks/rpc-api/fees/estimate.mdx +++ /dev/null @@ -1,213 +0,0 @@ ---- -title: Get approximate fees for the given transaction -description: Get an estimated fee for the supplied transaction. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get approximate fees for the given transaction - -Get an estimated fee for the supplied transaction. This -estimates the execution cost of the transaction, the current -fee rate of the network, and returns estimates for fee -amounts. - -* `transaction_payload` is a hex-encoded serialization of - the TransactionPayload for the transaction. -* `estimated_len` is an optional argument that provides the - endpoint with an estimation of the final length (in bytes) - of the transaction, including any post-conditions and - signatures - -If the node cannot provide an estimate for the transaction -(e.g., if the node has never seen a contract-call for the -given contract and function) or if estimation is not -configured on this node, a 400 response is returned. -The 400 response will be a JSON error containing a `reason` -field which can be one of the following: - -* `DatabaseError` - this Stacks node has had an internal - database error while trying to estimate the costs of the - supplied transaction. -* `NoEstimateAvailable` - this Stacks node has not seen this - kind of contract-call before, and it cannot provide an - estimate yet. -* `CostEstimationDisabled` - this Stacks node does not perform - fee or cost estimation, and it cannot respond on this - endpoint. - -The 200 response contains the following data: - -* `estimated_cost` - the estimated multi-dimensional cost of - executing the Clarity VM on the provided transaction. -* `estimated_cost_scalar` - a unitless integer that the Stacks - node uses to compare how much of the block limit is consumed - by different transactions. This value incorporates the - estimated length of the transaction and the estimated - execution cost of the transaction. The range of this integer - may vary between different Stacks nodes. In order to compute - an estimate of total fee amount for the transaction, this - value is multiplied by the same Stacks node's estimated fee - rate. -* `cost_scalar_change_by_byte` - a float value that indicates how - much the `estimated_cost_scalar` value would increase for every - additional byte in the final transaction. -* `estimations` - an array of estimated fee rates and total fees to - pay in microSTX for the transaction. This array provides a range of - estimates (default: 3) that may be used. Each element of the array - contains the following fields: - * `fee_rate` - the estimated value for the current fee - rates in the network - * `fee` - the estimated value for the total fee in - microSTX that the given transaction should pay. These - values are the result of computing: - `fee_rate` x `estimated_cost_scalar`. - If the estimated fees are less than the minimum relay - fee `(1 ustx x estimated_len)`, then that minimum relay - fee will be returned here instead. - - -Note: If the final transaction's byte size is larger than -supplied to `estimated_len`, then applications should increase -this fee amount by: - - `fee_rate` x `cost_scalar_change_by_byte` x (`final_size` - `estimated_size`) - - -### Request Body (Optional) - - - - - - - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Estimated fees for the transaction | - - - - - - - - - - - - - -```terminal -$ curl -X POST "http://localhost:20443/v2/fees/transaction" \ - -d '{ - "transaction_payload": "string", - "estimated_len": 0 -}' -``` - - - - - -```js -fetch("http://localhost:20443/v2/fees/transaction", { - method: "POST" -}); -``` - - - - - - - - - -POST response for estimated fee - - - - - -```json -{ - "estimated_cost_scalar": 0, - "cost_scalar_change_by_byte": 0, - "estimated_cost": { - "read_count": 0, - "read_length": 0, - "runtime": 0, - "write_count": 0, - "write_length": 0 - }, - "estimations": [ - { - "fee_rate": 0, - "fee": 0 - } - ] -} -``` - - - - - -```ts -/** - * POST response for estimated fee - */ -export interface TransactionFeeEstimateResponse { - estimated_cost_scalar: number; - cost_scalar_change_by_byte?: number; - estimated_cost: { - read_count: number; - read_length: number; - runtime: number; - write_count: number; - write_length: number; - }; - estimations?: { - fee_rate?: number; - fee?: number; - }[]; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/rpc-api/fees/index.mdx b/content/docs/stacks/rpc-api/fees/index.mdx deleted file mode 100644 index 33c4d61fe..000000000 --- a/content/docs/stacks/rpc-api/fees/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Fees -index: true -toc: false -description: Provide estimates, rates, and approximate calculations for transaction costs. ---- \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/fees/meta.json b/content/docs/stacks/rpc-api/fees/meta.json deleted file mode 100644 index 8553c9cf0..000000000 --- a/content/docs/stacks/rpc-api/fees/meta.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "title": "Fees", - "pages": [ - "estimate", - "transfer-estimate" - ], - "defaultOpen": false -} \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/fees/transfer-estimate.mdx b/content/docs/stacks/rpc-api/fees/transfer-estimate.mdx deleted file mode 100644 index c9dc84332..000000000 --- a/content/docs/stacks/rpc-api/fees/transfer-estimate.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Get transfer fee estimate -description: Retrieves an estimated fee rate for STX transfer transactions. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get estimated fee - -Get an estimated fee rate for STX transfer transactions. This a a fee rate / byte, and is returned as a JSON integer - -| Status code | Description | -| ----------- | ----------- | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "http://localhost:20443/v2/fees/transfer" -``` - - - - - -```js -fetch("http://localhost:20443/v2/fees/transfer", { - method: "GET" -}); -``` - - - - - - - - - -GET fee estimates - - - - - -```json -"string" -``` - - - - - -```ts -/** - * GET fee estimates - */ -export type CoreNodeFeeResponse = string; -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/rpc-api/index.mdx b/content/docs/stacks/rpc-api/index.mdx deleted file mode 100644 index 36ed14903..000000000 --- a/content/docs/stacks/rpc-api/index.mdx +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Overview -description: Query the Stacks Node RPC API, interact with smart contracts, and broadcast transactions all via a familiar REST interface. ---- - -import { SecondaryCard } from '@/components/card'; - -The Stacks Node RPC API allows you to query the Stacks blockchain and interact with smart contracts. Note: this is not a Hiro-maintained service. This RPC API is generated by every Stacks node and allows you to self-host your own node and API. This is a minimalist configuration. For a richer data set and an API that is easier to use, try [Hiro's Stacks Blockchain API](/stacks/api). - -## Popular endpoints - - - - - - - - -## Related tools - -- **[Stacks Blockchain API](/stacks/api)**: Fetch richer data from Hiro's Stacks Blockchain API. -- **[Token Metadata API](/stacks/token-metadata-api)**: Fetch fungible and non-fungible token data on the Stacks blockchain. -- **[Stacks Explorer](https://explorer.hiro.so)**: Verify activity on the Stacks blockchain with an easy-to-use front end. - -
- - -Reach out to us on the #api channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET. - - - diff --git a/content/docs/stacks/rpc-api/info/core-api.mdx b/content/docs/stacks/rpc-api/info/core-api.mdx deleted file mode 100644 index 6bd346d8d..000000000 --- a/content/docs/stacks/rpc-api/info/core-api.mdx +++ /dev/null @@ -1,171 +0,0 @@ ---- -title: Get core API info -description: Retrieves information about the Core API, including the server version. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get Core API info - -Get Core API information - -| Status code | Description | -| ----------- | ----------- | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "http://localhost:20443/v2/info" -``` - - - - - -```js -fetch("http://localhost:20443/v2/info", { - method: "GET" -}); -``` - - - - - - - - - -GET request that core node information - - - - - -```json -{ - "peer_version": 0, - "pox_consensus": "string", - "burn_block_height": 0, - "stable_pox_consensus": "string", - "stable_burn_block_height": 0, - "server_version": "string", - "network_id": 0, - "parent_network_id": 0, - "stacks_tip_height": 0, - "stacks_tip": "string", - "stacks_tip_consensus_hash": "string", - "unanchored_tip": "string", - "exit_at_block_height": 0 -} -``` - - - - - -```ts -/** - * GET request that core node information - */ -export interface CoreNodeInfoResponse { - /** - * identifies the version number for the networking communication, this should not change while a node is running, and will only change if there's an upgrade - */ - peer_version: number; - /** - * is a hash used to identify the burnchain view for a node. it incorporates bitcoin chain information and PoX information. nodes that disagree on this value will appear to each other as forks. this value will change after every block - */ - pox_consensus: string; - /** - * latest bitcoin chain height - */ - burn_block_height: number; - /** - * same as burn_consensus, but evaluated at stable_burn_block_height - */ - stable_pox_consensus: string; - /** - * leftover from stacks 1.0, basically always burn_block_height - 1 - */ - stable_burn_block_height: number; - /** - * is a version descriptor - */ - server_version: string; - /** - * is similar to peer_version and will be used to differentiate between different testnets. this value will be different between mainnet and testnet. once launched, this value will not change - */ - network_id: number; - /** - * same as network_id, but for bitcoin - */ - parent_network_id: number; - /** - * the latest Stacks chain height. Stacks forks can occur independent of the Bitcoin chain, that height doesn't increase 1-to-1 with the Bitcoin height - */ - stacks_tip_height: number; - /** - * the best known block hash for the Stack chain (not including any pending microblocks) - */ - stacks_tip: string; - /** - * the burn chain (i.e., bitcoin) consensus hash at the time that stacks_tip was mined - */ - stacks_tip_consensus_hash: string; - /** - * the latest microblock hash if any microblocks were processed. if no microblock has been processed for the current block, a 000.., hex array is returned - */ - unanchored_tip: string; - /** - * the block height at which the testnet network will be reset. not applicable for mainnet - */ - exit_at_block_height: number; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/rpc-api/info/index.mdx b/content/docs/stacks/rpc-api/info/index.mdx deleted file mode 100644 index 4106173a5..000000000 --- a/content/docs/stacks/rpc-api/info/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Info -index: true -toc: false -description: Retrieves information about the Core API and the Stacks network. ---- diff --git a/content/docs/stacks/rpc-api/info/meta.json b/content/docs/stacks/rpc-api/info/meta.json deleted file mode 100644 index d99dd0e19..000000000 --- a/content/docs/stacks/rpc-api/info/meta.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "title": "Info", - "pages": [ - "core-api" - ], - "defaultOpen": false -} \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/meta.json b/content/docs/stacks/rpc-api/meta.json deleted file mode 100644 index 6f86ddc05..000000000 --- a/content/docs/stacks/rpc-api/meta.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "title": "Stacks Node RPC", - "root": true, - "pages": [ - "---Stacks Node RPC---", - "index", - "---API Reference---", - "accounts", - "transactions", - "blocks", - "pox", - "fees", - "burn-ops", - "smart-contracts", - "names", - "v3", - "info" - ] -} diff --git a/content/docs/stacks/rpc-api/names/index.mdx b/content/docs/stacks/rpc-api/names/index.mdx deleted file mode 100644 index b1e2ce35f..000000000 --- a/content/docs/stacks/rpc-api/names/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Names -index: true -toc: false -description: Manages and retrieve information on blockchain namespaces, names, and related details. ---- \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/names/meta.json b/content/docs/stacks/rpc-api/names/meta.json deleted file mode 100644 index 7bed3ab7c..000000000 --- a/content/docs/stacks/rpc-api/names/meta.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "title": "Names", - "pages": [ - "namespace-price", - "name-price" - ], - "defaultOpen": false -} diff --git a/content/docs/stacks/rpc-api/names/name-price.mdx b/content/docs/stacks/rpc-api/names/name-price.mdx deleted file mode 100644 index 43cbf5612..000000000 --- a/content/docs/stacks/rpc-api/names/name-price.mdx +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Get name price -description: Retrieves the price of a name. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get name price - -Retrieves the price of a name. The `amount` given will be in the smallest possible units of the currency. -### Path Parameters - - - -the name to query price information for - -Example: `"muneeb.id"` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/v2/prices/names/muneeb.id" -``` - - - - - -```js -fetch("https://api.hiro.so/v2/prices/names/muneeb.id", { - method: "GET" -}); -``` - - - - - - - - - -Fetch price for name. - - - - - -```json -{ - "units": "string", - "amount": "string" -} -``` - - - - - -```ts -/** - * Fetch price for name. - */ -export interface BnsGetNamePriceResponse { - units: string; - amount: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/rpc-api/names/namespace-price.mdx b/content/docs/stacks/rpc-api/names/namespace-price.mdx deleted file mode 100644 index 9e6311ec3..000000000 --- a/content/docs/stacks/rpc-api/names/namespace-price.mdx +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Get namespace price -description: Retrieves the price of a namespace. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get Namespace Price - -Retrieves the price of a namespace. The `amount` given will be in the smallest possible units of the currency. -### Path Parameters - - - -the namespace to fetch price for - -Example: `"id"` - - - -| Status code | Description | -| :------ | :------ | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "https://api.hiro.so/v2/prices/namespaces/id" -``` - - - - - -```js -fetch("https://api.hiro.so/v2/prices/namespaces/id", { - method: "GET" -}); -``` - - - - - - - - - -Fetch price for namespace. - - - - - -```json -{ - "units": "string", - "amount": "string" -} -``` - - - - - -```ts -/** - * Fetch price for namespace. - */ -export interface BnsGetNamespacePriceResponse { - units: string; - amount: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/rpc-api/pox/index.mdx b/content/docs/stacks/rpc-api/pox/index.mdx deleted file mode 100644 index 58aff34b7..000000000 --- a/content/docs/stacks/rpc-api/pox/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Proof of Transfer -index: true -toc: false -description: Retrieves Proof-of-Transfer (PoX) information. ---- diff --git a/content/docs/stacks/rpc-api/pox/meta.json b/content/docs/stacks/rpc-api/pox/meta.json deleted file mode 100644 index c0d853cdf..000000000 --- a/content/docs/stacks/rpc-api/pox/meta.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "title": "Proof of Transfer", - "pages": [ - "pox-details", - "stacker-set" - ], - "defaultOpen": false -} \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/pox/pox-details.mdx b/content/docs/stacks/rpc-api/pox/pox-details.mdx deleted file mode 100644 index 0b48d5c3e..000000000 --- a/content/docs/stacks/rpc-api/pox/pox-details.mdx +++ /dev/null @@ -1,282 +0,0 @@ ---- -title: Get Proof-of-Transfer details -description: Retrieves Proof-of-Transfer (PoX) information. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get PoX details - -Get Proof of Transfer (PoX) information. Can be used for Stacking. - -### Query Parameters - - - -The Stacks chain tip to query from. If tip == latest, the query will be run from the latest known tip (includes unconfirmed state). - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "http://localhost:20443/v2/pox?tip=string" -``` - - - - - -```js -fetch("http://localhost:20443/v2/pox?tip=string", { - method: "GET" -}); -``` - - - - - - - - - -Get Proof of Transfer (PoX) information - - - - - -```json -{ - "contract_id": "string", - "first_burnchain_block_height": 0, - "current_burnchain_block_height": 0, - "pox_activation_threshold_ustx": 0, - "rejection_fraction": 0, - "reward_phase_block_length": 0, - "prepare_phase_block_length": 0, - "reward_slots": 0, - "total_liquid_supply_ustx": 0, - "reward_cycle_length": 0, - "current_cycle": { - "id": 0, - "min_threshold_ustx": 0, - "stacked_ustx": 0, - "is_pox_active": true - }, - "next_cycle": { - "id": 0, - "min_threshold_ustx": 0, - "stacked_ustx": 0, - "min_increment_ustx": 0, - "prepare_phase_start_block_height": 0, - "blocks_until_prepare_phase": 0, - "reward_phase_start_block_height": 0, - "blocks_until_reward_phase": 0, - "ustx_until_pox_rejection": 0 - }, - "reward_cycle_id": 0, - "min_amount_ustx": 0, - "prepare_cycle_length": 0, - "rejection_votes_left_required": 0, - "contract_versions": [ - { - "contract_id": "string", - "activation_burnchain_block_height": 0, - "first_reward_cycle_id": 0 - } - ] -} -``` - - - - - -```ts -/** - * Get Proof of Transfer (PoX) information - */ -export interface CoreNodePoxResponse { - /** - * The contract identifier for the PoX contract - */ - contract_id: string; - /** - * The first burn block evaluated in this Stacks chain - */ - first_burnchain_block_height: number; - /** - * The latest Bitcoin chain block height - */ - current_burnchain_block_height: number; - /** - * The threshold of stacking participation that must be reached for PoX to activate in any cycle - */ - pox_activation_threshold_ustx: number; - /** - * The fraction of liquid STX that must vote to reject PoX in order to prevent the next reward cycle from activating. - */ - rejection_fraction: number; - /** - * The length in burn blocks of the reward phase - */ - reward_phase_block_length: number; - /** - * The length in burn blocks of the prepare phase - */ - prepare_phase_block_length: number; - /** - * The number of reward slots in a reward cycle - */ - reward_slots: number; - /** - * The current total amount of liquid microstacks. - */ - total_liquid_supply_ustx: number; - /** - * The length in burn blocks of a whole PoX cycle (reward phase and prepare phase) - */ - reward_cycle_length: number; - current_cycle: { - /** - * The reward cycle number - */ - id: number; - /** - * The threshold amount for obtaining a slot in this reward cycle. - */ - min_threshold_ustx: number; - /** - * The total amount of stacked microstacks in this reward cycle. - */ - stacked_ustx: number; - /** - * Whether or not PoX is active during this reward cycle. - */ - is_pox_active: boolean; - }; - next_cycle: { - /** - * The reward cycle number - */ - id: number; - /** - * The threshold amount for obtaining a slot in this reward cycle. - */ - min_threshold_ustx: number; - /** - * The total amount of stacked microstacks in this reward cycle. - */ - stacked_ustx: number; - /** - * The minimum amount that can be used to submit a `stack-stx` call. - */ - min_increment_ustx: number; - /** - * The burn block height when the prepare phase for this cycle begins. Any eligible stacks must be stacked before this block. - */ - prepare_phase_start_block_height: number; - /** - * The number of burn blocks until the prepare phase for this cycle starts. If the prepare phase for this cycle already started, this value will be negative. - */ - blocks_until_prepare_phase: number; - /** - * The burn block height when the reward phase for this cycle begins. Any eligible stacks must be stacked before this block. - */ - reward_phase_start_block_height: number; - /** - * The number of burn blocks until this reward phase starts. - */ - blocks_until_reward_phase: number; - /** - * The remaining amount of liquid STX that must vote to reject the next reward cycle to prevent the next reward cycle from activating. - */ - ustx_until_pox_rejection: number; - }; - /** - * @deprecated - * The active reward cycle number - */ - reward_cycle_id: number; - /** - * @deprecated - */ - min_amount_ustx: number; - /** - * @deprecated - */ - prepare_cycle_length: number; - /** - * @deprecated - */ - rejection_votes_left_required: number; - /** - * Versions of each PoX - */ - contract_versions: { - /** - * The contract identifier for the PoX contract - */ - contract_id: string; - /** - * The burn block height at which this version of PoX is activated - */ - activation_burnchain_block_height: number; - /** - * The first reward cycle number that uses this version of PoX - */ - first_reward_cycle_id: number; - }[]; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/rpc-api/pox/stacker-set.mdx b/content/docs/stacks/rpc-api/pox/stacker-set.mdx deleted file mode 100644 index f519f1771..000000000 --- a/content/docs/stacks/rpc-api/pox/stacker-set.mdx +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Get stacker and signer set information -description: Retrieves stacker and signer set information for a given cycle. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Fetch the stacker and signer set information for a given cycle. - -Used to get stacker and signer set information for a given cycle. - -This will only return information for cycles started in Epoch-2.5 where PoX-4 was active and subsequent cycles. - - -### Path Parameters - - - -reward cycle number - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Information for the given reward cycle | -| `400` | Could not fetch the given reward set | - - - - - - - - - - - - - -```terminal -$ curl -X GET "http://localhost:20443/v2/stacker_set/0" -``` - - - - - -```js -fetch("http://localhost:20443/v2/stacker_set/0", { - method: "GET" -}); -``` - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/smart-contracts/constants.mdx b/content/docs/stacks/rpc-api/smart-contracts/constants.mdx deleted file mode 100644 index 372d571fe..000000000 --- a/content/docs/stacks/rpc-api/smart-contracts/constants.mdx +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Get constant value -description: Get the value of a constant inside a contract. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get the value of a constant inside a contract - -Attempt to fetch the value of a constant inside a contract. The contract is identified with [Stacks Address] and [Contract Name] in the URL path. The constant is identified with [Constant Name]. - -In the response, `data` is the hex serialization of the constant value. - -### Path Parameters - - - -Stacks address - - - - - -Contract name - - - - - -Constant name - - - -### Query Parameters - - - -The Stacks chain tip to query from. If tip == latest, the query will be run from the latest known tip (includes unconfirmed state). - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Success | -| `400` | Failed to retrieve constant value from contract | - - - - - - - - - - - - - -```terminal -$ curl -X POST "http://localhost:20443/v2/constant_val/string/string/string?tip=string" -``` - - - - - -```js -fetch("http://localhost:20443/v2/constant_val/string/string/string?tip=string", { - method: "POST" -}); -``` - - - - - - - - - -Response of get constant val request - - - - - -```json -{ - "data": "string" -} -``` - - - - - -```ts -/** - * Response of get constant val request - */ -export interface ConstantValResponse { - /** - * Hex-encoded string of clarity value. - */ - data: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/rpc-api/smart-contracts/index.mdx b/content/docs/stacks/rpc-api/smart-contracts/index.mdx deleted file mode 100644 index 32e39b1ac..000000000 --- a/content/docs/stacks/rpc-api/smart-contracts/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Smart contracts -index: true -toc: false -description: Provide information and facilitate interactions with smart contracts. ---- diff --git a/content/docs/stacks/rpc-api/smart-contracts/interface.mdx b/content/docs/stacks/rpc-api/smart-contracts/interface.mdx deleted file mode 100644 index 68155e077..000000000 --- a/content/docs/stacks/rpc-api/smart-contracts/interface.mdx +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: Get contract interface -description: Retrieves a list of functions, variables, maps, fungible tokens and non-fungible tokens for a given smart contract. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get contract interface - -Get contract interface using a `contract_address` and `contract name` - -| Status code | Description | -| ----------- | ----------- | -| `200` | Contract interface | - - - - - - - - - - - - - -```terminal -$ curl -X GET "http://localhost:20443/v2/contracts/interface/%7Bcontract_address%7D/%7Bcontract_name%7D" -``` - - - - - -```js -fetch("http://localhost:20443/v2/contracts/interface/%7Bcontract_address%7D/%7Bcontract_name%7D", { - method: "GET" -}); -``` - - - - - - - - - -GET request to get contract interface - - - - - -```json -{ - "functions": [ - {} - ], - "variables": [ - {} - ], - "maps": [ - {} - ], - "fungible_tokens": [ - {} - ], - "non_fungible_tokens": [ - {} - ] -} -``` - - - - - -```ts -/** - * GET request to get contract interface - */ -export interface ContractInterfaceResponse { - /** - * List of defined methods - */ - functions: {}[]; - /** - * List of defined variables - */ - variables: {}[]; - /** - * List of defined data-maps - */ - maps: {}[]; - /** - * List of fungible tokens in the contract - */ - fungible_tokens: {}[]; - /** - * List of non-fungible tokens in the contract - */ - non_fungible_tokens: {}[]; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/rpc-api/smart-contracts/map-entry.mdx b/content/docs/stacks/rpc-api/smart-contracts/map-entry.mdx deleted file mode 100644 index 52a35dc6b..000000000 --- a/content/docs/stacks/rpc-api/smart-contracts/map-entry.mdx +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: Get contract map entry -description: Retrieves a specific entry from a contract data map. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get specific data-map inside a contract - -Attempt to fetch data from a contract data map. The contract is identified with [Stacks Address] and [Contract Name] in the URL path. The map is identified with [Map Name]. - -The key to lookup in the map is supplied via the POST body. This should be supplied as the hex string serialization of the key (which should be a Clarity value). Note, this is a JSON string atom. - -In the response, `data` is the hex serialization of the map response. Note that map responses are Clarity option types, for non-existent values, this is a serialized none, and for all other responses, it is a serialized (some ...) object. - - -### Request Body - -Hex string serialization of the lookup key (which should be a Clarity value) - - - - - -### Path Parameters - - - -Stacks address - - - - - -Contract name - - - - - -Map name - - - -### Query Parameters - - - -Returns object without the proof field when set to 0 - - - - - -The Stacks chain tip to query from. If tip == latest, the query will be run from the latest known tip (includes unconfirmed state). - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Success | -| `400` | Failed loading data map | - - - - - - - - - - - - - -```terminal -$ curl -X POST "http://localhost:20443/v2/map_entry/string/string/string?proof=0&tip=string" \ - -d 'string' -``` - - - - - -```js -fetch("http://localhost:20443/v2/map_entry/string/string/string?proof=0&tip=string", { - method: "POST" -}); -``` - - - - - - - - - -Response of get data map entry request - - - - - -```json -{ - "data": "string", - "proof": "string" -} -``` - - - - - -```ts -/** - * Response of get data map entry request - */ -export interface MapEntryResponse { - /** - * Hex-encoded string of clarity value. It is always an optional tuple. - */ - data: string; - /** - * Hex-encoded string of the MARF proof for the data - */ - proof?: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/rpc-api/smart-contracts/meta.json b/content/docs/stacks/rpc-api/smart-contracts/meta.json deleted file mode 100644 index 9e0e7f933..000000000 --- a/content/docs/stacks/rpc-api/smart-contracts/meta.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "title": "Smart Contracts", - "pages": ["..."], - "defaultOpen": false -} - diff --git a/content/docs/stacks/rpc-api/smart-contracts/read-only.mdx b/content/docs/stacks/rpc-api/smart-contracts/read-only.mdx deleted file mode 100644 index 70de2e41b..000000000 --- a/content/docs/stacks/rpc-api/smart-contracts/read-only.mdx +++ /dev/null @@ -1,166 +0,0 @@ ---- -title: Call read-only function -description: Calls a read-only public function on a given smart contract. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Call read-only function - -Call a read-only public function on a given smart contract. - -The smart contract and function are specified using the URL path. The arguments and the simulated tx-sender are supplied via the POST body in the following JSON format: - - -### Request Body - -map of arguments and the simulated tx-sender where sender is either a Contract identifier or a normal Stacks address, and arguments is an array of hex serialized Clarity values. - - - -The simulated tx-sender - - - -"} required={true} deprecated={undefined}> - -An array of hex serialized Clarity values - - - -### Path Parameters - - - -Stacks address - - - - - -Contract name - - - - - -Function name - - - -### Query Parameters - - - -The Stacks chain tip to query from. If tip == latest, the query will be run from the latest known tip (includes unconfirmed state). - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X POST "http://localhost:20443/v2/contracts/call-read/string/string/string?tip=string" \ - -d '{ - "sender": "SP31DA6FTSJX2WGTZ69SFY11BH51NZMB0ZW97B5P0.get-info", - "arguments": [ - "0x0011...", - "0x00231..." - ] -}' -``` - - - - - -```js -fetch("http://localhost:20443/v2/contracts/call-read/string/string/string?tip=string", { - method: "POST" -}); -``` - - - - - - - - - -GET request to get contract source - - - - - -```json -{ - "okay": true, - "result": "string", - "cause": "string" -} -``` - - - - - -```ts -/** - * GET request to get contract source - */ -export interface ReadOnlyFunctionSuccessResponse { - okay: boolean; - result?: string; - cause?: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/rpc-api/smart-contracts/source.mdx b/content/docs/stacks/rpc-api/smart-contracts/source.mdx deleted file mode 100644 index 5b2906aaa..000000000 --- a/content/docs/stacks/rpc-api/smart-contracts/source.mdx +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Get contract source -description: Retrieves the Clarity source code of a given contract, along with the block height it was published in, and the MARF proof for the data. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get contract source - -Returns the Clarity source code of a given contract, along with the block height it was published in, and the MARF proof for the data - -| Status code | Description | -| ----------- | ----------- | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "http://localhost:20443/v2/contracts/source/%7Bcontract_address%7D/%7Bcontract_name%7D" -``` - - - - - -```js -fetch("http://localhost:20443/v2/contracts/source/%7Bcontract_address%7D/%7Bcontract_name%7D", { - method: "GET" -}); -``` - - - - - - - - - -GET request to get contract source - - - - - -```json -{ - "source": "string", - "publish_height": 0, - "proof": "string" -} -``` - - - - - -```ts -/** - * GET request to get contract source - */ -export interface ContractSourceResponse { - source: string; - publish_height: number; - proof: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/rpc-api/smart-contracts/traits.mdx b/content/docs/stacks/rpc-api/smart-contracts/traits.mdx deleted file mode 100644 index 4d8b9dd09..000000000 --- a/content/docs/stacks/rpc-api/smart-contracts/traits.mdx +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: Get trait implementation details -description: Determine whether or not a specified trait is implemented (either explicitly or implicitly) within a given contract. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get trait implementation details - -Determine whether or not a specified trait is implemented (either explicitly or implicitly) within a given contract. - -| Status code | Description | -| ----------- | ----------- | -| `200` | Success | - - - - - - - - - - - - - -```terminal -$ curl -X GET "http://localhost:20443/v2/traits/%7Bcontract_address%7D/%7Bcontract_name%7D/%7Btrait_contract_address%7D/%7Btrait_contract_name%7D/%7Btrait_name%7D" -``` - - - - - -```js -fetch("http://localhost:20443/v2/traits/%7Bcontract_address%7D/%7Bcontract_name%7D/%7Btrait_contract_address%7D/%7Btrait_contract_name%7D/%7Btrait_name%7D", { - method: "GET" -}); -``` - - - - - - - - - -GET request to get trait implementation information - - - - - -```json -{ - "is_implemented": true -} -``` - - - - - -```ts -/** - * GET request to get trait implementation information - */ -export interface IsTraitImplementedSuccessResponse { - is_implemented: boolean; -} -``` - - - - - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/smart-contracts/variables.mdx b/content/docs/stacks/rpc-api/smart-contracts/variables.mdx deleted file mode 100644 index 5ce13db30..000000000 --- a/content/docs/stacks/rpc-api/smart-contracts/variables.mdx +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Get data variable value -description: Get the value of a data variable inside a contract. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Get the value of a data variable inside a contract - -Attempt to vetch a data var from a contract. The contract is identified with [Stacks Address] and -[Contract Name] in the URL path. The variable is identified with [Var Name]. - -In the response, `data` is the hex serialization of the data variable value. - -### Path Parameters - - - -Stacks address - - - - - -Contract name - - - - - -Data variable name - - - -### Query Parameters - - - -When supplied `0`, will return the JSON object _without_ the `proof` field. - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Success | -| `400` | Failed to retrieve data variable value from contract | - - - - - - - - - - - - - -```terminal -$ curl -X GET "http://localhost:20443/v2/data_var/string/string/string" -``` - - - - - -```js -fetch("http://localhost:20443/v2/constant_val/string/string/string", { - method: "POST" -}); -``` - - - - - - - - - -Response of get constant val request - - - - - -```json -{ - "data": "string", - "proof": "string", -} -``` - - - - - -```ts -/** - * Response of get constant val request - */ -export interface ConstantValResponse { - /** - * Hex-encoded string of clarity value. - */ - data: string; - proof: string; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/rpc-api/transactions/broadcast-transaction.mdx b/content/docs/stacks/rpc-api/transactions/broadcast-transaction.mdx deleted file mode 100644 index 09a02725f..000000000 --- a/content/docs/stacks/rpc-api/transactions/broadcast-transaction.mdx +++ /dev/null @@ -1,160 +0,0 @@ ---- -title: Broadcast transaction -description: Broadcasts raw transactions on the network. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Broadcast raw transaction - -Broadcast raw transactions on the network. You can use the [@stacks/transactions](https://github.com/blockstack/stacks.js) project to generate a raw transaction payload. - -### Request Body (Optional) - - - -Format: `"binary"` - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Transaction id of successful post of a raw tx to the node's mempool | -| `400` | Rejections result in a 400 error | - - - - - - - - - - - - - -```terminal -$ curl -X POST "http://localhost:20443/v2/transactions" \ - -d 'string' -``` - - - - - -```js -fetch("http://localhost:20443/v2/transactions", { - method: "POST" -}); -``` - - - - - - - - - - - - - -```json -"e161978626f216b2141b156ade10501207ae535fa365a13ef5d7a7c9310a09f2" -``` - - - - - -```ts -export type Response = string; -``` - - - - - - - - - -GET request that returns transactions - - - - - -```json -{ - "error": "string", - "reason": "string", - "reason_data": {}, - "txid": "string" -} -``` - - - - - -```ts -/** - * GET request that returns transactions - */ -export interface PostCoreNodeTransactionsError { - /** - * The error - */ - error: string; - /** - * The reason for the error - */ - reason: string; - /** - * More details about the reason - */ - reason_data: {}; - /** - * The relevant transaction id - */ - txid: string; -} -``` - - - - - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/transactions/index.mdx b/content/docs/stacks/rpc-api/transactions/index.mdx deleted file mode 100644 index c6098a6e7..000000000 --- a/content/docs/stacks/rpc-api/transactions/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Transactions -index: true -toc: false -description: Manage, retrieve, and broadcast transaction data on the blockchain. ---- \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/transactions/meta.json b/content/docs/stacks/rpc-api/transactions/meta.json deleted file mode 100644 index c927411b9..000000000 --- a/content/docs/stacks/rpc-api/transactions/meta.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "title": "Transactions", - "pages": [ - "broadcast-transaction" - ], - "defaultOpen": false -} - diff --git a/content/docs/stacks/rpc-api/v3/index.mdx b/content/docs/stacks/rpc-api/v3/index.mdx deleted file mode 100644 index f6c28b331..000000000 --- a/content/docs/stacks/rpc-api/v3/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: v3 -index: true -toc: false -description: Version 3 of the RPC API. ---- \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/v3/meta.json b/content/docs/stacks/rpc-api/v3/meta.json deleted file mode 100644 index 22b93adc8..000000000 --- a/content/docs/stacks/rpc-api/v3/meta.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "title": "v3", - "pages": [ - "nakamoto-block", - "tenure-metadata", - "tenure-blocks" - ], - "defaultOpen": false -} \ No newline at end of file diff --git a/content/docs/stacks/rpc-api/v3/nakamoto-block.mdx b/content/docs/stacks/rpc-api/v3/nakamoto-block.mdx deleted file mode 100644 index ac195c5a9..000000000 --- a/content/docs/stacks/rpc-api/v3/nakamoto-block.mdx +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: Get Nakamoto block -description: Fetch a Nakamoto block by its index block hash. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Fetch a Nakamoto block - -Fetch a Nakamoto block by its index block hash. - -### Path Parameters - - - -The block's ID hash - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | The raw SIP-003-encoded block will be returned. | -| `404` | The block could not be found | - - - - - - - - - - - - - -```terminal -$ curl -X GET "http://localhost:20443/v3/blocks/string" -``` - - - - - -```js -fetch("http://localhost:20443/v3/blocks/string", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -"string" -``` - - - - - -```ts -export type Response = string; -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/rpc-api/v3/tenure-blocks.mdx b/content/docs/stacks/rpc-api/v3/tenure-blocks.mdx deleted file mode 100644 index edfeb621f..000000000 --- a/content/docs/stacks/rpc-api/v3/tenure-blocks.mdx +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Get Nakamoto tenure blocks -description: Fetch a sequence of Nakamoto blocks in a tenure. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Fetch a sequence of Nakamoto blocks in a tenure - -Fetch a sequence of Nakamoto blocks in a tenure. The blocks will be served in order from highest to lowest. The blocks will be encoded in their SIP-003 wire format, and concatenated together. - -| Status code | Description | -| ----------- | ----------- | -| `200` | SIP-003-encoded Nakamoto blocks, concatenated together | - - - - - - - - - - - - - -```terminal -$ curl -X GET "http://localhost:20443/v3/tenures/%7Bblock_id%7D" -``` - - - - - -```js -fetch("http://localhost:20443/v3/tenures/%7Bblock_id%7D", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -"string" -``` - - - - - -```ts -export type Response = string; -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/rpc-api/v3/tenure-metadata.mdx b/content/docs/stacks/rpc-api/v3/tenure-metadata.mdx deleted file mode 100644 index 5eaf9d430..000000000 --- a/content/docs/stacks/rpc-api/v3/tenure-metadata.mdx +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: Get Nakamoto tenure metadata -description: Fetch metadata about the ongoing Nakamoto tenure. -toc: false ---- - -import { - API, - APIExample, - APIInfo, - APIPlayground, - ExampleResponse, - Property, - Request, - Requests, - Response, - Responses, - ResponseTypes, - Root, - TypeScriptResponse -} from 'fumadocs-openapi/ui'; - - - - - - - -## Fetch metadata about the ongoing Nakamoto tenure - -Fetch metadata about the ongoing Nakamoto tenure. This information is sufficient to obtain and authenticate the highest complete tenure, as well as obtain new tenure blocks. - -| Status code | Description | -| ----------- | ----------- | -| `200` | Metadata about the ongoing tenure | - - - - - - - - - - - - - -```terminal -$ curl -X GET "http://localhost:20443/v3/tenures/info" -``` - - - - - -```js -fetch("http://localhost:20443/v3/tenures/info", { - method: "GET" -}); -``` - - - - - - - - - - diff --git a/content/docs/stacks/signer-metrics-api/block-proposals/index.mdx b/content/docs/stacks/signer-metrics-api/block-proposals/index.mdx deleted file mode 100644 index 05677c64e..000000000 --- a/content/docs/stacks/signer-metrics-api/block-proposals/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Block proposals -description: Get information about block proposals. -toc: false -index: true ---- \ No newline at end of file diff --git a/content/docs/stacks/signer-metrics-api/block-proposals/signer-information-for-a-block.mdx b/content/docs/stacks/signer-metrics-api/block-proposals/signer-information-for-a-block.mdx deleted file mode 100644 index b41ef1aa2..000000000 --- a/content/docs/stacks/signer-metrics-api/block-proposals/signer-information-for-a-block.mdx +++ /dev/null @@ -1,254 +0,0 @@ ---- -title: Signer information for a block -description: Get signer information for a specific block. -toc: false ---- - -import { Root, API, APIInfo, APIExample, Responses, Response, ResponseTypes, ExampleResponse, TypeScriptResponse, Property, ObjectCollapsible, Requests, Request, APIPlayground } from "fumadocs-openapi/ui"; - - - - - - - -## Signer information for a block proposal - -Signer information for a block proposal - -### Query Parameters - - - -Number of results to return - -Default: `25` - -Minimum: `1` - -Maximum: `50` - - - - - -Number of results to skip - -Default: `0` - - - -### Path Parameters - - - -Block hash - -Pattern: `"^(0x)?[a-fA-F0-9]{64}$"` - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/signer-metrics/v1/block_proposals/string?limit=25&offset=0" -``` - - - - - -```js -fetch("https://api.hiro.so/signer-metrics/v1/block_proposals/string?limit=25&offset=0", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "received_at": "string", - "block_height": 0, - "block_hash": "string", - "index_block_hash": "string", - "burn_block_height": 0, - "block_time": 0, - "cycle_number": 0, - "status": "pending", - "push_time_ms": {}, - "total_signer_count": 0, - "total_signer_weight": 0, - "total_signer_stacked_amount": "string", - "accepted_count": 0, - "rejected_count": 0, - "missing_count": 0, - "accepted_weight": 0, - "rejected_weight": 0, - "missing_weight": 0, - "signer_data": [ - { - "signer_key": "string", - "slot_index": 0, - "response": "accepted", - "weight": 0, - "weight_percentage": 0, - "stacked_amount": "string", - "version": "string", - "received_at": "string", - "response_time_ms": 0, - "reason_string": "string", - "reason_code": "string", - "reject_code": "string" - } - ] -} -``` - - - - - -```ts -export interface Response { - /** - * ISO timestamp of when this block proposal was received - */ - received_at: string; - block_height: number; - block_hash: string; - index_block_hash: string; - burn_block_height: number; - /** - * Unix timestamp in seconds of when the block was mined - */ - block_time: number; - cycle_number: number; - /** - * Status of the block proposal - */ - status: "pending" | "accepted" | "rejected"; - /** - * Time duration (in milliseconds) taken between when the block was proposed and when it was pushed - */ - push_time_ms: null | number; - /** - * Total number of signers expected for this proposal - */ - total_signer_count: number; - /** - * Total voting weight of signers expected for this proposal - */ - total_signer_weight: number; - /** - * Total STX stacked of signers expected for this proposal - */ - total_signer_stacked_amount: string; - /** - * Number of signers that submitted an approval for this proposal - */ - accepted_count: number; - /** - * Number of signers that submitted a rejection for this proposal - */ - rejected_count: number; - /** - * Number of signers that failed to submit any response/vote for this proposal - */ - missing_count: number; - /** - * Sum of voting weight of signers who approved the proposal - */ - accepted_weight: number; - /** - * Sum of voting weight of signers who rejected the proposal - */ - rejected_weight: number; - /** - * Sum of voting weight of missing signers - */ - missing_weight: number; - signer_data: { - signer_key: string; - /** - * Index of the signer in the stacker set - */ - slot_index: number; - response: "accepted" | "rejected" | "missing"; - /** - * Voting weight of this signer (based on slots allocated which is proportional to stacked amount) - */ - weight: number; - /** - * Voting weight percent (weight / total_weight) - */ - weight_percentage: number; - /** - * Total STX stacked associated with this signer (string quoted integer) - */ - stacked_amount: string; - /** - * The signer binary version reported by this signer for this proposal response (null if response missing) - */ - version: string | null; - /** - * ISO timestamp of when this response was received (null if response missing - */ - received_at: string | null; - /** - * Time duration (in milliseconds) taken to submit this response (tracked best effort, null if response missing) - */ - response_time_ms: number | null; - /** - * (For rejection responses) reason string for rejection - */ - reason_string: string | null; - /** - * (For rejection responses) reason code for rejection - */ - reason_code: string | null; - /** - * (For rejection responses) reject code for rejection - */ - reject_code: string | null; - }[]; -} -``` - - - - - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/signer-metrics-api/block-proposals/signer-information-for-most-recent-block-proposals.mdx b/content/docs/stacks/signer-metrics-api/block-proposals/signer-information-for-most-recent-block-proposals.mdx deleted file mode 100644 index c9f715928..000000000 --- a/content/docs/stacks/signer-metrics-api/block-proposals/signer-information-for-most-recent-block-proposals.mdx +++ /dev/null @@ -1,254 +0,0 @@ ---- -title: Signer information for most recent block proposals -description: Get signer information for most recent block proposals. -toc: false ---- - -import { Root, API, APIInfo, APIExample, Responses, Response, ResponseTypes, ExampleResponse, TypeScriptResponse, Property, ObjectCollapsible, Requests, Request, APIPlayground } from "fumadocs-openapi/ui"; - - - - - - - -## Signer information for most recent block proposals - -Signer information for most recent block proposals - -### Query Parameters - - - -Number of results to return - -Default: `25` - -Minimum: `1` - -Maximum: `50` - - - - - -Number of results to skip - -Default: `0` - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/signer-metrics/v1/block_proposals?limit=25&offset=0" -``` - - - - - -```js -fetch("https://api.hiro.so/signer-metrics/v1/block_proposals?limit=25&offset=0", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "limit": 0, - "offset": 0, - "results": [ - { - "received_at": "string", - "block_height": 0, - "block_hash": "string", - "index_block_hash": "string", - "burn_block_height": 0, - "block_time": 0, - "cycle_number": 0, - "status": "pending", - "push_time_ms": {}, - "total_signer_count": 0, - "total_signer_weight": 0, - "total_signer_stacked_amount": "string", - "accepted_count": 0, - "rejected_count": 0, - "missing_count": 0, - "accepted_weight": 0, - "rejected_weight": 0, - "missing_weight": 0, - "signer_data": [ - { - "signer_key": "string", - "slot_index": 0, - "response": "accepted", - "weight": 0, - "weight_percentage": 0, - "stacked_amount": "string", - "version": "string", - "received_at": "string", - "response_time_ms": 0, - "reason_string": "string", - "reason_code": "string", - "reject_code": "string" - } - ] - } - ] -} -``` - - - - - -```ts -export interface Response { - limit: number; - offset: number; - results: { - /** - * ISO timestamp of when this block proposal was received - */ - received_at: string; - block_height: number; - block_hash: string; - index_block_hash: string; - burn_block_height: number; - /** - * Unix timestamp in seconds of when the block was mined - */ - block_time: number; - cycle_number: number; - /** - * Status of the block proposal - */ - status: "pending" | "accepted" | "rejected"; - /** - * Time duration (in milliseconds) taken between when the block was proposed and when it was pushed - */ - push_time_ms: null | number; - /** - * Total number of signers expected for this proposal - */ - total_signer_count: number; - /** - * Total voting weight of signers expected for this proposal - */ - total_signer_weight: number; - /** - * Total STX stacked of signers expected for this proposal - */ - total_signer_stacked_amount: string; - /** - * Number of signers that submitted an approval for this proposal - */ - accepted_count: number; - /** - * Number of signers that submitted a rejection for this proposal - */ - rejected_count: number; - /** - * Number of signers that failed to submit any response/vote for this proposal - */ - missing_count: number; - /** - * Sum of voting weight of signers who approved the proposal - */ - accepted_weight: number; - /** - * Sum of voting weight of signers who rejected the proposal - */ - rejected_weight: number; - /** - * Sum of voting weight of missing signers - */ - missing_weight: number; - signer_data: { - signer_key: string; - /** - * Index of the signer in the stacker set - */ - slot_index: number; - response: "accepted" | "rejected" | "missing"; - /** - * Voting weight of this signer (based on slots allocated which is proportional to stacked amount) - */ - weight: number; - /** - * Voting weight percent (weight / total_weight) - */ - weight_percentage: number; - /** - * Total STX stacked associated with this signer (string quoted integer) - */ - stacked_amount: string; - /** - * The signer binary version reported by this signer for this proposal response (null if response missing) - */ - version: string | null; - /** - * ISO timestamp of when this response was received (null if response missing - */ - received_at: string | null; - /** - * Time duration (in milliseconds) taken to submit this response (tracked best effort, null if response missing) - */ - response_time_ms: number | null; - /** - * (For rejection responses) reason string for rejection - */ - reason_string: string | null; - /** - * (For rejection responses) reason code for rejection - */ - reason_code: string | null; - /** - * (For rejection responses) reject code for rejection - */ - reject_code: string | null; - }[]; - }[]; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/signer-metrics-api/blocks/aggregated-signer-information-for-a-block.mdx b/content/docs/stacks/signer-metrics-api/blocks/aggregated-signer-information-for-a-block.mdx deleted file mode 100644 index deee661f1..000000000 --- a/content/docs/stacks/signer-metrics-api/blocks/aggregated-signer-information-for-a-block.mdx +++ /dev/null @@ -1,182 +0,0 @@ ---- -title: Aggregated signer information for a block -description: Get aggregated signer information for a specific block. -toc: false ---- - -import { Root, API, APIInfo, APIExample, Responses, Response, ResponseTypes, ExampleResponse, TypeScriptResponse, Property, ObjectCollapsible, Requests, Request, APIPlayground } from "fumadocs-openapi/ui"; - - - - - - - -## Aggregated signer information for a block - -Aggregated signer information for a block - -### Path Parameters - - - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/signer-metrics/v1/blocks/latest" -``` - - - - - -```js -fetch("https://api.hiro.so/signer-metrics/v1/blocks/latest", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "block_height": 0, - "block_hash": "string", - "block_time": 0, - "index_block_hash": "string", - "burn_block_height": 0, - "tenure_height": 0, - "signer_data": { - "cycle_number": 0, - "total_signer_count": 0, - "accepted_count": 0, - "rejected_count": 0, - "missing_count": 0, - "accepted_excluded_count": 0, - "average_response_time_ms": 0, - "block_proposal_time_ms": 0, - "accepted_stacked_amount": "string", - "rejected_stacked_amount": "string", - "missing_stacked_amount": "string", - "accepted_weight": 0, - "rejected_weight": 0, - "missing_weight": 0 - } -} -``` - - - - - -```ts -export interface Response { - block_height: number; - block_hash: string; - /** - * Unix timestamp in seconds of when the block was mined - */ - block_time: number; - index_block_hash: string; - burn_block_height: number; - tenure_height: number; - /** - * Signer data can by null if it was not detected by the metrics service - */ - signer_data: { - cycle_number: number; - /** - * Total number of signers expected for this block - */ - total_signer_count: number; - /** - * Number of signers that submitted an approval for this block - */ - accepted_count: number; - /** - * Number of signers that submitted a rejection for this block - */ - rejected_count: number; - /** - * Number of signers that failed to submit any response/vote for this block - */ - missing_count: number; - /** - * Number of signers that submitted an approval but where not included in time by the miner (this is a subset of the accepted_count) - */ - accepted_excluded_count: number; - /** - * Average time duration (in milliseconds) taken by signers to submit a response for this block (tracked best effort) - */ - average_response_time_ms: number; - /** - * Unix timestamp in milliseconds of when the block was first proposed (tracked best effort) - */ - block_proposal_time_ms: number; - /** - * Sum of total STX stacked of signers who approved the block - */ - accepted_stacked_amount: string; - /** - * Sum of total STX stacked of signers who rejected the block - */ - rejected_stacked_amount: string; - /** - * Sum of total STX stacked of missing signers - */ - missing_stacked_amount: string; - /** - * Sum of voting weight of signers who approved the block (based on slots allocated to each signer proportional to stacked amount) - */ - accepted_weight: number; - /** - * Sum of voting weight of signers who rejected the block - */ - rejected_weight: number; - /** - * Sum of voting weight of missing signers - */ - missing_weight: number; - } | null; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/signer-metrics-api/blocks/aggregated-signer-information-for-most-recent-blocks.mdx b/content/docs/stacks/signer-metrics-api/blocks/aggregated-signer-information-for-most-recent-blocks.mdx deleted file mode 100644 index 697d6cfb8..000000000 --- a/content/docs/stacks/signer-metrics-api/blocks/aggregated-signer-information-for-most-recent-blocks.mdx +++ /dev/null @@ -1,206 +0,0 @@ ---- -title: Aggregated signer information for most recent blocks -description: Get aggregated signer information for most recent blocks. -toc: false ---- - -import { Root, API, APIInfo, APIExample, Responses, Response, ResponseTypes, ExampleResponse, TypeScriptResponse, Property, ObjectCollapsible, Requests, Request, APIPlayground } from "fumadocs-openapi/ui"; - - - - - - - -## Aggregated signer information for most recent blocks - -Aggregated signer information for most recent blocks - -### Query Parameters - - - -Number of results to return - -Default: `100` - - - - - -Number of results to skip - -Default: `0` - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/signer-metrics/v1/blocks?limit=100&offset=0" -``` - - - - - -```js -fetch("https://api.hiro.so/signer-metrics/v1/blocks?limit=100&offset=0", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "total": 0, - "limit": 0, - "offset": 0, - "results": [ - { - "block_height": 0, - "block_hash": "string", - "block_time": 0, - "index_block_hash": "string", - "burn_block_height": 0, - "tenure_height": 0, - "signer_data": { - "cycle_number": 0, - "total_signer_count": 0, - "accepted_count": 0, - "rejected_count": 0, - "missing_count": 0, - "accepted_excluded_count": 0, - "average_response_time_ms": 0, - "block_proposal_time_ms": 0, - "accepted_stacked_amount": "string", - "rejected_stacked_amount": "string", - "missing_stacked_amount": "string", - "accepted_weight": 0, - "rejected_weight": 0, - "missing_weight": 0 - } - } - ] -} -``` - - - - - -```ts -export interface Response { - total: number; - limit: number; - offset: number; - results: { - block_height: number; - block_hash: string; - /** - * Unix timestamp in seconds of when the block was mined - */ - block_time: number; - index_block_hash: string; - burn_block_height: number; - tenure_height: number; - /** - * Signer data can by null if it was not detected by the metrics service - */ - signer_data: { - cycle_number: number; - /** - * Total number of signers expected for this block - */ - total_signer_count: number; - /** - * Number of signers that submitted an approval for this block - */ - accepted_count: number; - /** - * Number of signers that submitted a rejection for this block - */ - rejected_count: number; - /** - * Number of signers that failed to submit any response/vote for this block - */ - missing_count: number; - /** - * Number of signers that submitted an approval but where not included in time by the miner (this is a subset of the accepted_count) - */ - accepted_excluded_count: number; - /** - * Average time duration (in milliseconds) taken by signers to submit a response for this block (tracked best effort) - */ - average_response_time_ms: number; - /** - * Unix timestamp in milliseconds of when the block was first proposed (tracked best effort) - */ - block_proposal_time_ms: number; - /** - * Sum of total STX stacked of signers who approved the block - */ - accepted_stacked_amount: string; - /** - * Sum of total STX stacked of signers who rejected the block - */ - rejected_stacked_amount: string; - /** - * Sum of total STX stacked of missing signers - */ - missing_stacked_amount: string; - /** - * Sum of voting weight of signers who approved the block (based on slots allocated to each signer proportional to stacked amount) - */ - accepted_weight: number; - /** - * Sum of voting weight of signers who rejected the block - */ - rejected_weight: number; - /** - * Sum of voting weight of missing signers - */ - missing_weight: number; - } | null; - }[]; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/signer-metrics-api/blocks/index.mdx b/content/docs/stacks/signer-metrics-api/blocks/index.mdx deleted file mode 100644 index c11f8a6e3..000000000 --- a/content/docs/stacks/signer-metrics-api/blocks/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Blocks -description: Get aggregated signer information for blocks. -toc: false -index: true ---- \ No newline at end of file diff --git a/content/docs/stacks/signer-metrics-api/index.mdx b/content/docs/stacks/signer-metrics-api/index.mdx deleted file mode 100644 index 9d830f3cc..000000000 --- a/content/docs/stacks/signer-metrics-api/index.mdx +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Overview -description: Monitor and analyze signer behavior on the Stacks network. ---- - -import { SecondaryCard } from '@/components/card'; - -The Signer Metrics API enables you to monitor signers on the Stacks network. With a familiar REST interface, you can easily fetch information about the signer network, such as lists of active signers in a particular PoX cycle and signer information for a particular block. - -This API also lets you analyze and evaluate the behavior of individual signers, such as their block acceptance rate, their average block push time, and more. - -## Popular endpoints - - - - - - - -## Related tools - -- **[Stacks Blockchain API](/stacks/api)**: Fetch richer data from Hiro's Stacks Blockchain API. -- **[Stacks Node RPC API](/stacks/rpc-api)**: Query the Stacks Node RPC API, interact with smart contracts, and broadcast transactions all via a familiar REST interface. -- **[Token Metadata API](/stacks/token-metadata-api)**: Fetch fungible and non-fungible token data on the Stacks blockchain. - -
- - -Reach out to us on the #api channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET. - - - diff --git a/content/docs/stacks/signer-metrics-api/info/index.mdx b/content/docs/stacks/signer-metrics-api/info/index.mdx deleted file mode 100644 index 7ab2124bf..000000000 --- a/content/docs/stacks/signer-metrics-api/info/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Info -description: Service status endpoints -toc: false -index: true ---- \ No newline at end of file diff --git a/content/docs/stacks/signer-metrics-api/info/status.mdx b/content/docs/stacks/signer-metrics-api/info/status.mdx deleted file mode 100644 index fed7fbed3..000000000 --- a/content/docs/stacks/signer-metrics-api/info/status.mdx +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: API Status -description: Displays the status of the API and its current workload. -toc: false ---- - -import { Root, API, APIInfo, APIExample, Responses, Response, ResponseTypes, ExampleResponse, TypeScriptResponse, Property, ObjectCollapsible, Requests, Request, APIPlayground } from "fumadocs-openapi/ui"; - - - - - - - -## API Status - -Displays the status of the API and its current workload - -| Status code | Description | -| ----------- | ----------- | -| `200` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/signer-metrics/" -``` - - - - - -```js -fetch("https://api.hiro.so/signer-metrics/", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "server_version": "signer-metrics-api v0.0.1 (master:a1b2c3)", - "status": "ready", - "chain_tip": { - "block_height": 163541 - } -} -``` - - - - - -```ts -export interface ApiStatusResponse { - server_version: string; - status: string; - chain_tip: { - block_height: number; - }; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/signer-metrics-api/meta.json b/content/docs/stacks/signer-metrics-api/meta.json deleted file mode 100644 index ec56e8475..000000000 --- a/content/docs/stacks/signer-metrics-api/meta.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "title": "Signer Metrics API", - "root": true, - "pages": [ - "---Signer Metrics API---", - "index", - "---API Reference---", - "info", - "signers", - "blocks", - "block-proposals", - "prometheus" - ] -} diff --git a/content/docs/stacks/signer-metrics-api/prometheus/index.mdx b/content/docs/stacks/signer-metrics-api/prometheus/index.mdx deleted file mode 100644 index c47e7b6b9..000000000 --- a/content/docs/stacks/signer-metrics-api/prometheus/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Prometheus Metrics -description: Get Prometheus metrics for the Signer Metrics API. -toc: false -index: true ---- \ No newline at end of file diff --git a/content/docs/stacks/signer-metrics-api/prometheus/meta.json b/content/docs/stacks/signer-metrics-api/prometheus/meta.json deleted file mode 100644 index 87492d80b..000000000 --- a/content/docs/stacks/signer-metrics-api/prometheus/meta.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "title": "Prometheus Metrics", - "pages": ["..."] -} \ No newline at end of file diff --git a/content/docs/stacks/signer-metrics-api/prometheus/metrics.mdx b/content/docs/stacks/signer-metrics-api/prometheus/metrics.mdx deleted file mode 100644 index 08b5610b1..000000000 --- a/content/docs/stacks/signer-metrics-api/prometheus/metrics.mdx +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: Prometheus Metrics -description: Get Prometheus metrics for the Signer Metrics API. -toc: false ---- - -import { Root, API, APIInfo, APIExample, Responses, Response, ResponseTypes, ExampleResponse, TypeScriptResponse, Property, ObjectCollapsible, Requests, Request, APIPlayground } from "fumadocs-openapi/ui"; - - - - - - - -## API Signer Prometheus Metrics - -Retreives the Prometheus metrics signer and block proposal related data - -| Status code | Description | -| ----------- | ----------- | -| `200` | Prometheus metrics in plain text format | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/signer-metrics/metrics" -``` - - - - - -```js -fetch("https://api.hiro.so/signer-metrics/metrics", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -"string" -``` - - - - - -```ts -export type Response = string; -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/signer-metrics-api/signers/index.mdx b/content/docs/stacks/signer-metrics-api/signers/index.mdx deleted file mode 100644 index 40196a10d..000000000 --- a/content/docs/stacks/signer-metrics-api/signers/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Signers -description: Get information about signers on the Stacks blockchain. -toc: false -index: true ---- \ No newline at end of file diff --git a/content/docs/stacks/signer-metrics-api/signers/pox-cycle-signer.mdx b/content/docs/stacks/signer-metrics-api/signers/pox-cycle-signer.mdx deleted file mode 100644 index c6a6d513f..000000000 --- a/content/docs/stacks/signer-metrics-api/signers/pox-cycle-signer.mdx +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: PoX Cycle Signer -description: Get stats for a specific signer in a given PoX cycle. -toc: false ---- - -import { Root, API, APIInfo, APIExample, Responses, Response, ResponseTypes, ExampleResponse, TypeScriptResponse, Property, ObjectCollapsible, Requests, Request, APIPlayground } from "fumadocs-openapi/ui"; - - - - - - - -## PoX Cycle Signer - -Get stats for a specific signer in a given PoX cycle - -### Path Parameters - - - -PoX cycle number - - - - - -Signer public key (hex encoded) - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Default Response | -| `404` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/signer-metrics/v1/cycles/0/signers/string" -``` - - - - - -```js -fetch("https://api.hiro.so/signer-metrics/v1/cycles/0/signers/string", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "signer_key": "string", - "slot_index": 0, - "weight": 0, - "weight_percentage": 0, - "stacked_amount": "string", - "stacked_amount_percent": 0, - "stacked_amount_rank": 0, - "proposals_accepted_count": 0, - "proposals_rejected_count": 0, - "proposals_missed_count": 0, - "average_response_time_ms": 0, - "last_seen": "string", - "version": "string" -} -``` - - - - - -```ts -export interface Response { - signer_key: string; - /** - * Index of the signer in the stacker set - */ - slot_index: number; - /** - * Voting weight of this signer (based on slots allocated which is proportional to stacked amount) - */ - weight: number; - /** - * Voting weight percent (weight / total_weight) - */ - weight_percentage: number; - /** - * Total STX stacked associated with this signer (string quoted integer) - */ - stacked_amount: string; - /** - * Stacked amount percent (stacked_amount / total_stacked_amount) - */ - stacked_amount_percent: number; - /** - * This signer's rank in the list of all signers (for this cycle) ordered by stacked amount - */ - stacked_amount_rank: number; - /** - * Number of block proposals accepted by this signer - */ - proposals_accepted_count: number; - /** - * Number of block proposals rejected by this signer - */ - proposals_rejected_count: number; - /** - * Number of block proposals missed by this signer - */ - proposals_missed_count: number; - /** - * Time duration (in milliseconds) taken to submit responses to block proposals (tracked best effort) - */ - average_response_time_ms: number; - /** - * ISO timestamp of the last time a message from this signer was seen - */ - last_seen: string | null; - /** - * The last seen signer binary version reported by this signer - */ - version: string | null; -} -``` - - - - - - - - - - - - - -```json -{ - "error": "string" -} -``` - - - - - -```ts -export interface Response { - /** - * Error message when signer is not found - */ - error: string; -} -``` - - - - - - - - - - - - - - \ No newline at end of file diff --git a/content/docs/stacks/signer-metrics-api/signers/pox-cycle-signers.mdx b/content/docs/stacks/signer-metrics-api/signers/pox-cycle-signers.mdx deleted file mode 100644 index deb45b1ae..000000000 --- a/content/docs/stacks/signer-metrics-api/signers/pox-cycle-signers.mdx +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: PoX Cycle Signers -description: Get a list of signers in a given PoX cycle. -toc: false ---- - -import { Root, API, APIInfo, APIExample, Responses, Response, ResponseTypes, ExampleResponse, TypeScriptResponse, Property, ObjectCollapsible, Requests, Request, APIPlayground } from "fumadocs-openapi/ui"; - - - - - - - -## PoX Cycle Signers - -List of signers for a given PoX cycle - -### Query Parameters - - - -Start of time range (e.g., now-2h or ISO timestamp) - - - - - -End of time range (e.g., now or ISO timestamp) - - - - - -Number of results to return (default: 100) - -Default: `100` - - - - - -Number of results to skip (default: 0) - -Default: `0` - - - -### Path Parameters - - - -PoX cycle number - - - -| Status code | Description | -| ----------- | ----------- | -| `200` | Default Response | - - - - - - - - - - - - - -```bash -curl -X GET "https://api.hiro.so/signer-metrics/v1/cycles/0/signers?from=string&to=string&limit=100&offset=0" -``` - - - - - -```js -fetch("https://api.hiro.so/signer-metrics/v1/cycles/0/signers?from=string&to=string&limit=100&offset=0", { - method: "GET" -}); -``` - - - - - - - - - - - - - -```json -{ - "total": 0, - "limit": 0, - "offset": 0, - "results": [ - { - "signer_key": "string", - "slot_index": 0, - "weight": 0, - "weight_percentage": 0, - "stacked_amount": "string", - "stacked_amount_percent": 0, - "stacked_amount_rank": 0, - "proposals_accepted_count": 0, - "proposals_rejected_count": 0, - "proposals_missed_count": 0, - "average_response_time_ms": 0, - "last_seen": "string", - "version": "string" - } - ] -} -``` - - - - - -```ts -export interface Response { - total: number; - limit: number; - offset: number; - results: { - signer_key: string; - /** - * Index of the signer in the stacker set - */ - slot_index: number; - /** - * Voting weight of this signer (based on slots allocated which is proportional to stacked amount) - */ - weight: number; - /** - * Voting weight percent (weight / total_weight) - */ - weight_percentage: number; - /** - * Total STX stacked associated with this signer (string quoted integer) - */ - stacked_amount: string; - /** - * Stacked amount percent (stacked_amount / total_stacked_amount) - */ - stacked_amount_percent: number; - /** - * This signer's rank in the list of all signers (for this cycle) ordered by stacked amount - */ - stacked_amount_rank: number; - /** - * Number of block proposals accepted by this signer - */ - proposals_accepted_count: number; - /** - * Number of block proposals rejected by this signer - */ - proposals_rejected_count: number; - /** - * Number of block proposals missed by this signer - */ - proposals_missed_count: number; - /** - * Time duration (in milliseconds) taken to submit responses to block proposals (tracked best effort) - */ - average_response_time_ms: number; - /** - * ISO timestamp of the last time a message from this signer was seen - */ - last_seen: string | null; - /** - * The last seen signer binary version reported by this signer - */ - version: string | null; - }[]; -} -``` - - - - - - - - - - - - - - diff --git a/content/docs/stacks/stacks.js/concepts/accounts-and-addresses.mdx b/content/docs/stacks/stacks.js/concepts/accounts-and-addresses.mdx deleted file mode 100644 index efcb5d82b..000000000 --- a/content/docs/stacks/stacks.js/concepts/accounts-and-addresses.mdx +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: Accounts & Addresses -description: Learn how to get an address from an account. ---- - -Stacks uses the concept of an "account" to represent a user's identity on the blockchain. An account is identified by a unique address. The address is derived from the account's public key, which is derived from the account's private key. - -A normal mainnet address starts with `SP`, and a testnet address starts with `ST`. For example: - -Mainnet: `SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159` - -Testnet: `ST2F4BK4GZH6YFBNHYDDGN4T1RKBA7DA1BJZPJEJJ` - -## Getting an address - -### Using Stacks Connect - -```tsx -n -import { showConnect } from '@stacks/connect'; - -showConnect({ - appDetails, - userSession, - onFinish: () => { - const user = userSession.loadUserData(); - const address = user.profile.stxAddress.mainnet; - // 'SP1MXSZF4NFC8JQ1TTYGEC2WADMC7Y3GHVZYRX6RF' - }, -}); -``` - -### Using a seed phrase / mnemonic / private key - -```ts -n -import { randomSeedPhrase, generateWallet } from "@stacks/wallet-sdk"; -import { privateKeyToAddress } from "@stacks/transactions"; - -const seed = randomSeedPhrase(); - -const wallet = await generateWallet({ - secretKey: seed, - password: 'secret', -}); - -const address = privateKeyToAddress(wallet.accounts[0].stxPrivateKey, 'mainnet'); -// 'SP1MXSZF4NFC8JQ1TTYGEC2WADMC7Y3GHVZYRX6RF' -``` - -### Using a public key - -```ts -n -import { publicKeyToAddress } from '@stacks/transactions'; - -const address = publicKeyToAddress(publicKey, 'mainnet'); -// 'SP1MXSZF4NFC8JQ1TTYGEC2WADMC7Y3GHVZYRX6RF' -``` - -{/* todo: add accounts code sections, once we have better abstractions */} - -{/* todo: multisig */} diff --git a/content/docs/stacks/stacks.js/concepts/broadcasting.mdx b/content/docs/stacks/stacks.js/concepts/broadcasting.mdx deleted file mode 100644 index b4f875880..000000000 --- a/content/docs/stacks/stacks.js/concepts/broadcasting.mdx +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Broadcasting -description: Learn how to broadcast transactions to the Stacks network. ---- - -## Broadcasting Transactions - -A finalized transaction can be broadcasted to the network or serialized (to a byte representation) using Stacks.js. - -```ts -n -import { broadcastTransaction, makeSTXTokenTransfer } from "@stacks/transactions"; - -const transaction = await makeSTXTokenTransfer({ - recipient: "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5", - amount: 42000000, - senderKey: - "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601", - network: "devnet", -}); - -const tx = await broadcastTransaction({ transaction }); - -``` - -For web applications, user wallets can broadcast transactions via [@stacks/connect](/stacks/connect). diff --git a/content/docs/stacks/stacks.js/concepts/post-conditions.mdx b/content/docs/stacks/stacks.js/concepts/post-conditions.mdx deleted file mode 100644 index 94a1a2f3a..000000000 --- a/content/docs/stacks/stacks.js/concepts/post-conditions.mdx +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Post-Conditions ---- - -In Stacks, transactions can have *post-conditions*. - -These offer additional security to ensure a transaction was executed as expected. - -More precisely, adding post-conditions to a transaction can ensure that: - -- STX tokens were transferred from an address -- FTs/NFTs were transferred from an address - - -Post-conditions aren't perfect. They can't say anything about the end-state after a transaction. In other words, they can't guarantee the receipt of FTs/NFTs, since they only check for sending. - - -Here's an example of a post-condition using the `Pc` helper, where the `principal` must send 1000 uSTX, or else the transaction will abort: - -```ts -n -import { Pc } from '@stacks/transactions'; - -const tx = await makeContractCall({ - // ... - postConditions: [ - Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6').willSendEq(1000).ustx(), - ], -}); -``` - -If you prefer to write the post-condition manually, you can do so using the following approach: - -```ts -n -import { StxPostCondition, FungiblePostCondition, NonFungiblePostCondition } from '@stacks/transactions'; -// STX post-condition -const stxPostCondition: StxPostCondition = { - type: 'stx-postcondition', - address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B', - condition: 'gte', // 'eq' | 'gt' | 'gte' | 'lt' | 'lte' - amount: '100', -}; - -// Fungible token post-condition -const ftPostCondition: FungiblePostCondition = { - type: 'ft-postcondition', - address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B', - condition: 'eq', // 'eq' | 'gt' | 'gte' | 'lt' | 'lte' - amount: '100', - asset: 'SP3D6PV2ACBPEKYJTCMH7HEN02KP87QSP8KTEH335.my-ft-token::my-token', -}; - -// Non-fungible token post-condition -const nftPostCondition: NonFungiblePostCondition = { - type: 'nft-postcondition', - address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B', - condition: 'sent', // 'sent' | 'not-sent' - asset: 'SP3D6PV2ACBPEKYJTCMH7HEN02KP87QSP8KTEH335.my-nft::my-asset', - assetId: Cl.uint(602), -}; -``` - -## Post-condition mode - -In addition to the post-condition itself, we can also specify a `mode` for the transaction to verify asset transfers. -The mode can be either `Allow` or `Deny`. - -- `Allow` means that the transaction can transfer any asset (assuming no conflicting post-conditions). -- `Deny` means the transaction will fail if any asset transfers (not specified in the post-conditions) are attempted. - - -In either case, all post-conditions will still be checked. -By default, transactions are set to `Deny` mode for additional security. - \ No newline at end of file diff --git a/content/docs/stacks/stacks.js/concepts/private-keys.mdx b/content/docs/stacks/stacks.js/concepts/private-keys.mdx deleted file mode 100644 index 4140fa4c6..000000000 --- a/content/docs/stacks/stacks.js/concepts/private-keys.mdx +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: Private Keys & Wallets -description: Learn how to manage secrets with Stacks.js. ---- - -import { Card, SmallCard } from '@/components/card'; -import { Play, FileSignature } from 'lucide-react'; - -## WITHOUT direct private key access - -Most users interact with apps via their favorite Stacks wallet. -Developers can build web apps that prompt the user for an action (e.g. sign a transaction), and then the wallet will handle the rest. - -} - href="/stacks/connect" - title="Build Web Apps" - description="You can build Stacks enabled web apps without direct private key access using Stacks Connect." -/> - -## WITH private key access - -Developers can build scripts, backends, and tools intended for full control over private keys. - -- Using the Stacks.js CLI directly to send transactions, or perform common tasks -- Building custom tools using Stacks.js libraries that manage private keys directly - -### Generating random private keys - -Let's start by generating a random private key. -Note that this will return a different value each time you run the code. - -```ts -n -import { randomPrivateKey } from '@stacks/transactions'; - -const privateKey = randomPrivateKey(); -// 'f5a31c1268a1e37d4edaa05c7d11183c5fbfdcdc48aae36ea4d8cd5cb709932801' -``` - -Private keys are typically represented as hex strings in Stacks.js. -For more control you can use the `PrivateKey` type, which also accepts raw bytes as `Uint8Array` in JavaScript. - -### Using a wallet / seed phrase - -Typically, we don't want to generate random private keys, but instead use a deterministic wallet based on a seed phrase. - -#### Generate a random seed phrase (24 words): - -```ts -n -import { randomSeedPhrase } from '@stacks/wallet-sdk'; - -const phrase = randomSeedPhrase(); -// "warrior volume sport ... figure cake since" -``` - -#### Generate a wallet from a seed phrase: - -```ts -n -import { generateWallet, randomSeedPhrase } from '@stacks/wallet-sdk'; - -const seedPhrase = randomSeedPhrase(); - -let wallet = await generateWallet({ - secretKey: seedPhrase, - password: "secret", -}); - -console.log(wallet.accounts[0]); // one account is generated by default -// {  -// stxPrivateKey: '893fc4936c5350394bbe0053d2c31a4b5a44680f6dceb4be2aacaaa3c12e45ff01', -// dataPrivateKey: '676dc36d89ba04cf1789552fc35f3a6279b4b5f13f3d49fb469b0afecea9698f', -// appsKey: 'xprvA19evFHUzrZF3wULUSv1UVcQNRP7xJ2vn2MyAKaUHbT8SvjrrkkhANRG2bewMxHAeDSoUVUBRPiztDc8WwGtz9Ero2GXW5rk3vHHXmutb4V', -// salt: 'cf8a5c7142d842bb38f30c5ab626f7996dd7494236edf21ba00349bb09b9558d', -// index: 0 -// }  -``` - -#### Generate more accounts: - -```ts -n -import { generateNewAccount, generateWallet, randomSeedPhrase } from '@stacks/wallet-sdk'; - -const seedPhrase = randomSeedPhrase(); - -let wallet = await generateWallet({ - secretKey: seedPhrase, - password: "secret", -}); - -wallet = generateNewAccount(wallet); -console.log(wallet.accounts.length); // 2 -``` \ No newline at end of file diff --git a/content/docs/stacks/stacks.js/concepts/transactions.mdx b/content/docs/stacks/stacks.js/concepts/transactions.mdx deleted file mode 100644 index 4ee12171c..000000000 --- a/content/docs/stacks/stacks.js/concepts/transactions.mdx +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Transactions -description: Learn how to create and broadcast transactions with Stacks.js. ---- - -The following shows how to create a simple transaction (STX transfer) using Stacks.js in different environments. - -## Creating a transaction - -### Using Stacks Connect - -```ts -n -import { openSTXTransfer } from '@stacks/connect'; - -openSTXTransfer({ - network: 'testnet', - - recipient: 'ST39MJ145BR6S8C315AG2BD61SJ16E208P1FDK3AK', // which address you are sending to - amount: 10000, // tokens, denominated in micro-STX - - onFinish: response => console.log(response.txid), - onCancel: () => console.log('User canceled'), -}); -``` - -### Using a private key - -For full manual transaction signing, you need to provide the sender's private key. -Treat the private key as a secret and *never* expose it to the public. - -```ts -n -import { makeSTXTokenTransfer } from '@stacks/transactions'; - -const privateKey = randomPrivateKey(); // see "Private Keys & Wallets" page - -const tx = await makeSTXTokenTransfer({ - recipient: 'ST39MJ145BR6S8C315AG2BD61SJ16E208P1FDK3AK', // which address you are sending to - amount: 10000, // tokens, denominated in micro-STX - senderKey: privateKey, - network: "testnet", -}); -``` - -## Different transaction types - -In Stacks.js, we can create transactions for different purposes: -- STX token transfers -- Smart contract calls -- Smart contract deployments diff --git a/content/docs/stacks/stacks.js/guides/broadcast-transactions.mdx b/content/docs/stacks/stacks.js/guides/broadcast-transactions.mdx deleted file mode 100644 index b54d10d4e..000000000 --- a/content/docs/stacks/stacks.js/guides/broadcast-transactions.mdx +++ /dev/null @@ -1,178 +0,0 @@ ---- -title: Broadcast transactions -description: Create and broadcast transactions to the Stacks blockchain network using Stacks.js. ---- - -import { Badge } from '@/components/ui/badge'; -import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; - -import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; -import { ChevronRight, Code, Terminal } from 'lucide-react'; -import { File, Folder, Files } from 'fumadocs-ui/components/files'; - -The process of broadcasting transactions is fundamental for interacting with blockchains, whether you're transferring tokens, deploying contracts, or executing contract functions. - -In this guide, you will learn how to: - -1. [Install the necessary packages for building and broadcasting transactions](#setup-and-installation) -2. [Build different types of transactions](#create-a-transaction) -3. [Sign and broadcast those transactions to the Stacks blockchain](#broadcasting-the-transaction) -4. [Process and handle the results](#handle-the-results) - -{/* To see this guide in action, check out a full example [here](https://github.com/hiro-so/stacks-connect-example). */} - ---- - -## Setup and installation - -Install the required packages to start building and broadcasting transactions. - -```package-install -@stacks/network @stacks/transactions @stacks/connect -``` - -- **`@stacks/network`**: Used to interact with the Stacks blockchain network. -- **`@stacks/transactions`**: Used to build the transactions. -- **`@stacks/connect`**: Used to authenticate users and broadcast the transactions. - -## Create a transaction - -There are three types of transactions: - -- STX transfer -- Contract deployment -- Contract execution - - - - - STX transfer - - - Contract deployment - - - Contract execution - - - - To transfer STX, use the `makeSTXTokenTransfer` function provided by the `@stacks/transactions` package: - - ```ts stx-transfer.ts -cn - import { broadcastTransaction, makeSTXTokenTransfer } from "@stacks/transactions"; - - const transaction = await makeSTXTokenTransfer({ - recipient: "SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159", - amount: 12345n, - senderKey: - "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601", - network: "devnet", - }); - ``` - - This builds a STX token transfer transaction. The `makeSTXTokenTransfer` function takes parameters like the `recipient` address, `amount` to transfer, and the sender's private key, ie `senderKey`. - - Several parameters are available for calling `makeSTXTokenTransfer`. To learn more, check out our [transactions reference page](/stacks/stacks.js/packages/transactions). - - - - To deploy a contract, use the `makeContractDeploy` function provided by the `@stacks/transactions` package: - - ```ts contract-deploy.ts -cn - import { broadcastTransaction, makeContractDeploy } from '@stacks/transactions'; - - const transaction = await makeContractDeploy({ - contractName: 'hello-world', - codeBody: `(define-public (hello) - (ok "Hello, world!"))`, - senderKey: '753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601', - network: "testnet", - }); - ``` - - This builds a contract deployment transaction. The `makeContractDeploy` function takes parameters like the `contractName`, `codeBody`, and the sender's private key, ie `senderKey`. - - Several parameters are available for calling `makeContractDeploy`. To learn more, check out our [transactions reference page](/stacks/stacks.js/packages/transactions). - - - - To execute a contract function, use the `makeContractCall` function provided by the `@stacks/transactions` package: - - ```ts function-call.ts -cn - import { - broadcastTransaction, - bufferCVFromString, - Cl, - makeContractCall, - Pc, - } from "@stacks/transactions"; - - const postCondition = Pc.principal("SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE") - .willSendEq(1000000n) - .ustx(); - - const transaction = await makeContractCall({ - contractAddress: "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X", - contractName: "contract_name", - functionName: "contract_function", - functionArgs: [Cl.bufferFromAscii("foo")], - senderKey: - "b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01", - validateWithAbi: true, - network: "testnet", - postConditions: [postCondition], - }); - ``` - - This builds a contract function call transaction. The `makeContractCall` function takes parameters like the `contractAddress`, `contractName`, `functionName`, `functionArgs`, `senderKey`, `validateWithAbi`, `network`, `postConditions`, and `anchorMode`. - - Several parameters are available for calling `makeContractCall`. To learn more, check out our [transactions reference page](/stacks/stacks.js/packages/transactions). - - - - -## Broadcasting the transaction - -After building the transaction, broadcast it to the Stacks blockchain network using the `broadcastTransaction` function from the `@stacks/transactions` package. - -1. Pass in the transaction object you created in the previous step to the `broadcastTransaction` function. -2. Handle the response by logging the response object. - -```ts -cn -import { broadcastTransaction } from '@stacks/transactions'; - -const broadcastResponse = await broadcastTransaction({ transaction }); -``` - -This code sends the signed transaction to the Stacks blockchain. The `broadcastTransaction` function returns a response containing the transaction ID, which can be used to track the transaction on the blockchain. - -## Handle the results - -Handle the transaction results by checking the transaction status and responding accordingly. - -```ts -cn -if (broadcastResponse.success) { - console.log('Transaction successful with ID:', broadcastResponse.txid); -} else { - console.error('Transaction failed with error:', broadcastResponse.error); -} -``` - -This checks if the transaction was successful and logs the `txid`. - ---- - -## Next steps - - - - - \ No newline at end of file diff --git a/content/docs/stacks/stacks.js/guides/post-conditions.mdx b/content/docs/stacks/stacks.js/guides/post-conditions.mdx deleted file mode 100644 index a64f48b78..000000000 --- a/content/docs/stacks/stacks.js/guides/post-conditions.mdx +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: Deep dive into post-conditions -description: This guide explains how to use post-conditions to secure your smart contracts. ---- - -import { Badge } from '@/components/ui/badge'; - -import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; -import { ChevronRight, Code, Terminal } from 'lucide-react'; -import { File, Folder, Files } from 'fumadocs-ui/components/files'; - -Post-conditions in Stacks transactions provide an additional layer of security. They ensure that transactions execute as expected without requiring the user to know the underlying smart contract code. - -In this guide, you will learn how to: - -1. [Construct post-conditions](#constructing-post-conditions). -2. [Use post-conditions](#using-post-conditions). -3. [Set the post-condition mode](#setting-the-post-condition-mode). -4. [Usage examples](#usage-examples). - ---- - -## Constructing post-conditions - -In Stacks.js, post-conditions can be constructed using the Pc helpers. These are inspired by Behavior Driven Development (BDD). - -Start with the `Pc.principal` initializer to specify the address of the principal that will be verified in the post-condition. Then auto-complete the rest of the post-condition. - -## Using post-conditions - -Post-conditions can be added to contract calls and FT/NFT transfers to ensure assets are transferred as specified. - -For instance, the following post-condition ensures that the principal initiating the transaction must send exactly 1000 uSTX, or else the transaction will abort. - -```ts -cn -import { Pc } from '@stacks/transactions'; - -const postCondition = Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6') - .willSendEq(1000) - .ustx(); -``` - - - - STX/FT - - `.willSendEq(amount: number)` ensures that the amount to be sent is **exactly** the specified value. - - `.willSendGte(amount: number)` ensures that the amount to be sent is **greater than or equal** to the specified value. - - `.willSendGt(amount: number)` ensures that the amount to be sent is **greater than** the specified value. - - `.willSendLte(amount: number)` ensures that the amount to be sent is **less than or equal** to the specified value. - - `.willSendLt(amount: number)` ensures that the amount to be sent is **less than** the specified value. - - `.ustx()` to specify uSTX as the FT asset _(ends the builder)_ - - `.ft(contract: string, tokenName: string)` to specify a specific FT asset _(ends the builder)_ - - --- - - NFT - - `.willSendAsset()` ensures that an asset should **be sent**. - - `.willNotSendAsset()` to specify an asset should **not be sent** - - - -## Setting the post-condition mode - -When creating a transaction, the mode of the transaction can be set to `Allow` or `Deny` to specify whether unspecified asset transfers are permitted. - -```ts -n -import { PostConditionMode } from '@stacks/transactions'; - -const tx = await makeContractCall({ - // ... - postConditionMode: PostConditionMode.Allow, - // OR - postConditionMode: PostConditionMode.Deny, - // ... -}); -``` - -Essentially, the `postConditionMode` is what tells the Stacks node whether to require (`Deny`) or ignore (`Allow`) the post-conditions when evaluating the transaction. - -## Usage examples - -### Amount uSTX sent - -Construct a post-condition for a certain amount of uSTX to be sent. - -```ts -cn -import { Pc } from '@stacks/transactions'; - -const postCondition = Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6') - .willSendEq(1000) - .ustx(); -``` - -### Amount FT sent - -Construct a post-condition for a certain amount of a specific FT to be sent. - -```ts -cn -import { Pc } from '@stacks/transactions'; - -const postCondition = Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6.token-ft') - .willSendGte(500) - .ft('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6.token-ft', 'token'); -``` - -### Amount NFT sent / not sent - -Construct a post-condition for sending / not-sending a specific NFT. - -```ts -cn -import { Pc } from '@stacks/transactions'; - -const postCondition = Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6') - .willNotSendAsset() - .nft('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6.token-nft::token', Cl.uint(12)); -``` - -### Amount SFT sent / not sent - -Construct a post-condition for sending / not-sending a specific SFT (Semi-fungible token). - -```ts -cn -import { Cl, Pc } from '@stacks/transactions'; - -const postConditionForNFT = Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6') -.willSendAsset() -.nft( - "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.semi-fungible-token::semi-fungible-token-id", - Cl.tuple({ "token-id": Cl.uint(1), owner: Cl.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6') }) -); - -const postConditionForFT = Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6') -.willSendEq(500) -.ft("ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.semi-fungible-token", "semi-fungible-token"); -``` - - -The previous builders (`makeStandardSTXPostCondition`, `makeStandardFungiblePostCondition`, etc) were removed in `v7.0.0`. - - ---- - -## Next steps - - - - - \ No newline at end of file diff --git a/content/docs/stacks/stacks.js/guides/use-with-react-native.mdx b/content/docs/stacks/stacks.js/guides/use-with-react-native.mdx deleted file mode 100644 index e1b8ac31e..000000000 --- a/content/docs/stacks/stacks.js/guides/use-with-react-native.mdx +++ /dev/null @@ -1,185 +0,0 @@ ---- -title: Using Stacks.js with React Native -description: Learn how to use Stacks.js with React Native. ---- - -import { Badge } from '@/components/ui/badge'; - -import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; -import { ChevronRight, Code, Terminal } from 'lucide-react'; -import { File, Folder, Files } from 'fumadocs-ui/components/files'; - -Using Stacks.js with React Native allows you to integrate Stacks blockchain functionalities into mobile applications. - -In this guide, you will learn how to: - -1. [Set up the Expo project](#set-up-the-expo-project). -2. [Install necessary dependencies](#install-necessary-dependencies). -3. [Add NodeJS polyfills](#add-nodejs-polyfills). -4. [Add global polyfills](#add-global-polyfills). -5. [Use Stacks.js in the project](#use-stacksjs-in-the-project). - -{/* To see this guide in action, check out a full example [here](https://github.com/hirosystems/stacks.js-react-native-expo-51). */} - ---- - -## Set up the Expo project - -Start by creating a new Expo project using `create-expo-app`. - -```terminal -$ npx create-expo-app@latest -``` - -This will generate a boilerplate Expo project. You can run the project with `npm start` and connect a mobile device for previewing via the shown QR code. - -## Install necessary dependencies - -Install Stacks.js libraries along with other dependencies needed for polyfilling browser-specific and NodeJS-specific APIs. - -```terminal -$ npm install @stacks/transactions @stacks/wallet-sdk -$ npm install --save-dev buffer process react-native-get-random-values text-encoding readable-stream crypto-browserify @peculiar/webcrypto -``` - -## Add NodeJS polyfills - -Modify the project's Metro configuration to include polyfills for missing NodeJS modules. - -```terminal -$ npx expo customize metro.config.js -``` - -```js metro.config.js -cn -const { getDefaultConfig } = require("expo/metro-config"); - -const config = getDefaultConfig(__dirname); - -config.resolver.extraNodeModules = { - stream: require.resolve("readable-stream"), - crypto: require.resolve("crypto-browserify"), -}; - -module.exports = config; -``` - -## Add global polyfills - -Update the Expo entry point to include polyfills. - -1. Create `polyfill.js` file -2. Create `index.js` file -3. Update the `package.json` - -```js polyfill.js -cn -import { Buffer } from "buffer/"; -import process from "process"; -import "react-native-get-random-values"; -import { TextDecoder, TextEncoder } from "text-encoding"; - -global.process = process; -global.Buffer = Buffer; -global.TextEncoder = TextEncoder; -global.TextDecoder = TextDecoder; -``` - -```js index.js -cn -import "./polyfill"; -import { Crypto } from "@peculiar/webcrypto"; - -Object.assign(global.crypto, new Crypto()); - -import "expo-router/entry"; -``` - -```json package.json -"main": "index.js", -``` - - -Ensure that the polyfills live in their own file as specified to avoid any runtime issues. - - -## Use Stacks.js in the project - -Edit the `app/(tabs)/index.tsx` file to integrate Stacks.js functionalities, starting with the imports. - -```tsx app/(tabs)/index.tsx -cn -import { - TransactionVersion, - getAddressFromPrivateKey, - makeSTXTokenTransfer, -} from "@stacks/transactions"; -import { Wallet, generateSecretKey, generateWallet } from "@stacks/wallet-sdk"; -import { useState } from "react"; -``` - -Now you can start to manage the state as follows: - -```tsx app/(tabs)/index.tsx -cn -export default function HomeScreen() { - const [mnemonic, setMnemonic] = useState("..."); - const [wallet, setWallet] = useState(null); - const [log, setLog] = useState(""); -} -``` - -Next, to generate a wallet and sign a transaction: - -```tsx app/(tabs)/index.tsx -cn -const generate = async () => { - const mnemonic = generateSecretKey(); - setMnemonic(mnemonic); - - const wallet = await generateWallet({ - secretKey: mnemonic, - password: "", - }); - setWallet(wallet); - - await makeSTXTokenTransfer({ - amount: 1000, - anchorMode: "any", - recipient: "SP3W993D3BRDYB284CY3SBFDEGTC5XEDJPDEA21CN", - senderKey: wallet.accounts[0].stxPrivateKey, - fee: 10, - network: "mainnet", - nonce: 0, - }); - setLog("Transaction signed successfully ☑"); -}; -``` - -And lastly, to integrate the UI: - -```tsx app/(tabs)/index.tsx -cn - - Seed Phrase - {mnemonic} - \n \n
\n\n### Related tools\n\n- **[Ordinals API](/bitcoin/ordinals/api)**: Looking for on-chain data without the front end? Leverage the Ordinals API.\n- **[Stacks Explorer](https://explorer.hiro.so)**: Looking for a front end to verify activity on the Stacks blockchain? Try the Stacks Explorer.\n\n---\n\nNeed help building with the Ordinals Explorer? Reach out to us on the `#ordinals` channel on Discord under the [Hiro Developer Tools section](https://stacks.chat/). There’s also a [weekly office hours](https://events.stacks.co/event/HD16484710) on Discord every Thursday at 11am ET.\n" + }, + { + "title": "Build Ordinals Explorer", + "description": "", + "slug": "/bitcoin/runes/explorer/guides/build-explorer", + "content": "\nAfter installing and configuring your environment, you can run the Ordinals Explorer locally if you wish by running the followning `npm` command:\n\n`npm run dev`\n\n## Building for production\n\nYou may also build a production version of the Ordinals Explorer. To do that, simply run the following command:\n\n`npm run build`\n\n\n Running `npm run build` also run the default next.js build task.\n\n" + }, + { + "title": "Overview", + "description": "The Runes API provides you with fast, reliable data for Bitcoin Runes via an easy-to-use REST interface.", + "slug": "/bitcoin/runes/api/index", + "content": "\nThe Runes API is a service that helps you with the complete ingestion of Bitcoin Runes data. Using our endpoints, you can retrieve metadata for a particular rune, trading activity, all runes held by a particular address, and more.\n\nThe Runes API uses REST endpoints and cached responses in order to optimize performance and reduce unnecessary requests. Reliable, consistent runes data, one request away.\n\n## Popular endpoints\n\n\n \n \n \n\n\n### Related tools\n\n{/* - **[Runehook](/bitcoin/runes/runeshook)**: Want to run your own infra? [Set up your own Runehook](/bitcoin/runes/runeshook/guides/runehook-as-a-service), the indexer that powers the Rune API. */}\n- **[Ordinals API](/bitcoin/ordinals/api)**: Looking for on-chain ordinals data without the front end? Leverage the Ordinals API.\n- **[Ordinals Explorer](https://ordinals.hiro.so/)**: The Ordinals API powers Hiro’s Ordinals Explorer, which lets you rapidly discover inscriptions and verify on-chain activity.\n\n---\n\nNeed help building with Runes API? Reach out to us on the `#ordinals` channel on Discord. Or join us at our weekly office hours on Discord every Monday at 11am ET.\n" + }, + { + "title": "Status", + "description": "Retrieves information about the Rune API status.", + "slug": "/bitcoin/runes/api/info/index", + "content": "" + }, + { + "title": "Get API Status", + "description": "Retrieves the status of the API.", + "slug": "/bitcoin/runes/api/info/status", + "content": "\n" + }, + { + "title": "Get address balances", + "description": "Retrieves a paginated list of address balances.", + "slug": "/bitcoin/runes/api/balances/address", + "content": "\n" + }, + { + "title": "Balances", + "description": "Retrieves information about Rune balances.", + "slug": "/bitcoin/runes/api/balances/index", + "content": "" + }, + { + "title": "Get holder balance", + "description": "Retrieves holder balance for a specific Rune.", + "slug": "/bitcoin/runes/api/balances/holder-balance", + "content": "\n" + }, + { + "title": "Get rune holders", + "description": "Retrieves a paginated list of holders for a Rune.", + "slug": "/bitcoin/runes/api/balances/holders", + "content": "\n" + }, + { + "title": "Activities", + "description": "Retrieves information about Rune activities.", + "slug": "/bitcoin/runes/api/activities/index", + "content": "" + }, + { + "title": "Get activity for a transaction", + "description": "Retrieves a paginated list of rune activity for a transaction.", + "slug": "/bitcoin/runes/api/activities/for-transaction", + "content": "\n" + }, + { + "title": "Get activity for an address", + "description": "Retrieves all Rune activity for a Bitcoin address.", + "slug": "/bitcoin/runes/api/activities/for-address", + "content": "\n" + }, + { + "title": "Get activity for a block", + "description": "Retrieves a paginated list of rune activity for a block.", + "slug": "/bitcoin/runes/api/activities/for-block", + "content": "\n" + }, + { + "title": "Get all activity", + "description": "Retrieves all activity for a Rune.", + "slug": "/bitcoin/runes/api/activities/activity", + "content": "\n" + }, + { + "title": "Usage", + "description": "Create your first project in less than 2 minutes", + "slug": "/bitcoin/runes/api/usage", + "content": "\nThe Usage section should focus on practical, hands-on instructions for getting started with the API. This includes:\nAuthentication: How to authenticate with the API (e.g., API keys, OAuth tokens).\nMaking Requests: Basic examples of making requests to the API, including request format, essential headers, and parameters.\nHandling Responses: Information on response structure, understanding status codes, and error handling.\nRate Limits: If applicable, explain any rate limits and best practices for avoiding them.\nThe goal of the \"Usage\" section is to equip developers with the knowledge to make successful API calls and handle responses effectively.\n" + }, + { + "title": "Etchings", + "description": "Retrieves information about Rune etchings.", + "slug": "/bitcoin/runes/api/etchings/index", + "content": "" + }, + { + "title": "Get etchings", + "description": "Retrieves a paginated list of rune etchings.", + "slug": "/bitcoin/runes/api/etchings/get-etchings", + "content": "\n" + }, + { + "title": "Get etching", + "description": "Retrieves information for a Rune etching.", + "slug": "/bitcoin/runes/api/etchings/get-etching", + "content": "\n" + }, + { + "title": "Overview", + "description": "Explore and verify ordinals and BRC-20 data on Bitcoin.", + "slug": "/bitcoin/ordinals/explorer/index", + "content": "\nimport Link from \"next/link\";\nimport { Button } from \"@/components/ui/button\"\n\nThe Ordinals Explorer lets you explore and verify Bitcoin Ordinals and BRC-20 token data. You can also use a variety of filters to discover inscriptions. We maintain and support the [Ordinals Explorer](https://ordinals.hiro.so) as a service for the community, but you can also run your own instance of the explorer if you so choose.\n\n
\n \n \n
\n\n## Related tools\n\n- **[Ordinals API](/bitcoin/ordinals/api)**: Looking for on-chain data without the front end? Leverage the Ordinals API.\n- **[Stacks Explorer](https://explorer.hiro.so)**: Looking for a front end to verify activity on the Stacks blockchain? Try the Stacks Explorer.\n\n---\n\nNeed help building with the Ordinals Explorer? Reach out to us on the `#ordinals` channel on Discord under the [Hiro Developer Tools section](https://stacks.chat/). There’s also a [weekly office hours](https://events.stacks.co/event/HD16484710) on Discord every Thursday at 11am ET.\n" + }, + { + "title": "Build Ordinals Explorer", + "description": "", + "slug": "/bitcoin/ordinals/explorer/guides/build-explorer", + "content": "\nAfter installing and configuring your environment, you can run the Ordinals Explorer locally if you wish by running the followning `npm` command:\n\n`npm run dev`\n\n## Building for production\n\nYou may also build a production version of the Ordinals Explorer. To do that, simply run the following command:\n\n`npm run build`\n\n\n Running `npm run build` also run the default next.js build task.\n\n" + }, + { + "title": "Statistics", + "description": "Retrieves stats on the number of inscriptions per block.", + "slug": "/bitcoin/ordinals/api/statistics/index", + "content": "" + }, + { + "title": "Get inscription count per block", + "description": "Retrieves statistics on the number of inscriptions revealed per block.", + "slug": "/bitcoin/ordinals/api/statistics/get-stats-inscription-count", + "content": "\n" + }, + { + "title": "Get BRC-20 token holders", + "description": "Retrieves a list of holders and their balances for a particular BRC-20 token.", + "slug": "/bitcoin/ordinals/api/brc20/get-brc20-token-holders", + "content": "\n" + }, + { + "title": "BRC-20", + "description": "Retrieves information about BRC-20 tokens.", + "slug": "/bitcoin/ordinals/api/brc20/index", + "content": "" + }, + { + "title": "Get BRC-20 balances", + "description": "Retrieves BRC-20 token balances for a Bitcoin address.", + "slug": "/bitcoin/ordinals/api/brc20/get-brc20-balances", + "content": "\n" + }, + { + "title": "Get BRC-20 token details", + "description": "Retrieves information for a BRC-20 token, including supply and holders.", + "slug": "/bitcoin/ordinals/api/brc20/get-brc20-token-details", + "content": "\n" + }, + { + "title": "Get BRC-20 tokens", + "description": "Retrieves information for BRC-20 tokens.", + "slug": "/bitcoin/ordinals/api/brc20/get-brc20-tokens", + "content": "\n" + }, + { + "title": "Get BRC-20 activity", + "description": "Retrieves BRC-20 activity filtered by ticker, address, operation, or block height.", + "slug": "/bitcoin/ordinals/api/brc20/get-brc20-activity", + "content": "\n\n" + }, + { + "title": "Inscriptions", + "description": "Retrieves information about Ordinals inscriptions.", + "slug": "/bitcoin/ordinals/api/inscriptions/index", + "content": "" + }, + { + "title": "Get inscription transfers", + "description": "Retrieves all transfers for a single inscription.", + "slug": "/bitcoin/ordinals/api/inscriptions/get-inscription-transfers", + "content": "\n" + }, + { + "title": "Get inscriptions", + "description": "Retrieves a list of inscriptions with options to filter and sort results.", + "slug": "/bitcoin/ordinals/api/inscriptions/get-inscriptions", + "content": "\n" + }, + { + "title": "Get inscription content", + "description": "Retrieves the content of a single inscription.", + "slug": "/bitcoin/ordinals/api/inscriptions/get-inscription-content", + "content": "\n" + }, + { + "title": "Get transfers per block", + "description": "Retrieves a list of inscription transfers that ocurred at a specific Bitcoin block.", + "slug": "/bitcoin/ordinals/api/inscriptions/get-transfers-per-block", + "content": "\n" + }, + { + "title": "Get inscription", + "description": "Retrieves a single inscription.", + "slug": "/bitcoin/ordinals/api/inscriptions/get-inscription", + "content": "\n" + }, + { + "title": "Overview", + "description": "The Ordinals API provides you with fast, reliable data for Bitcoin ordinals and BRC-20 tokens via an easy-to-use REST interface.", + "slug": "/bitcoin/ordinals/api/index", + "content": "\nimport { SecondaryCard } from '@/components/card';\n\nThe Ordinals API is a service that helps you with the complete ingestion of ordinals inscription data. Using our endpoints, you can retrieve metadata for a particular inscription, trading activity, all inscriptions held by a particular address, and more.\n\nThe Ordinals API uses REST endpoints and cached responses in order to optimize performance and reduce unnecessary requests. Start integrating ordinals and BRC-20 tokens into your app with one of the most reliable APIs on the market today.\n\n## Popular endpoints\n\n\n \n \n \n \n \n\n\n## Related tools\n\n- **[Bitcoin Indexer](/bitcoin/indexer)**: Want to run your own infra? [Set up your own Bitcoin Indexer](/bitcoin/indexer), the indexer that powers the Ordinals API.\n- **[Ordinals Explorer](https://ordinals.hiro.so/)**: The Ordinals API powers Hiro’s Ordinals Explorer, which lets you rapidly discover inscriptions and verify on-chain activity.\n\n
\n\n\nReach out to us on the #ordinals channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET.\n\n" + }, + { + "title": "Status", + "description": "Retrieves information about the Ordinals API status, including the server version.", + "slug": "/bitcoin/ordinals/api/info/index", + "content": "" + }, + { + "title": "Get API status", + "description": "Retrieves the running status of the Ordinals API.", + "slug": "/bitcoin/ordinals/api/info/status", + "content": "\n" + }, + { + "title": "Usage", + "description": "Create your first project in less than 2 minutes", + "slug": "/bitcoin/ordinals/api/usage", + "content": "\nThe Usage section should focus on practical, hands-on instructions for getting started with the API. This includes:\nAuthentication: How to authenticate with the API (e.g., API keys, OAuth tokens).\nMaking Requests: Basic examples of making requests to the API, including request format, essential headers, and parameters.\nHandling Responses: Information on response structure, understanding status codes, and error handling.\nRate Limits: If applicable, explain any rate limits and best practices for avoiding them.\nThe goal of the \"Usage\" section is to equip developers with the knowledge to make successful API calls and handle responses effectively.\n" + }, + { + "title": "Satoshis", + "description": "Retrieves ordinal information for satoshis.", + "slug": "/bitcoin/ordinals/api/satoshis/index", + "content": "" + }, + { + "title": "Get satoshi ordinal", + "description": "Retrieves ordinal information for a single satoshi.", + "slug": "/bitcoin/ordinals/api/satoshis/get-satoshi", + "content": "\n" + }, + { + "title": "Get satoshi inscriptions", + "description": "Retrieves all inscriptions associated with a single satoshi.", + "slug": "/bitcoin/ordinals/api/satoshis/get-satoshi-inscriptions", + "content": "\n\n" + }, + { + "title": "Home", + "description": "", + "slug": "/bitcoin/index", + "content": "\nimport { Card, SmallCard } from '@/components/card';\nimport { ImageZoom } from 'fumadocs-ui/components/image-zoom';\nimport { PageFooter } from '@/components/footer';\nimport { Database, Play } from 'lucide-react';\nimport { API, Backend, Chainhook, Newspaper, Ordinals, QuestionIcon, BugIcon, Pulse } from '@/components/ui/icon';\nimport heroImage from '@/public/bitcoin-hero.svg';\n\n
\n\n
\n \n\n
\n\n ## Build with Bitcoin\n\n Find all the guides and resources you need to build on Ordinals and Runes.\n\n
\n
\n\n\n }\n href=\"/bitcoin/get-started\"\n title=\"Get Started\"\n description=\"Get started with our end-to-end tutorials and quickstart guides across all Hiro's ordinals tools.\"\n />\n }\n href=\"/bitcoin/ordinals/api\"\n title=\"Ordinals API Reference\"\n description=\"Explore API endpoints for interacting with Ordinals and meta-protocols.\"\n />\n\n\n
\n\n

\n Explore Bitcoin\n

\n\n---\n\n\n }\n href=\"/bitcoin/indexer\"\n title=\"Bitcoin Indexer\"\n description=\"Use the Bitcoin Indexer to index and query Bitcoin blockchain data.\"\n />\n }\n href=\"/bitcoin/ordinals/api\"\n title=\"Ordinals API\"\n description=\"Fetch on-chain data for Ordinals and meta-protocols with our hosted API.\"\n />\n }\n href=\"https://ordinals.hiro.so/\"\n title=\"Ordinals Explorer\"\n description=\"View on-chain data for Ordinals and meta-protocols with our explorer.\"\n />\n }\n href=\"/bitcoin/runes/api\"\n title=\"Runes API\"\n description=\"Interact with the Runes protocol from your backend via our hosted API.\"\n />\n\n\n
\n\n
\n\n" + }, + { + "title": "API keys", + "description": "For developers who need API requests beyond the standard rate limits.", + "slug": "/bitcoin/api-keys", + "content": "\nimport ApiKeysContent from '@/content/_shared/api-keys.mdx';\n\n\n" + }, + { + "title": "Status", + "description": "Retrieves information about the Rune API status.", + "slug": "/bitcoin/api/runes/info/index", + "content": "" + }, + { + "title": "Get API Status", + "description": "Retrieves the status of the API.", + "slug": "/bitcoin/api/runes/info/status", + "content": "\n" + }, + { + "title": "Get address balances", + "description": "Retrieves a paginated list of address balances.", + "slug": "/bitcoin/api/runes/balances/address", + "content": "\n" + }, + { + "title": "Balances", + "description": "Retrieves information about Rune balances.", + "slug": "/bitcoin/api/runes/balances/index", + "content": "" + }, + { + "title": "Get holder balance", + "description": "Retrieves holder balance for a specific Rune.", + "slug": "/bitcoin/api/runes/balances/holder-balance", + "content": "\n" + }, + { + "title": "Get rune holders", + "description": "Retrieves a paginated list of holders for a Rune.", + "slug": "/bitcoin/api/runes/balances/holders", + "content": "\n" + }, + { + "title": "Activities", + "description": "Retrieves information about Rune activities.", + "slug": "/bitcoin/api/runes/activities/index", + "content": "" + }, + { + "title": "Get activity for a transaction", + "description": "Retrieves a paginated list of rune activity for a transaction.", + "slug": "/bitcoin/api/runes/activities/for-transaction", + "content": "\n" + }, + { + "title": "Get activity for an address", + "description": "Retrieves all Rune activity for a Bitcoin address.", + "slug": "/bitcoin/api/runes/activities/for-address", + "content": "\n" + }, + { + "title": "Get activity for a block", + "description": "Retrieves a paginated list of rune activity for a block.", + "slug": "/bitcoin/api/runes/activities/for-block", + "content": "\n" + }, + { + "title": "Get all activity", + "description": "Retrieves all activity for a Rune.", + "slug": "/bitcoin/api/runes/activities/activity", + "content": "\n" + }, + { + "title": "Etchings", + "description": "Retrieves information about Rune etchings.", + "slug": "/bitcoin/api/runes/etchings/index", + "content": "" + }, + { + "title": "Get etchings", + "description": "Retrieves a paginated list of rune etchings.", + "slug": "/bitcoin/api/runes/etchings/get-etchings", + "content": "\n" + }, + { + "title": "Get etching", + "description": "Retrieves information for a Rune etching.", + "slug": "/bitcoin/api/runes/etchings/get-etching", + "content": "\n" + }, + { + "title": "Statistics", + "description": "Retrieves stats on the number of inscriptions per block.", + "slug": "/bitcoin/api/ordinals/statistics/index", + "content": "" + }, + { + "title": "Get inscription count per block", + "description": "Retrieves statistics on the number of inscriptions revealed per block.", + "slug": "/bitcoin/api/ordinals/statistics/get-stats-inscription-count", + "content": "\n" + }, + { + "title": "Get BRC-20 token holders", + "description": "Retrieves a list of holders and their balances for a particular BRC-20 token.", + "slug": "/bitcoin/api/ordinals/brc20/get-brc20-token-holders", + "content": "\n" + }, + { + "title": "BRC-20", + "description": "Retrieves information about BRC-20 tokens.", + "slug": "/bitcoin/api/ordinals/brc20/index", + "content": "" + }, + { + "title": "Get BRC-20 balances", + "description": "Retrieves BRC-20 token balances for a Bitcoin address.", + "slug": "/bitcoin/api/ordinals/brc20/get-brc20-balances", + "content": "\n" + }, + { + "title": "Get BRC-20 token details", + "description": "Retrieves information for a BRC-20 token, including supply and holders.", + "slug": "/bitcoin/api/ordinals/brc20/get-brc20-token-details", + "content": "\n" + }, + { + "title": "Get BRC-20 tokens", + "description": "Retrieves information for BRC-20 tokens.", + "slug": "/bitcoin/api/ordinals/brc20/get-brc20-tokens", + "content": "\n" + }, + { + "title": "Get BRC-20 activity", + "description": "Retrieves BRC-20 activity filtered by ticker, address, operation, or block height.", + "slug": "/bitcoin/api/ordinals/brc20/get-brc20-activity", + "content": "\n\n" + }, + { + "title": "Inscriptions", + "description": "Retrieves information about Ordinals inscriptions.", + "slug": "/bitcoin/api/ordinals/inscriptions/index", + "content": "" + }, + { + "title": "Get inscription transfers", + "description": "Retrieves all transfers for a single inscription.", + "slug": "/bitcoin/api/ordinals/inscriptions/get-inscription-transfers", + "content": "\n" + }, + { + "title": "Get inscriptions", + "description": "Retrieves a list of inscriptions with options to filter and sort results.", + "slug": "/bitcoin/api/ordinals/inscriptions/get-inscriptions", + "content": "\n" + }, + { + "title": "Get inscription content", + "description": "Retrieves the content of a single inscription.", + "slug": "/bitcoin/api/ordinals/inscriptions/get-inscription-content", + "content": "\n" + }, + { + "title": "Get transfers per block", + "description": "Retrieves a list of inscription transfers that ocurred at a specific Bitcoin block.", + "slug": "/bitcoin/api/ordinals/inscriptions/get-transfers-per-block", + "content": "\n" + }, + { + "title": "Get inscription", + "description": "Retrieves a single inscription.", + "slug": "/bitcoin/api/ordinals/inscriptions/get-inscription", + "content": "\n" + }, + { + "title": "Status", + "description": "Retrieves information about the Ordinals API status, including the server version.", + "slug": "/bitcoin/api/ordinals/info/index", + "content": "" + }, + { + "title": "Get API status", + "description": "Retrieves the running status of the Ordinals API.", + "slug": "/bitcoin/api/ordinals/info/status", + "content": "\n" + }, + { + "title": "Satoshis", + "description": "Retrieves ordinal information for satoshis.", + "slug": "/bitcoin/api/ordinals/satoshis/index", + "content": "" + }, + { + "title": "Get satoshi ordinal", + "description": "Retrieves ordinal information for a single satoshi.", + "slug": "/bitcoin/api/ordinals/satoshis/get-satoshi", + "content": "\n" + }, + { + "title": "Get satoshi inscriptions", + "description": "Retrieves all inscriptions associated with a single satoshi.", + "slug": "/bitcoin/api/ordinals/satoshis/get-satoshi-inscriptions", + "content": "\n\n" + }, + { + "title": "APIs", + "description": "The following guides cover ways to use Hiro tools to build apps on Stacks.", + "slug": "/bitcoin/api/index", + "content": "\nimport { Database, Ticket } from 'lucide-react';\nimport { Blockchain, BitcoinIcon, Clarinet, Container, DAO, Js, Plant, Shapes, StacksIcon } from '@/components/ui/icon';\nimport { SecondaryCard, SmallCard } from '@/components/card';\n\n
\n\n\n }\n href=\"/stacks/chainhook/quickstart\"\n title=\"Stream custom blockchain events\"\n description=\"Use Chainhook to filter & stream for contract deployments.\"\n tag='Chainhook'\n />\n\n\n
\n\n

\n Learn by example\n

\n\n---\n\n\n }\n href=\"/guides/build-an-nft-marketplace\"\n title=\"Build an NFT Marketplace\"\n description=\"Learn how to create and deploy your own NFT marketplace.\"\n />\n {/* }\n href=\"/stacks/clarinet\"\n title=\"Launch a Decentralized Autonomous Organization (DAO)\"\n description=\"Discover the steps to creating your own DAO.\"\n /> */}\n }\n href=\"/guides/no-loss-lottery\"\n title=\"Create a no-loss lottery pool\"\n description=\"Build a no-loss lottery pool that leverages stacking yield.\"\n />\n }\n href=\"/guides/build-a-decentralized-kickstarter\"\n title=\"Build a decentralized Kickstarter\"\n description=\"Learn how to create a crowdfunding app, enabling creators to fund their projects without a third party.\"\n />\n\n\n
\n\n
\n\n

\n Installation guides\n

\n\n---\n\n\n }\n href=\"/guides/sync-a-bitcoin-node\"\n title=\"Sync a Bitcoin node\"\n description=\"Set up and run a Bitcoin node to run tools like Chainhook as a service.\"\n />\n }\n href=\"/guides/sync-a-stacks-node\"\n title=\"Sync a Stacks node\"\n description=\"Set up and run a Stacks node to use tools like Chainhook or spin up your own API.\"\n />\n }\n href=\"/guides/installing-docker\"\n title=\"Install and run Docker on your machine\"\n description=\"Essential for running a local development with Clarinet\"\n />\n\n\n
\n\n\nFor more, check out our [guides](/guides) section.\n\n\n
\n" + }, + { + "title": "Overview", + "description": "The Bitcoin Indexer enables you to build ordinals event streams, so you can create accurate, lightweight databases that gracefully handle Bitcoin forks and reorgs.", + "slug": "/bitcoin/indexer/index", + "content": "\nimport { SecondaryCard } from '@/components/card';\nimport { Step, Steps } from 'fumadocs-ui/components/steps';\n\nThe Bitcoin Indexer is a reorg-aware indexer that automatically handles chain forks, so you don't need to waste time or resources reindexing your database yourself.\n\nYou can customize what ordinals data you index in order to create lightweight databases for faster query responses and a better user experience.\n\n## Installation\n\n```terminal\n$ git clone https://github.com/hirosystems/bitcoin-indexer.git\n$ cd bitcoin-indexer\n$ cargo bitcoin-indexer-install\n```\n\nAlternatively, you can use Docker images from [Docker Hub](https://hub.docker.com/r/hirosystems/bitcoin-indexer).\n\n## Get started\n\n\n \n\n\n## System Requirements\n\nBefore running the indexer, ensure your system meets these requirements:\n\n- **CPU**: Multi-core support for parallel processing\n- **Memory**: Minimum 16GB RAM\n- **Storage**: SSD or NVMe recommended\n- **OS**: Support for 4096+ open file descriptors\n- **Postgres**: Version 17+ recommended\n\n## Related tools\n\n- **[Ordinals API](/bitcoin/ordinals/api)**: Skip the infrastructure setup and get the ordinals data you need from our Ordinals API, which is powered by the Bitcoin Indexer.\n- **[Ordinals Explorer](https://ordinals.hiro.so/)**: Explore ordinals inscriptions and BRC-20 tokens rapidly in our Ordinals Explorer.\n\n
\n\n\nReach out to us on the #indexer channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET.\n\n" + }, + { + "title": "TBD", + "description": "TBD", + "slug": "/bitcoin/indexer/guides/run-indexer", + "content": "\n" + }, + { + "title": "Quickstart", + "description": "Learn how to scan the Bitcoin blockchain for Ordinals activity.", + "slug": "/bitcoin/indexer/quickstart", + "content": "\nimport { Steps, Step } from 'fumadocs-ui/components/steps';\n\nIn this quickstart guide, you will set up the Bitcoin Indexer to index Ordinals or Runes activity on the Bitcoin blockchain.\n\n\n \n Clone the repository and install the indexer:\n ```terminal\n $ git clone https://github.com/hirosystems/bitcoin-indexer.git\n $ cd bitcoin-indexer\n $ cargo bitcoin-indexer-install\n ```\n \n\n \n Generate a new configuration file:\n ```terminal\n $ bitcoin-indexer config new\n ```\n \n Configure your Postgres database in the generated TOML file:\n ```toml\n [ordinals.db]\n database = \"metaprotocols\"\n host = \"localhost\"\n port = 5432\n username = \"postgres\"\n password = \"postgres\"\n ```\n \n\n \n Run the following command to start indexing Ordinals activity:\n ```terminal\n $ bitcoin-indexer ordinals service start --config-path \n ```\n \n For Runes indexing, use:\n ```terminal\n $ bitcoin-indexer runes service start --config-path \n ```\n \n\n\n\n A fully synced Bitcoin node is required for indexing to start.\n\n\n## Next steps\n\n\n \n \n \n" + }, + { + "title": "Quickstarts", + "description": "The following guides cover ways to use Hiro tools to build apps on Stacks.", + "slug": "/bitcoin/quickstarts/index", + "content": "\nimport { Database, Ticket } from 'lucide-react';\nimport { Blockchain, BitcoinIcon, Clarinet, Container, DAO, Js, Plant, Shapes, StacksIcon } from '@/components/ui/icon';\nimport { SecondaryCard, SmallCard } from '@/components/card';\n\n
\n\n\n }\n href=\"/stacks/clarinet/quickstart\"\n title=\"Create your first smart contract\"\n description=\"Build a simple counter contract using Clarinet.\"\n tag='Clarinet'\n />\n }\n href=\"/stacks/clarinet-js-sdk/quickstart\"\n title=\"Write unit tests for your smart contracts\"\n description=\"Learn how run unit tests with Clarinet JS SDK.\"\n tag='Clarinet JS SDK'\n />\n }\n href=\"/stacks/stacks.js/quickstart\"\n title=\"Make a contract call with Stacks.js\"\n description=\"Learn how to integrate smart contracts into your app.\"\n tag='Stacks.js'\n />\n }\n href=\"/stacks/chainhook/quickstart\"\n title=\"Stream custom blockchain events\"\n description=\"Use Chainhook to filter & stream for contract deployments.\"\n tag='Chainhook'\n />\n\n\n
\n\n

\n Learn by example\n

\n\n---\n\n\n }\n href=\"/guides/build-an-nft-marketplace\"\n title=\"Build an NFT Marketplace\"\n description=\"Learn how to create and deploy your own NFT marketplace.\"\n />\n {/* }\n href=\"/stacks/clarinet\"\n title=\"Launch a Decentralized Autonomous Organization (DAO)\"\n description=\"Discover the steps to creating your own DAO.\"\n /> */}\n }\n href=\"/guides/no-loss-lottery\"\n title=\"Create a no-loss lottery pool\"\n description=\"Build a no-loss lottery pool that leverages stacking yield.\"\n />\n }\n href=\"/guides/build-a-decentralized-kickstarter\"\n title=\"Build a decentralized Kickstarter\"\n description=\"Learn how to create a crowdfunding app, enabling creators to fund their projects without a third party.\"\n />\n\n\n
\n\n
\n\n

\n Installation guides\n

\n\n---\n\n\n }\n href=\"/guides/sync-a-bitcoin-node\"\n title=\"Sync a Bitcoin node\"\n description=\"Set up and run a Bitcoin node to run tools like Chainhook as a service.\"\n />\n }\n href=\"/guides/sync-a-stacks-node\"\n title=\"Sync a Stacks node\"\n description=\"Set up and run a Stacks node to use tools like Chainhook or spin up your own API.\"\n />\n }\n href=\"/guides/installing-docker\"\n title=\"Install and run Docker on your machine\"\n description=\"Essential for running a local development with Clarinet\"\n />\n\n\n
\n\n\nFor more, check out our [guides](/guides) section.\n\n\n
\n" + }, + { + "title": "Contributors guide", + "description": "Learn how to contribute to Hiro's documentation and content.", + "slug": "/guides/contributors-guide", + "content": "\nimport ContributorsGuideContent from '@/content/_shared/contributors-guide.mdx';\n\n\n" + }, + { + "title": "Rate limiting", + "description": "Understand the rate limits for Hiro APIs and the STX Faucet.", + "slug": "/guides/rate-limiting", + "content": "\nimport RateLimitingContent from '@/content/_shared/rate-limiting.mdx';\n\n\n" + }, + { + "title": "Home", + "description": "", + "slug": "/guides/index", + "content": "\nimport Link from \"fumadocs-core/link\";\nimport { ImageZoom } from 'fumadocs-ui/components/image-zoom';\nimport { SecondaryCard } from \"@/components/card\"\nimport guidesImage from '@/public/guides.svg';\nimport data from '@/lib/all-guides.json';\n\n
\n
\n \n
\n\n \n {data.guides.map(guide => {\n return (\n \n )\n })}\n \n
" + }, + { + "title": "How to sync a Stacks node", + "description": "Learn how to sync a Stacks node for running a local devnet or mainnet.", + "slug": "/guides/sync-a-stacks-node", + "content": "\nimport { Code, Terminal } from 'lucide-react';\nimport { SmallCard } from '@/components/card';\nimport { InlineCode } from '@/components/inline-code';\n\nRunning a Stacks node is crucial for developers aiming to interact directly with the Stacks blockchain. It allows for the verification of transactions, ensures decentralized operations, and enhances blockchain security.\n\nIn this guide, you will learn how to:\n\n1. [Clone the Stacks blockchain Docker repository](#clone-the-stacks-blockchain-docker-repository).\n2. [Start the service](#start-the-service).\n3. [Monitor the node's synchronization process](#monitor-the-nodes-synchronization-process).\n\n---\n\n## Clone the Stacks blockchain Docker repository\n\nClone the Stacks blockchain Docker repository from GitHub:\n\n```terminal\n$ git clone https://github.com/blockstack/stacks-blockchain-docker.git\n$ cd stacks-blockchain-docker\n```\n\n## Start the service\n\nInside of the `stacks-blockchain-docker` directory, run the following command to start the Stacks node:\n\n```terminal\n$ ./manage.sh -n -a start\n```\n\nThe `` placeholder used below can be replaced with one of:\n\n- `mainnet`\n- `testnet`\n- `mocknet`\n\n## Monitor the node's synchronization process\n\nTo follow the logs for the Stacks node, run the following command:\n\n```terminal\n$ ./manage.sh -n -a logs\n```\n\nFor networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data.\n\n---\n\n## Next steps\n\n\n \n \n\n" + }, + { + "title": "How to install Docker", + "description": "Install Docker to run a local devnet.", + "slug": "/guides/installing-docker", + "content": "\nimport { Tab, Tabs } from 'fumadocs-ui/components/tabs';\n\n\n \n 1. Go to the [Docker Desktop for Mac](https://www.docker.com/products/docker-desktop/) page.\n 2. Download the .dmg file.\n 3. Open the downloaded .dmg file.\n 4. Drag the Docker icon to the Applications folder.\n 5. Open Docker from the Applications folder.\n 6. Grant the necessary permissions if prompted.\n 7. Docker Desktop icon will appear in the menu bar indicating that Docker is running.\n \n To verify installation, run `docker --version` in your terminal. You should see the Docker version information.\n \n \n \n 1. Go to the [Docker Desktop for Windows](https://www.docker.com/products/docker-desktop/) page.\n 2. Download the executable.\n 3. Run the downloaded executable.\n 4. Follow the installation wizard steps (you may need to restart your computer).\n 5. Ensure the WSL 2 (Windows Subsystem for Linux) backend is checked during installation, if applicable.\n 6. Open Docker Desktop from the Start menu.\n 7. Grant the necessary permissions if prompted.\n 8. Docker icon will appear in the system tray indicating Docker is running.\n\n To verify installation, run `docker --version` in your terminal. You should see the Docker version information.\n \n \n You might need to install additional Windows components like Hyper-V or WSL 2.\n \n \n\n\n---\n\n## Next steps\n\n\n \n \n" + }, + { + "title": "Build a decentralized Kickstarter", + "description": "Learn how to create a crowdfunding app, enabling creators to fund their projects without a third party.", + "slug": "/guides/build-a-decentralized-kickstarter", + "content": "\nimport { Code, Terminal } from 'lucide-react';\nimport { SmallCard } from '@/components/card';\n\nIn this guide, you will learn how to create an NFT marketplace that allows users to list NFTs for sale. Users can specify the following details for their listings:\n- The NFT token to sell.\n- Listing expiry in block height.\n- The payment asset, either STX or a SIP010 fungible token.\n- The NFT price in the chosen payment asset.\n- An optional intended taker. If set, only that principal will be able to fulfil the listing.\n\nThis marketplace leverages the following Clarity traits:\n- `nft-trait` for handling NFTs.\n- `ft-trait` for handling fungible tokens.\n\nOver the course of this guide, you will learn how to:\n1. Define and handle errors.\n2. Create and manage NFT listings.\n3. Whitelist asset contracts.\n4. Fulfil NFT purchases.\n\n---\n\n## Define and handle errors\n\nFirst, define constants for various errors that may occur during listing, cancelling, or fulfilling NFT transactions. This helps in maintaining clean and readable code.\n\n```clarity\n;; Define listing errors\n(define-constant ERR_EXPIRY_IN_PAST (err u1000))\n(define-constant ERR_PRICE_ZERO (err u1001))\n\n;; Define cancelling and fulfilling errors\n(define-constant ERR_UNKNOWN_LISTING (err u2000))\n(define-constant ERR_UNAUTHORISED (err u2001))\n(define-constant ERR_LISTING_EXPIRED (err u2002))\n(define-constant ERR_NFT_ASSET_MISMATCH (err u2003))\n(define-constant ERR_PAYMENT_ASSET_MISMATCH (err u2004))\n(define-constant ERR_MAKER_TAKER_EQUAL (err u2005))\n(define-constant ERR_UNINTENDED_TAKER (err u2006))\n(define-constant ERR_ASSET_CONTRACT_NOT_WHITELISTED (err u2007))\n(define-constant ERR_PAYMENT_CONTRACT_NOT_WHITELISTED (err u2008))\n```\n\n## Create and manage NFT listings\n\n### Define data structures\n\nCreate a map data structure for the asset listings and a data variable for unique IDs.\n\n```clarity\n;; Define a map data structure for the asset listings\n(define-map listings\n uint\n {\n maker: principal,\n taker: (optional principal),\n token-id: uint,\n nft-asset-contract: principal,\n expiry: uint,\n price: uint,\n payment-asset-contract: (optional principal)\n }\n)\n\n;; Used for unique IDs for each listing\n(define-data-var listing-nonce uint u0)\n```\n\n### List an asset\n\nCreate a public function to list an asset along with its contract. This function verifies the contract, checks expiry and price, and transfers the NFT ownership to the marketplace.\n\n```clarity\n(define-public (list-asset\n (nft-asset-contract )\n (nft-asset {\n taker: (optional principal),\n token-id: uint,\n expiry: uint,\n price: uint,\n payment-asset-contract: (optional principal)\n })\n)\n (let ((listing-id (var-get listing-nonce)))\n ;; Verify that the contract of this asset is whitelisted\n (asserts! (is-whitelisted (contract-of nft-asset-contract)) ERR_ASSET_CONTRACT_NOT_WHITELISTED)\n ;; Verify that the asset is not expired\n (asserts! (> (get expiry nft-asset) block-height) ERR_EXPIRY_IN_PAST)\n ;; Verify that the asset price is greater than zero\n (asserts! (> (get price nft-asset) u0) ERR_PRICE_ZERO)\n ;; Verify that the contract of the payment is whitelisted\n (asserts! (match (get payment-asset-contract nft-asset)\n payment-asset\n (is-whitelisted payment-asset)\n true\n ) ERR_PAYMENT_CONTRACT_NOT_WHITELISTED)\n ;; Transfer the NFT ownership to this contract's principal\n (try! (transfer-nft\n nft-asset-contract\n (get token-id nft-asset)\n tx-sender\n (as-contract tx-sender)\n ))\n ;; List the NFT in the listings map\n (map-set listings listing-id (merge\n { maker: tx-sender, nft-asset-contract: (contract-of nft-asset-contract) }\n nft-asset\n ))\n ;; Increment the nonce to use for the next unique listing ID\n (var-set listing-nonce (+ listing-id u1))\n ;; Return the created listing ID\n (ok listing-id)\n )\n)\n```\n\n### Retrieve an asset\n\nCreate a read-only function to retrieve an asset, or listing, by its ID.\n\n```clarity\n(define-read-only (get-listing (listing-id uint))\n (map-get? listings listing-id)\n)\n```\n\n### Cancel a listing\n\nCreate a public function to cancel a listing. Only the NFT's creator can cancel the listing, and it must use the same asset contract that the NFT uses.\n\n```clarity\n(define-public (cancel-listing (listing-id uint) (nft-asset-contract ))\n (let (\n (listing (unwrap! (map-get? listings listing-id) ERR_UNKNOWN_LISTING))\n (maker (get maker listing))\n )\n ;; Verify that the caller of the function is the creator of the NFT to be cancelled\n (asserts! (is-eq maker tx-sender) ERR_UNAUTHORISED)\n ;; Verify that the asset contract to use is the same one that the NFT uses\n (asserts! (is-eq\n (get nft-asset-contract listing)\n (contract-of nft-asset-contract)\n ) ERR_NFT_ASSET_MISMATCH)\n ;; Delete the listing\n (map-delete listings listing-id)\n ;; Transfer the NFT from this contract's principal back to the creator's principal\n (as-contract (transfer-nft nft-asset-contract (get token-id listing) tx-sender maker))\n )\n)\n```\n\n## Whitelist asset contracts\n\n### Whitelist contracts\n\nThe marketplace requires any contracts used for assets or payments to be whitelisted by the contract owner. Create a map to store whitelisted asset contracts and a function to check if a contract is whitelisted.\n\n```clarity\n(define-map whitelisted-asset-contracts principal bool)\n\n(define-read-only (is-whitelisted (asset-contract principal))\n (default-to false (map-get? whitelisted-asset-contracts asset-contract))\n)\n```\n\n### Set whitelisted contracts\n\nOnly the contract owner can whitelist an asset contract. Create a public function to set whitelisted asset contracts.\n\n```clarity\n(define-public (set-whitelisted (asset-contract principal) (whitelisted bool))\n (begin\n (asserts! (is-eq contract-owner tx-sender) ERR_UNAUTHORISED)\n (ok (map-set whitelisted-asset-contracts asset-contract whitelisted))\n )\n)\n```\n\n## Fulfill NFT purchases\n\n### Fulfill listing with STX\n\nCreate a public function to purchase a listing using STX as payment.\n\n```clarity\n(define-public (fulfil-listing-stx (listing-id uint) (nft-asset-contract ))\n (let (\n ;; Verify the given listing ID exists\n (listing (unwrap! (map-get? listings listing-id) ERR_UNKNOWN_LISTING))\n ;; Set the NFT's taker to the purchaser (caller of the function)\n (taker tx-sender)\n )\n ;; Validate that the purchase can be fulfilled\n (try! (assert-can-fulfil (contract-of nft-asset-contract) none listing))\n ;; Transfer the NFT to the purchaser (caller of the function)\n (try! (as-contract (transfer-nft nft-asset-contract (get token-id listing) tx-sender taker)))\n ;; Transfer the STX payment from the purchaser to the creator of the NFT\n (try! (stx-transfer? (get price listing) taker (get maker listing)))\n ;; Remove the NFT from the marketplace listings\n (map-delete listings listing-id)\n ;; Return the listing ID that was just purchased\n (ok listing-id)\n )\n)\n```\n\n### Fulfill listing with SIP-010\n\nCreate a public function to purchase a listing using another fungible token that follows the SIP-010 standard as payment.\n\n```clarity\n(define-public (fulfil-listing-ft\n (listing-id uint)\n (nft-asset-contract )\n (payment-asset-contract )\n)\n (let (\n ;; Verify the given listing ID exists\n (listing (unwrap! (map-get? listings listing-id) ERR_UNKNOWN_LISTING))\n ;; Set the NFT's taker to the purchaser (caller of the function)\n (taker tx-sender)\n )\n ;; Validate that the purchase can be fulfilled\n (try! (assert-can-fulfil\n (contract-of nft-asset-contract)\n (some (contract-of payment-asset-contract))\n listing\n ))\n ;; Transfer the NFT to the purchaser (caller of the function)\n (try! (as-contract (transfer-nft nft-asset-contract (get token-id listing) tx-sender taker)))\n ;; Transfer the tokens as payment from the purchaser to the creator of the NFT\n (try! (transfer-ft payment-asset-contract (get price listing) taker (get maker listing)))\n ;; Remove the NFT from the marketplace listings\n (map-delete listings listing-id)\n ;; Return the listing ID that was just purchased\n (ok listing-id)\n )\n)\n```\n\n### Validate purchase can be fulfilled\n\nCreate a private function to validate that a purchase can be fulfilled. This function checks the listing's expiry, the NFT's contract, and the payment's contract.\n\n```clarity\n(define-private (assert-can-fulfil\n (nft-asset-contract principal)\n (payment-asset-contract (optional principal))\n (listing {\n maker: principal,\n taker: (optional principal),\n token-id: uint,\n nft-asset-contract: principal,\n expiry: uint,\n price: uint,\n payment-asset-contract: (optional principal)\n })\n)\n (begin\n ;; Verify that the buyer is not the same as the NFT creator\n (asserts! (not (is-eq (get maker listing) tx-sender)) ERR_MAKER_TAKER_EQUAL)\n ;; Verify the buyer has been set in the listing metadata as its `taker`\n (asserts!\n (match (get taker listing) intended-taker (is-eq intended-taker tx-sender) true)\n ERR_UNINTENDED_TAKER\n )\n ;; Verify the listing for purchase is not expired\n (asserts! (< block-height (get expiry listing)) ERR_LISTING_EXPIRED)\n ;; Verify the asset contract used to purchase the NFT is the same as the one set on the NFT\n (asserts! (is-eq (get nft-asset-contract listing) nft-asset-contract) ERR_NFT_ASSET_MISMATCH)\n ;; Verify the payment contract used to purchase the NFT is the same as the one set on the NFT\n (asserts!\n (is-eq (get payment-asset-contract listing) payment-asset-contract)\n ERR_PAYMENT_ASSET_MISMATCH\n )\n (ok true)\n )\n)\n```\n\nBy following this guide, you have created a basic NFT marketplace that allows users to list, buy, and sell NFTs using either STX or fungible tokens. This implementation includes essential functionalities such as whitelisting contracts, validating transactions, and handling errors.\n\n---\n\n## Next steps\n\n\n \n \n" + }, + { + "title": "API keys", + "description": "For developers who need API requests beyond the standard rate limits.", + "slug": "/guides/api-keys", + "content": "\nimport ApiKeysContent from '@/content/_shared/api-keys.mdx';\n\n\n" + }, + { + "title": "Build an NFT marketplace", + "description": "Learn how to create an NFT marketplace that allows users to list NFTs for sale and purchase them using Clarity.", + "slug": "/guides/build-an-nft-marketplace", + "content": "\nimport { Code, Terminal } from 'lucide-react';\nimport { SmallCard } from '@/components/card';\n\nIn this guide, you will learn how to create an NFT marketplace that allows users to list NFTs for sale. Users can specify the following details for their listings:\n- The NFT token to sell.\n- Listing expiry in block height.\n- The payment asset, either STX or a SIP010 fungible token.\n- The NFT price in the chosen payment asset.\n- An optional intended taker. If set, only that principal will be able to fulfil the listing.\n\nThis marketplace leverages the following Clarity traits:\n- `nft-trait` for handling NFTs.\n- `ft-trait` for handling fungible tokens.\n\nOver the course of this guide, you will learn how to:\n1. Define and handle errors.\n2. Create and manage NFT listings.\n3. Whitelist asset contracts.\n4. Fulfil NFT purchases.\n\n---\n\n## Define and handle errors\n\nFirst, define constants for various errors that may occur during listing, cancelling, or fulfilling NFT transactions. This helps in maintaining clean and readable code.\n\n```clarity\n;; Define listing errors\n(define-constant ERR_EXPIRY_IN_PAST (err u1000))\n(define-constant ERR_PRICE_ZERO (err u1001))\n\n;; Define cancelling and fulfilling errors\n(define-constant ERR_UNKNOWN_LISTING (err u2000))\n(define-constant ERR_UNAUTHORISED (err u2001))\n(define-constant ERR_LISTING_EXPIRED (err u2002))\n(define-constant ERR_NFT_ASSET_MISMATCH (err u2003))\n(define-constant ERR_PAYMENT_ASSET_MISMATCH (err u2004))\n(define-constant ERR_MAKER_TAKER_EQUAL (err u2005))\n(define-constant ERR_UNINTENDED_TAKER (err u2006))\n(define-constant ERR_ASSET_CONTRACT_NOT_WHITELISTED (err u2007))\n(define-constant ERR_PAYMENT_CONTRACT_NOT_WHITELISTED (err u2008))\n```\n\n## Create and manage NFT listings\n\n### Define data structures\n\nCreate a map data structure for the asset listings and a data variable for unique IDs.\n\n```clarity\n;; Define a map data structure for the asset listings\n(define-map listings\n uint\n {\n maker: principal,\n taker: (optional principal),\n token-id: uint,\n nft-asset-contract: principal,\n expiry: uint,\n price: uint,\n payment-asset-contract: (optional principal)\n }\n)\n\n;; Used for unique IDs for each listing\n(define-data-var listing-nonce uint u0)\n```\n\n### List an asset\n\nCreate a public function to list an asset along with its contract. This function verifies the contract, checks expiry and price, and transfers the NFT ownership to the marketplace.\n\n```clarity\n(define-public (list-asset\n (nft-asset-contract )\n (nft-asset {\n taker: (optional principal),\n token-id: uint,\n expiry: uint,\n price: uint,\n payment-asset-contract: (optional principal)\n })\n)\n (let ((listing-id (var-get listing-nonce)))\n ;; Verify that the contract of this asset is whitelisted\n (asserts! (is-whitelisted (contract-of nft-asset-contract)) ERR_ASSET_CONTRACT_NOT_WHITELISTED)\n ;; Verify that the asset is not expired\n (asserts! (> (get expiry nft-asset) block-height) ERR_EXPIRY_IN_PAST)\n ;; Verify that the asset price is greater than zero\n (asserts! (> (get price nft-asset) u0) ERR_PRICE_ZERO)\n ;; Verify that the contract of the payment is whitelisted\n (asserts! (match (get payment-asset-contract nft-asset)\n payment-asset\n (is-whitelisted payment-asset)\n true\n ) ERR_PAYMENT_CONTRACT_NOT_WHITELISTED)\n ;; Transfer the NFT ownership to this contract's principal\n (try! (transfer-nft\n nft-asset-contract\n (get token-id nft-asset)\n tx-sender\n (as-contract tx-sender)\n ))\n ;; List the NFT in the listings map\n (map-set listings listing-id (merge\n { maker: tx-sender, nft-asset-contract: (contract-of nft-asset-contract) }\n nft-asset\n ))\n ;; Increment the nonce to use for the next unique listing ID\n (var-set listing-nonce (+ listing-id u1))\n ;; Return the created listing ID\n (ok listing-id)\n )\n)\n```\n\n### Retrieve an asset\n\nCreate a read-only function to retrieve an asset, or listing, by its ID.\n\n```clarity\n(define-read-only (get-listing (listing-id uint))\n (map-get? listings listing-id)\n)\n```\n\n### Cancel a listing\n\nCreate a public function to cancel a listing. Only the NFT's creator can cancel the listing, and it must use the same asset contract that the NFT uses.\n\n```clarity\n(define-public (cancel-listing (listing-id uint) (nft-asset-contract ))\n (let (\n (listing (unwrap! (map-get? listings listing-id) ERR_UNKNOWN_LISTING))\n (maker (get maker listing))\n )\n ;; Verify that the caller of the function is the creator of the NFT to be cancelled\n (asserts! (is-eq maker tx-sender) ERR_UNAUTHORISED)\n ;; Verify that the asset contract to use is the same one that the NFT uses\n (asserts! (is-eq\n (get nft-asset-contract listing)\n (contract-of nft-asset-contract)\n ) ERR_NFT_ASSET_MISMATCH)\n ;; Delete the listing\n (map-delete listings listing-id)\n ;; Transfer the NFT from this contract's principal back to the creator's principal\n (as-contract (transfer-nft nft-asset-contract (get token-id listing) tx-sender maker))\n )\n)\n```\n\n## Whitelist asset contracts\n\n### Whitelist contracts\n\nThe marketplace requires any contracts used for assets or payments to be whitelisted by the contract owner. Create a map to store whitelisted asset contracts and a function to check if a contract is whitelisted.\n\n```clarity\n(define-map whitelisted-asset-contracts principal bool)\n\n(define-read-only (is-whitelisted (asset-contract principal))\n (default-to false (map-get? whitelisted-asset-contracts asset-contract))\n)\n```\n\n### Set whitelisted contracts\n\nOnly the contract owner can whitelist an asset contract. Create a public function to set whitelisted asset contracts.\n\n```clarity\n(define-public (set-whitelisted (asset-contract principal) (whitelisted bool))\n (begin\n (asserts! (is-eq contract-owner tx-sender) ERR_UNAUTHORISED)\n (ok (map-set whitelisted-asset-contracts asset-contract whitelisted))\n )\n)\n```\n\n## Fulfill NFT purchases\n\n### Fulfill listing with STX\n\nCreate a public function to purchase a listing using STX as payment.\n\n```clarity\n(define-public (fulfil-listing-stx (listing-id uint) (nft-asset-contract ))\n (let (\n ;; Verify the given listing ID exists\n (listing (unwrap! (map-get? listings listing-id) ERR_UNKNOWN_LISTING))\n ;; Set the NFT's taker to the purchaser (caller of the function)\n (taker tx-sender)\n )\n ;; Validate that the purchase can be fulfilled\n (try! (assert-can-fulfil (contract-of nft-asset-contract) none listing))\n ;; Transfer the NFT to the purchaser (caller of the function)\n (try! (as-contract (transfer-nft nft-asset-contract (get token-id listing) tx-sender taker)))\n ;; Transfer the STX payment from the purchaser to the creator of the NFT\n (try! (stx-transfer? (get price listing) taker (get maker listing)))\n ;; Remove the NFT from the marketplace listings\n (map-delete listings listing-id)\n ;; Return the listing ID that was just purchased\n (ok listing-id)\n )\n)\n```\n\n### Fulfill listing with SIP-010\n\nCreate a public function to purchase a listing using another fungible token that follows the SIP-010 standard as payment.\n\n```clarity\n(define-public (fulfil-listing-ft\n (listing-id uint)\n (nft-asset-contract )\n (payment-asset-contract )\n)\n (let (\n ;; Verify the given listing ID exists\n (listing (unwrap! (map-get? listings listing-id) ERR_UNKNOWN_LISTING))\n ;; Set the NFT's taker to the purchaser (caller of the function)\n (taker tx-sender)\n )\n ;; Validate that the purchase can be fulfilled\n (try! (assert-can-fulfil\n (contract-of nft-asset-contract)\n (some (contract-of payment-asset-contract))\n listing\n ))\n ;; Transfer the NFT to the purchaser (caller of the function)\n (try! (as-contract (transfer-nft nft-asset-contract (get token-id listing) tx-sender taker)))\n ;; Transfer the tokens as payment from the purchaser to the creator of the NFT\n (try! (transfer-ft payment-asset-contract (get price listing) taker (get maker listing)))\n ;; Remove the NFT from the marketplace listings\n (map-delete listings listing-id)\n ;; Return the listing ID that was just purchased\n (ok listing-id)\n )\n)\n```\n\n### Validate purchase can be fulfilled\n\nCreate a private function to validate that a purchase can be fulfilled. This function checks the listing's expiry, the NFT's contract, and the payment's contract.\n\n```clarity\n(define-private (assert-can-fulfil\n (nft-asset-contract principal)\n (payment-asset-contract (optional principal))\n (listing {\n maker: principal,\n taker: (optional principal),\n token-id: uint,\n nft-asset-contract: principal,\n expiry: uint,\n price: uint,\n payment-asset-contract: (optional principal)\n })\n)\n (begin\n ;; Verify that the buyer is not the same as the NFT creator\n (asserts! (not (is-eq (get maker listing) tx-sender)) ERR_MAKER_TAKER_EQUAL)\n ;; Verify the buyer has been set in the listing metadata as its `taker`\n (asserts!\n (match (get taker listing) intended-taker (is-eq intended-taker tx-sender) true)\n ERR_UNINTENDED_TAKER\n )\n ;; Verify the listing for purchase is not expired\n (asserts! (< block-height (get expiry listing)) ERR_LISTING_EXPIRED)\n ;; Verify the asset contract used to purchase the NFT is the same as the one set on the NFT\n (asserts! (is-eq (get nft-asset-contract listing) nft-asset-contract) ERR_NFT_ASSET_MISMATCH)\n ;; Verify the payment contract used to purchase the NFT is the same as the one set on the NFT\n (asserts!\n (is-eq (get payment-asset-contract listing) payment-asset-contract)\n ERR_PAYMENT_ASSET_MISMATCH\n )\n (ok true)\n )\n)\n```\n\nBy following this guide, you have created a basic NFT marketplace that allows users to list, buy, and sell NFTs using either STX or fungible tokens. This implementation includes essential functionalities such as whitelisting contracts, validating transactions, and handling errors.\n\n---\n\n## Next steps\n\n\n \n \n" + }, + { + "title": "Using Clarity values", + "description": "Learn how to use Clarity values in your Clarity smart contracts.", + "slug": "/guides/using-clarity-values", + "content": "\nSome endpoints, like the [read-only function contract call](https://docs.hiro.so/api#operation/call_read_only_function), require input to a serialized [Clarity value](https://docs.stacks.co/docs/clarity/). Other endpoints return serialized values that need to be deserialized.\n\nThe example shown below illustrates Clarity value usage in combination with the API.\n\nThe `@stacks/transactions` library supports typed contract calls and makes [response value utilization much simpler](https://docs.stacks.co/docs/clarity/).\n\n```ts\nimport {\n Configuration,\n SmartContractsApiInterface,\n SmartContractsApi,\n ReadOnlyFunctionSuccessResponse,\n} from '@stacks/blockchain-api-client';\nimport { uintCV, UIntCV, cvToHex, hexToCV, ClarityType } from '@stacks/transactions';\n\n(async () => {\n const apiConfig: Configuration = new Configuration({\n fetchApi: fetch,\n // for mainnet, replace `testnet` with `mainnet`\n basePath: 'https://api.testnet.hiro.so', // defaults to http://localhost:3999\n });\n\n const contractsApi: SmartContractsApiInterface = new SmartContractsApi(apiConfig);\n\n const principal: string = 'ST000000000000000000002AMW42H';\n\n // use most recent from: https://api..hiro.so/v2/pox\n const rewardCycle: UIntCV = uintCV(22);\n\n // call a read-only function\n const fnCall: ReadOnlyFunctionSuccessResponse = await contractsApi.callReadOnlyFunction({\n contractAddress: principal,\n contractName: 'pox',\n functionName: 'is-pox-active',\n readOnlyFunctionArgs: {\n sender: principal,\n arguments: [cvToHex(rewardCycle)],\n },\n });\n\n console.log({\n status: fnCall.okay,\n result: fnCall.result,\n representation: hexToCV(fnCall.result).type === ClarityType.BoolTrue,\n });\n})().catch(console.error);\n```" + }, + { + "title": "How to sync a Bitcoin node", + "description": "Learn how to sync a Bitcoin node for building Bitcoin applications.", + "slug": "/guides/sync-a-bitcoin-node", + "content": "\nimport { InlineCode } from '@/components/inline-code';\nimport { Accordion, Accordions } from 'fumadocs-ui/components/accordion';\nimport { Tab, Tabs } from 'fumadocs-ui/components/tabs';\n\nSyncing a Bitcoin node is often one of the first steps a developer takes when building a Bitcoin application. It's a great introduction to the Bitcoin developer ecosystem, and if you're relying on on-chain data, there's no safer way to get that data than doing it yourself.\n\nIn this guide, you will learn how to:\n\n1. Download Bitcoin Core daemon on your machine\n2. Configure `bitcoind`\n3. Start syncing your node\n4. Properly shutdown and restart your node\n\n\nTo get started, we first need to download `bitcoind`. In our example, we'll be using version 25.0. You can select a software version compatible with your device [from this list](https://bitcoincore.org/bin/bitcoin-core-25.0). \n\n\n---\n\n## Configure bitcoind\n\nOnce your download is complete, make note of your path to the `bitcoind` executable.\n\n\nWhen you sync your node, we'll be running the program at `/bitcoin-25.0/bin/bitcoin`, which is where the `bitcoind` executable is located.\n\n\nNext up is a couple configuration steps.\n\n1. Select or create a directory to store your Bitcoin data.\n2. Update the `bitcoin.conf` file to include the path to your Bitcoin data directory.\n\nThe Bitcoin chainstate is pretty large, and you need a place to store it. In this example, we are going to set up a directory called `bitcoin-data` on an external hard drive that we have mounted at `/Volumes/SSD`.\n\n\n This folder, `bitcoin-data`, can be named whatever you like, and can exist locally or in an external hard drive.\n \n The most important thing is that it should exist in a place that has enough storage to hold all the Bitcoin data we will be receiving once it starts to sync.\n\n\nNow navigate to your `bitcoin.conf` file, which is located in your `/path/to/bitcoin` directory and update the `datadir` field with your directory. \n\nIn this example, it would look like this:\n\n```bash bitcoin.conf\ndatadir=/Volumes/SSD/bitcoin-data/\n```\n\n\n\nYou can override the default configuration with the following, including the path to where you will be storing all of the Bitcoin data once it starts syncing:\n\n```bash\ndatadir=/your-path-to/bitcoin-data/\nserver=1\nrpcuser=devnet\nrpcpassword=devnet\nrpcport=8332\nrpcallowip=0.0.0.0/0\nrpcallowip=::/0\ntxindex=1\nlisten=1\ndiscover=0\ndns=0\ndnsseed=0\nlistenonion=0\nrpcserialversion=1\ndisablewallet=0\nfallbackfee=0.00001\nrpcthreads=8\nblocksonly=1\ndbcache=4096\n\n# Start zeromq\nzmqpubhashblock=tcp://0.0.0.0:18543\n```\n\n\n\nIf you plan to use your node to receive transactions, you will need to make note of the `username` and `password` fields for your node.\n\n\nIn the example `bitcoin.conf` above, `devnet` is listed as the default `username` and `password`.\n\n\n## Run the node\n\nWith a finished `bitcoin.conf` file, it's time to start up your node.\n\nThis takes the form of `path/to/bitcoind -conf=path/to/bitcoin.conf`, which in this example looks like:\n\n```terminal\n$ /Volumes/SSD/bitcoin-25.0/bin/bitcoind -conf=/Volumes/SSD/bitcoin-25.0/bitcoin.conf\n```\n\nAfter running this command, you will see `zmq_url` entries in your console's stdout, displaying ZeroMQ logs from your Bitcoin node. Congrats! You're now syncing!\n\n\nIt might take anywhere from a few hours to a few days to run and fully sync, depending on if it's your first time syncing a node.\n\n\n## Proper shutdown and restart procedure\n\n1. Shutting down your node\n2. Restarting your node\n\nTo shut down your node safely, use the `bitcoin-cli` executable, located inside of the `bin` directory, and run the `stop` command:\n\n```terminal\n$ /path/to/bitcoin-cli \\\n --conf=/path/to/bitcoin.conf \\\n --rpcuser={{your-rpc-username}} \\\n --rpcpassword={{your-rpc-password}} stop\n```\n\nTo start your node back up, all you need to do is refer to the previous steps from above by running `path/to/bitcoind -conf=path/to/bitcoin.conf`.\n\n\n \n \n 1. Go to the Finder, then the sidebar, and select the disk you want to eject under “Devices”. Click on the eject icon next to the name.\n 2. Wait for a confirmation message saying it's safe to eject the device before you unplug the drive.\n \n\n \n 1. Open File Explorer, select the drive from the list under “This PC” (PC > Devices and Drives), and click the “Eject” button.\n 2. Wait for a confirmation message saying it's safe to eject the device before you unplug the drive.\n \n \n\n\n---\n\n## Next steps\n\n\n \n \n\n" + }, + { + "title": "Build a no-loss lottery pool", + "description": "Learn how to create a no-loss lottery pool that leverages stacking yield.", + "slug": "/guides/no-loss-lottery", + "content": "\nimport { Code, Terminal } from 'lucide-react';\n\nA no-loss lottery contract offers a unique way for participants to stack their assets and potentially earn a larger reward without the risk of losing their initial deposit.\n\nThis contract ensures that participants can stack their assets in a yield-generating pool, receive an NFT ticket, and have a chance to win additional rewards while retaining their original investment.\n\nIn this guide, you will learn how to:\n\n1. Define constants and data variables\n2. Create and manage participants and tickets\n3. Implement the lottery functionality\n4. Handle the selection of winners\n5. Claim and distribute rewards\n\n\nThis example uses the CityCoins protocol for the stacking yield mechanism, but leveraging a Stacking pool using Proof of Transfer (PoX4) can also be used.\n\n\n---\n\n## Define constants and data variables\n\nFirst, define some constants and data variables to manage the state of your contract. Constants are used for fixed values, and data variables store the state that can change during the contract execution.\n\n```clarity\n(define-constant OWNER tx-sender)\n(define-constant ERR_UNAUTHORIZED (err u101000))\n\n(define-data-var lotteryPool uint u0)\n(define-data-var totalYield uint u0)\n(define-data-var ticketCounter uint u0)\n```\n\nThe `OWNER` constant defines the contract owner with administrative privileges, while `ERR_UNAUTHORIZED` handles unauthorized access attempts.\n\nKey data variables include `lotteryPool` for tracking stacked assets, `totalYield` for accumulated earnings, and `ticketCounter` for managing issued tickets.\n\n## Create and manage participants and tickets\n\nNext, define an NFT to represent a ticket and a map to store participant information.\n\n```clarity\n(define-map Participants\n { participant: principal }\n { ticketId: uint, amount: uint, cycle: uint, ticketExpirationAtCycle: uint, isWinner: bool }\n)\n\n(define-map Tickets\n { ticketId: uint }\n { owner: principal }\n)\n\n(define-non-fungible-token LotteryTicket uint)\n```\n\nThe `Participants` map links participants to their ticket details, while the `Tickets` map associates tickets with their owners.\n\nThe `LotteryTicket` defines an NFT for the lottery tickets, crucial for managing entries.\n\n## Implement the lottery functionality\n\nNow, it's time to implement the core function of the contract, where participants can enter the lottery by depositing their assets.\n\n```clarity\n(define-public (roll-the-dice (cityName (string-ascii 10)) (amount uint) (lockPeriod (optional uint)))\n (let\n (\n (ticketId (+ (var-get ticketCounter) u1))\n (actualLockPeriod (default-to u1 lockPeriod))\n (rewardCycle (+ (contract-call? 'SP8A9HZ3PKST0S42VM9523Z9NV42SZ026V4K39WH.ccd007-citycoin-stacking get-current-reward-cycle) u1))\n )\n\n (begin\n (try! (contract-call? 'SP1H1733V5MZ3SZ9XRW9FKYGEZT0JDGEB8Y634C7R.miamicoin-token-v2 transfer amount tx-sender (as-contract tx-sender) none))\n (try! (nft-mint? LotteryTicket ticketId tx-sender))\n (map-insert Participants { participant: tx-sender } { ticketId: ticketId, amount: amount, cycle: rewardCycle, ticketExpirationAtCycle: (+ rewardCycle actualLockPeriod), isWinner: false })\n (map-set Tickets { ticketId: ticketId } { owner: tx-sender })\n (var-set lotteryPool (+ (var-get lotteryPool) amount))\n (var-set ticketCounter (+ (var-get ticketCounter) u1))\n (ok ticketId)\n )\n )\n)\n```\n\nThe `roll-the-dice` function enables participants to join the lottery by depositing assets, specifying the city (`cityName`), the deposit amount (`amount`), and the lock period (`lockPeriod`).\n\nThis function is crucial for managing lottery entries and ensuring assets are properly locked for the specified duration.\n\nWhen a participant calls this function, the following steps occur:\n\n1. **Generate ticket and determine lock period**: A new ticket ID is generated, and the lock period is set (defaulting to 1 if not specified).\n2. **Transfer assets and mint NFT ticket**: The specified amount of assets is transferred from the participant to the contract, and an NFT representing the lottery ticket is minted and assigned to the participant.\n3. **Update participant and ticket data**: The participant's information, including ticket ID, amount, cycle, and expiration, is stored, and the ticket's ownership information is updated.\n4. **Update lottery pool and return ticket ID**: The total amount in the lottery pool is updated, the ticket counter is incremented, and the function returns the newly generated ticket ID to the participant.\n\nThis streamlined process ensures that each participant's entry is properly recorded and their assets are securely managed within the lottery system.\n\n## Handling the selection of winners\n\nNow, implement the function to select a winner randomly from the participants.\n\n```clarity\n(define-private (select-winner)\n (match (contract-call? 'SPSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1F4DYQ11.citycoin-vrf-v2 get-save-rnd (- block-height u1)) randomTicketNumber\n (let\n (\n (ticketCount (var-get ticketCounter))\n (winningTicketId (mod randomTicketNumber ticketCount))\n (winner (unwrap! (get-ticket winningTicketId) (err u404)))\n (owner (get owner winner))\n (participant (unwrap! (get-participant owner) (err u404)))\n )\n (map-set Participants { participant: owner }\n { ticketId: winningTicketId, amount: (get amount participant), cycle: (get cycle participant), ticketExpirationAtCycle: (get ticketExpirationAtCycle participant), isWinner: true })\n (ok owner)\n )\n selectionError (err selectionError)\n )\n)\n```\nThe `select-winner` function randomly selects a winner using a number from the VRF contract (`get-save-rnd`) and updates their status with `unwrap!`. This ensures a fair and transparent winner selection process.\n\nWhen this function is called, the following steps occur:\n\n1. **Fetch random number**: A random number is obtained from the VRF contract by calling `get-save-rnd` with the previous block height.\n2. **Determine winning ticket**: The winning ticket ID is calculated by taking the modulus of the random number with the total number of tickets (`ticketCounter`).\n3. **Retrieve winner information**: The winner's ticket and participant information are retrieved using the calculated ticket ID.\n4. **Update winner status**: The participant's status is updated to indicate they are a winner by setting `isWinner` to `true` in the `Participants` map.\n\nThis process ensures that the winner is selected fairly and their status is accurately updated in the system.\n\n## Claim and distribute rewards\n\nLastly, implement the function to claim and distribute rewards to the winners.\n\n```clarity\n(define-public (claim-rewards (cityName (string-ascii 10)) (cycle uint))\n (let\n (\n (cityId (unwrap-panic (contract-call? 'SP8A9HZ3PKST0S42VM9523Z9NV42SZ026V4K39WH.ccd004-city-registry get-city-id cityName)))\n (cycleAmount (contract-call? 'SP8A9HZ3PKST0S42VM9523Z9NV42SZ026V4K39WH.ccd002-treasury-mia-stacking get-balance-stx))\n )\n (if (is-eq cityName \"mia\")\n (try! (contract-call? 'SP8A9HZ3PKST0S42VM9523Z9NV42SZ026V4K39WH.ccd011-stacking-payouts send-stacking-reward-mia cycle cycleAmount))\n (try! (contract-call? 'SP8A9HZ3PKST0S42VM9523Z9NV42SZ026V4K39WH.ccd011-stacking-payouts send-stacking-reward-nyc cycle cycleAmount))\n )\n (as-contract (contract-call? 'SP8A9HZ3PKST0S42VM9523Z9NV42SZ026V4K39WH.ccd007-citycoin-stacking claim-stacking-reward cityName cycle))\n )\n)\n\n(define-public (distribute-rewards)\n (select-winner)\n)\n```\n\nThe `claim-rewards` function enables participants to claim their staking rewards, while the `distribute-rewards` function calls `select-winner` to randomly select and reward winners, ensuring a fair distribution process.\n\nWhen the `claim-rewards` function is called, the following steps occur:\n\n1. **Retrieve city ID and balance**: The city ID is retrieved using the `get-city-id` function, and the balance for the specified cycle is obtained from the treasury contract.\n2. **Send stacking rewards**: Depending on the city (`mia` or `nyc`), the appropriate stacking reward function is called to send the rewards for the specified cycle.\n3. **Claim stacking reward**: The contract claims the stacking reward for the specified city and cycle.\n\nWhen the `distribute-rewards` function is called, it performs the following step:\n\n1. **Select winner**: The `select-winner` function is called to randomly select a winner from the participants and update their status.\n\nThis process ensures that participants can claim their rewards and that winners are selected and rewarded fairly.\n\n## Testing the contract\n\nTo test the contracts, use the following steps inside of `clarinet console`:\n\n```terminal\n$ ::advance_chain_tip 700000\n$ ::set_tx_sender\n$ (contract-call? 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.no-loss-lottery-pool roll-the-dice \"mia\" u500 none)\n$ ::advance_chain_tip 2000\n$ (contract-call? 'SP8A9HZ3PKST0S42VM9523Z9NV42SZ026V4K39WH.ccd002-treasury-mia-stacking deposit-stx u5000000000)\n$ (contract-call? 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.no-loss-lottery-pool claim \"mia\" u17)\n```\n\nTo bootstrap the CityCoins contracts, follow these steps:\n\n```clarity\n(contract-call? 'SP8A9HZ3PKST0S42VM9523Z9NV42SZ026V4K39WH.ccd004-city-registry get-or-create-city-id \"mia\")\n(contract-call? 'SP8A9HZ3PKST0S42VM9523Z9NV42SZ026V4K39WH.ccd004-city-registry get-or-create-city-id \"nyc\")\n(contract-call? 'SP8A9HZ3PKST0S42VM9523Z9NV42SZ026V4K39WH.ccd002-treasury-mia-stacking set-allowed 'SP1H1733V5MZ3SZ9XRW9FKYGEZT0JDGEB8Y634C7R.miamicoin-token-v2 true)\n(contract-call? 'SP8A9HZ3PKST0S42VM9523Z9NV42SZ026V4K39WH.ccd002-treasury-nyc-stacking set-allowed 'SPSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1F4DYQ11.newyorkcitycoin-token-v2 true)\n```\n---\n\n## Next steps\n\n\n \n \n\n" + }, + { + "title": "DocsKit", + "description": "DocsKit usage", + "slug": "/guides/docskit", + "content": "\n## Features\n\nDocsKit features:\n\n- adds [flags](#flags) and [annotations](#annotations) to codeblocks\n- includes a special syntax for [inline code](#inline-code)\n- adds three components that can be used in MDX: [_``_](#codetabs), [_``_](#withnotes), and [_``_](#terminal-picker)\n- adds a [language switcher](#language-switcher) (which is another usage of _``_)\n- codeblocks with language [`terminal`](#terminal) or [`package-install`](#package-install) are rendered with a different component\n\n## Flags\n\n````txt flags-example.md\n# !mark[/-wn/]\n```js index.js -wn\n```\n````\n\n- `-n` add line numbers\n- `-c` add copy button\n- `-w` word wrap\n- `-a` animate (for tabs)\n\n## Annotations\n\n````txt annotations-example.md\n```js\nconst x = 1;\n# !mark[/!mark/]\n// !mark(1:2)\nconst y = 2;\nconst z = 3;\n```\n````\n\n- `!mark` - highlight a line, a range of lines, or a regex\n- `!diff` - highlight added or removed lines\n- `!collapse` - collapse a range of lines\n- `!fold` - fold a regex pattern inline\n- `!link` - add a link\n- `!tooltip` - add a tooltip\n- `!callout` - add a callout\n\nLearn more about using annotations from Code Hike docs:\n\n- [Annotation comments](https://codehike.org/docs/concepts/annotations#annotation-comments)\n- [Using regular expressions](https://codehike.org/docs/concepts/annotations#using-regular-expressions-instead-of-ranges)\n\n## Mark\n\nYou can use it for one line (`!mark`), a range of lines (`!mark(1:3)`), a range of columns (`!mark[5:10]`), or a regex pattern (`!mark[/pattern/]`).\n\nYou can provide any valid CSS color, for example: `!mark(1:3) red` or `!mark(1:3) hsl(var(--hiro))`.\n\n```clarity\n;; !mark[/Counters/mg]\n(define-map Counters principal uint)\n\n;; !mark(1:3)\n(define-public (count-up)\n (ok (map-set Counters tx-sender (+ (get-count tx-sender) u1)))\n)\n\n;; !mark hsl(var(--hiro))\n(define-read-only (get-count (who principal))\n (default-to u0 (map-get? Counters who))\n)\n```\n\n## Diff\n\n```js\nfunction lorem(ipsum, dolor = 1) {\n const sit = 10;\n // !diff -\n dolor = ipsum - sit;\n // !diff +\n dolor = sit - amet(dolor);\n return sit ? consectetur(ipsum) : [];\n}\n```\n\n## Collapse\n\n```jsonc sample-alert-payload.json -cwn\n{\n \"nonce\": 5,\n \"fee_rate\": \"250\",\n \"sponsored\": false,\n \"post_condition_mode\": \"deny\",\n // !collapse(1:9) collapsed\n \"post_conditions\": [\n {\n \"type\": \"stx\",\n \"condition_code\": \"sent_equal_to\",\n \"amount\": \"3000000\",\n \"principal\": {\n \"type_id\": \"principal_standard\",\n },\n },\n ],\n \"anchor_mode\": \"any\",\n \"tx_status\": \"pending\",\n \"receipt_time\": 1726104636,\n \"tx_type\": \"contract_call\",\n // !collapse(1:11) collapsed\n \"contract_call\": {\n \"function_name\": \"donate\",\n \"function_signature\": \"(define-public (donate (amount uint)))\",\n \"function_args\": [\n {\n \"hex\": \"0x01000000000000000000000000002dc6c0\",\n \"repr\": \"u3000000\",\n \"name\": \"amount\",\n \"type\": \"uint\",\n },\n ],\n },\n}\n```\n\n## Fold\n\n```jsx\n// !fold[/className=\"(.*?)\"/gm]\nfunction Foo() {\n return (\n
\n hey\n
\n );\n}\n```\n\n## Link\n\n```js\n// !link[/foo/mg] https://example.com\n// !link[/bar/mg] https://example.com\nimport { foo, bar } from \"baz\";\n\nconst x = foo(10);\nconst y = bar(x);\n```\n\n## CodeTabs\n\n````txt tabs-example.md\n# !mark[/!!/mg]\n\n\n```ts !! index.ts\n\n```\n\n```css !! styles.css\n\n```\n\n````\n\nNote: the codeblocks inside the _``_ component should have the `!!` decoration and a title.\n\nYou can pass flags to the _``_ component to apply them to all codeblocks inside it. The `a` flag will animate the transition between tabs.\n\nExample:\n\n\n\n```clarity !! one.clar\n;; !mark[/increment/mg]\n(define-data-var count uint u0)\n\n(define-public (increment)\n (begin\n (var-set count (+ (var-get count) u1))\n (ok (var-get count)) ;; !mark\n )\n)\n```\n\n```solidity !! two.sol\n// !mark[/add/mg]\nuint256 constant TOO_BIG = 10;\nuint256 count = 0;\n\nfunction add(uint256 amount) public returns (uint256) {\n uint256 newCount = count + amount;\n if (newCount <= TOO_BIG) {\n count = newCount;\n return count;\n }\n revert(\"Amount too large\"); // !mark\n}\n```\n\n\n\n### Language switcher\n\nTo switch between languages, use the _``_ component with the `storage` prop. The `storage` prop is used to store the selected language in the local storage and sync all the _``_ using the same `storage` key.\n\n\n\n```ts !! TypeScript\n(async () => {\n const apiConfig: Configuration = new Configuration({\n fetchApi: fetch,\n // for mainnet, replace `testnet` with `mainnet`\n basePath: \"https://api.testnet.hiro.so\",\n });\n})().catch(console.error);\n```\n\n```js !! JavaScript\n(async () => {\n const apiConfig = new Configuration({\n fetchApi: fetch,\n // for mainnet, replace `testnet` with `mainnet`\n basePath: \"https://api.testnet.hiro.so\",\n });\n})().catch(console.error);\n```\n\n\n\n## WithNotes\n\nFor `!callout` and `!tooltip` annotations, you can use the _``_ to define the content you want to show.\n\n### Callouts\n\n\n\n```js index.js\n// !callout[/ipsum/] description\nimport lorem from \"ipsum\";\n\n// !callout[/sit/] inspect\nconst sit = lorem({ a: 1, b: 2 });\n```\n\n```js !inspect\nsit = [\n { name: \"a\", value: 1 },\n { name: \"b\", value: 2 },\n];\n```\n\n## !description\n\nThe default export of the `ipsum` package is a function that **returns an array**.\n\nKind of like _`Object.entries(x)`_ but different.\n\n\n\n### Tooltips\n\n\n\n```js demo.js\n// !tooltip[/lorem/] install\nimport { read, write } from \"lorem\";\n\n// !tooltip[/data.json/] data\nvar data = read(\"data.json\");\n\n// !tooltip[/test-123/] apikey\nwrite({ x: 1 }, { apiKey: \"test-123\" });\n```\n\nWe can also use tooltips [here](tooltip \"install\") in [prose](tooltip \"data\") text.\n\n```json !data data.json\n{\n \"lorem\": \"ipsum dolor sit amet\",\n \"foo\": [4, 8, 15, 16]\n}\n```\n\n## !install\n\nThis is a **fake library**. You can install it with:\n\n```terminal\n$ npm install lorem\n```\n\nIt lets you read and write data.\n\n## !apikey\n\nThis is a public sample test mode [API key](https://example.com). Don’t submit any personally information using this key.\n\nReplace this with your secret key found on the [API Keys page](https://example.com) in the dashboard.\n\n\n\n## Inline code\n\nTo use inline codeyou need to use a special syntax: ``_`code`_``.\n\nThis syntax also allows you to specify the language for inline code ``_clarity`(contract-call? .counter count-up)`_`` renders: _clarity`(contract-call? .counter count-up)`_\n\n## Terminal\n\nTo use the terminal component, set the language of a codeblock to `terminal`, and start each command with `$`.\n\n```terminal\n$ tar -xf clarinet-linux-x64.tar.gz\n$ chmod +x ./clarinet\n$ mv ./clarinet /usr/local/bin\n```\n\nThe lines that don't start with `$` are rendered as collapsed output. The output can use ANSI colors and styles.\n\n```terminal\n$ npx create-next-app@latest\ncreate-next-app@14.2.13\n\u001b[32m✔\u001b[0m \u001b[1mWhat is your project?\u001b[0m \u001b[90m…\u001b[0m my-app\n$ npm run dev\n```\n\n### Terminal Picker\n\n\n\n```terminal !! macOS\n$ brew install clarinet\n```\n\n```terminal !! Windows\n$ winget install clarinet\n```\n\n```terminal !! Cargo\n$ sudo apt install build-essential pkg-config libssl-dev\n```\n\n\n\n### Package Install\n\nYou can use `package-install` as a language to get a picker for JS package managers.\n\n```package-install\n@stacks/connect\n```\n\n### Opting out of the terminal component\n\nTo use features from the normal codeblock component, you can still use languages like `sh` or `bash` or even `txt`.\n\n```sh Terminal -w\n# !tooltip[/v0.27.0/] You can change the v0.27.0 version that is available on the releases page.\n$ wget -nv download/v0.27.0/clarinet-linux-x64-glibc.tar.gz -O clarinet-linux-x64.tar.gz\n```\n" + } +] \ No newline at end of file diff --git a/scripts/clean-urls.js b/scripts/clean-urls.js deleted file mode 100644 index e748c2a31..000000000 --- a/scripts/clean-urls.js +++ /dev/null @@ -1,44 +0,0 @@ -const fs = require('fs'); -const path = require('path'); - -// Path to the generated JSON file -const filePath = path.join(process.cwd(), '.next', 'server', 'chunks', 'fumadocs_search.json'); - -// Check if the file exists -if (!fs.existsSync(filePath)) { - console.error('File does not exist:', filePath); - process.exit(1); -} - -// Read the JSON file -fs.readFile(filePath, 'utf8', (err, data) => { - if (err) { - console.error('Error reading the file:', err); - return; - } - - // Parse the JSON data - let jsonData; - try { - jsonData = JSON.parse(data); - } catch (parseErr) { - console.error('Error parsing JSON:', parseErr); - return; - } - - // Modify the URLs - jsonData.forEach((entry) => { - if (entry.url.startsWith('/docs/')) { - entry.url = entry.url.replace(/^\/docs\//, '/'); - } - }); - - // Write the updated JSON back to the file - fs.writeFile(filePath, JSON.stringify(jsonData, null, 2), 'utf8', (writeErr) => { - if (writeErr) { - console.error('Error writing the file:', writeErr); - return; - } - console.log('URLs updated successfully.'); - }); -}); \ No newline at end of file diff --git a/scripts/fetch-guides.js b/scripts/fetch-guides.js deleted file mode 100644 index 113a4a4ce..000000000 --- a/scripts/fetch-guides.js +++ /dev/null @@ -1,67 +0,0 @@ -const fs = require('fs'); -const path = require('path'); -const matter = require('gray-matter'); - -const baseDir = path.join(__dirname, '../content/docs'); - -const categories = { - stacks: [], - ordinals: [], - guides: [] -}; - -const stacksSubDirs = [ - 'api', 'archive', 'chainhook', 'clarinet', 'clarinet-js-sdk', 'connect', - 'explorer', 'nakamoto', 'platform', 'stacks.js', 'token-metadata-api' -]; - -const ordinalsSubDirs = ['api', 'explorer', 'indexer']; - -function categorizeFiles(dir, category, subDirs = []) { - if (subDirs.length > 0) { - subDirs.forEach(subDir => { - const guidesDir = path.join(dir, subDir, 'guides'); - if (fs.existsSync(guidesDir)) { - collectMarkdownFiles(guidesDir, category, subDir); - } - }); - } else { - collectMarkdownFiles(dir, category); - } -} - -function collectMarkdownFiles(dir, category, subDir = '') { - const files = fs.readdirSync(dir); - - files.forEach(file => { - const filePath = path.join(dir, file); - const stat = fs.statSync(filePath); - - if (stat.isDirectory()) { - collectMarkdownFiles(filePath, category, subDir); - } else if (file.endsWith('.md') || file.endsWith('.mdx')) { - const fileContent = fs.readFileSync(filePath, 'utf8'); - const { data } = matter(fileContent); - - categories[category].push({ - title: data.title || toReadableTitle(path.basename(file, path.extname(file))), - href: filePath.replace(baseDir, '').replace(/\\/g, '/').replace(path.extname(filePath), ''), - description: data.description || '', - category: subDir - }); - } - }); -} - -function toReadableTitle(slug) { - return slug - .replace(/-/g, ' ') - .replace(/\b\w/g, char => char.toUpperCase()); -} - -categorizeFiles(path.join(baseDir, 'stacks'), 'stacks', stacksSubDirs); -categorizeFiles(path.join(baseDir, 'ordinals'), 'ordinals', ordinalsSubDirs); -categorizeFiles(baseDir, 'guides'); - -fs.writeFileSync(path.join(__dirname, '../utils/all-guides.json'), JSON.stringify(categories, null, 2)); -console.log('Guides data generated successfully.'); \ No newline at end of file diff --git a/scripts/fetch-openapi-specs.js b/scripts/fetch-openapi-specs.js deleted file mode 100644 index f05ac6599..000000000 --- a/scripts/fetch-openapi-specs.js +++ /dev/null @@ -1,26 +0,0 @@ -const fetch = require('node-fetch'); -const fs = require('fs'); -const path = require('path'); - -const filesToDownload = [ - { - url: 'https://raw.githubusercontent.com/hirosystems/stacks-blockchain-api/develop/docs/stacks-api.yaml', - outputPath: './specs/stacks-api.yaml' - } - // Add more files here if needed -]; - -async function downloadFile(fileUrl, outputPath) { - const response = await fetch(fileUrl); - const data = await response.text(); - fs.writeFileSync(outputPath, data); - console.log(`Downloaded ${path.basename(outputPath)}`); -} - -async function main() { - for (const file of filesToDownload) { - await downloadFile(file.url, file.outputPath); - } -} - -main().catch(console.error); \ No newline at end of file diff --git a/scripts/fetch-openapi-specs.mts b/scripts/fetch-openapi-specs.mts new file mode 100644 index 000000000..2dc22e32c --- /dev/null +++ b/scripts/fetch-openapi-specs.mts @@ -0,0 +1,1168 @@ +#!/usr/bin/env node + +import fs from "fs/promises"; +import path from "path"; +import yaml from "js-yaml"; +import SwaggerParser from "@apidevtools/swagger-parser"; +import { OpenAPIMarkdownGenerator } from "./openapi-to-markdown.mts"; +import type { OpenAPIV3, OpenAPIV3_1 } from "openapi-types"; +import { buildEndpointMappings, saveMappings } from "./utils/api-endpoint-mapping.mts"; + +interface ApiSpec { + name: string; + url: string; +} + +interface GitHubApiSpec { + name: string; + type: "github"; + repo: string; + branch: string; + filePath: string; +} + +const API_SPECS: ApiSpec[] = [ + { + name: "stacks-blockchain", + url: "https://stacks-blockchain-api.vercel.app/openapi.json", + }, + { + name: "token-metadata", + url: "https://token-metadata-api.vercel.app/openapi.json", + }, + { + name: "signer-metrics", + url: "https://signer-metrics-api.vercel.app/openapi.json", + }, + { + name: "ordinals", + url: "https://ordinals-api.vercel.app/openapi.json", + }, + { + name: "runes", + url: "https://runes-api.vercel.app/openapi.json", + }, +]; + +const GITHUB_API_SPECS: GitHubApiSpec[] = [ + { + name: "stacks-node-rpc", + type: "github", + repo: "stacks-network/stacks-core", + branch: "develop", + filePath: "docs/rpc/openapi.yaml", + }, +]; + +async function generatePlatformApiSpec(): Promise { + try { + const openApiDir = path.join(process.cwd(), "openapi"); + await fs.mkdir(openApiDir, { recursive: true }); + + const platformApiPath = path.join(openApiDir, "platform-api.json"); + + // Check if file already exists (skip if it does) + try { + await fs.access(platformApiPath); + return; + } catch { + // File doesn't exist, generate it + console.log("Generating platform-api.json..."); + } + + // Hardcoded Platform API spec - copied from existing platform-api.json + const platformApiSpec = { + openapi: "3.0.0", + info: { + title: "Hiro Platform API", + version: "1.0.0", + description: + "API for managing devnets and chainhooks on the Hiro Platform", + }, + servers: [ + { + url: "https://api.platform.hiro.so", + description: "Production server", + }, + ], + paths: { + "/v1/ext/{apiKey}/devnet/{projectName}": { + put: { + summary: "Start devnet", + description: "Start a development network (devnet)", + operationId: "startDevnet", + tags: ["Devnet"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + example: "0941f307fd270ace19a5bfed67fbd3bc", + }, + }, + { + name: "projectName", + in: "path", + required: true, + description: "Project name", + schema: { + type: "string", + example: "clarity-bitcoin-197s", + }, + }, + ], + requestBody: { + required: true, + content: { + "multipart/form-data": { + schema: { + type: "object", + required: ["file"], + properties: { + file: { + type: "string", + format: "binary", + description: + "JSON file containing the devnet plan. The file can be created using clarinet devnet package", + }, + }, + }, + }, + }, + }, + responses: { + "200": { + description: "Default Response", + content: { + "application/json": { + schema: { + type: "object", + }, + }, + }, + }, + }, + }, + }, + "/v1/ext/{apiKey}/devnet": { + delete: { + summary: "Stop devnet", + description: "Stop a development network (devnet)", + operationId: "stopDevnet", + tags: ["Devnet"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + example: "0941f307fd270ace19a5bfed67fbd3bc", + }, + }, + ], + responses: { + "200": { + description: "Default Response", + content: { + "text/plain": { + schema: { + type: "string", + example: "Ok", + }, + }, + }, + }, + }, + }, + }, + "/v1/ext/{apiKey}/stacks-blockchain-api/{*}": { + get: { + summary: "Stacks Blockchain API Proxy (GET)", + description: + "Proxy for the Stacks Blockchain API on a development network (devnet)", + operationId: "stacksBlockchainApiProxyGet", + tags: ["Devnet"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + example: "0941f307fd270ace19a5bfed67fbd3bc", + }, + }, + { + name: "*", + in: "path", + required: true, + description: + "The path (endpoint) for the Stacks Blockchain API", + schema: { + type: "string", + example: "extended/v1/tx", + }, + }, + ], + responses: { + "200": { + description: "Default Response", + content: { + "application/json": { + schema: { + type: "object", + }, + }, + }, + }, + }, + }, + post: { + summary: "Stacks Blockchain API Proxy (POST)", + description: + "Proxy for the Stacks Blockchain API on a development network (devnet)", + operationId: "stacksBlockchainApiProxyPost", + tags: ["Devnet"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + example: "0941f307fd270ace19a5bfed67fbd3bc", + }, + }, + { + name: "*", + in: "path", + required: true, + description: + "The path (endpoint) for the Stacks Blockchain API", + schema: { + type: "string", + example: "v2/transactions", + }, + }, + ], + requestBody: { + content: { + "application/json": { + schema: { + type: "object", + }, + }, + }, + }, + responses: { + "200": { + description: "Default Response", + content: { + "application/json": { + schema: { + type: "object", + }, + }, + }, + }, + }, + }, + put: { + summary: "Stacks Blockchain API Proxy (PUT)", + description: + "Proxy for the Stacks Blockchain API on a development network (devnet)", + operationId: "stacksBlockchainApiProxyPut", + tags: ["Devnet"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + }, + }, + { + name: "*", + in: "path", + required: true, + description: + "The path (endpoint) for the Stacks Blockchain API", + schema: { + type: "string", + }, + }, + ], + responses: { + "200": { + description: "Default Response", + }, + }, + }, + delete: { + summary: "Stacks Blockchain API Proxy (DELETE)", + description: + "Proxy for the Stacks Blockchain API on a development network (devnet)", + operationId: "stacksBlockchainApiProxyDelete", + tags: ["Devnet"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + }, + }, + { + name: "*", + in: "path", + required: true, + description: + "The path (endpoint) for the Stacks Blockchain API", + schema: { + type: "string", + }, + }, + ], + responses: { + "200": { + description: "Default Response", + }, + }, + }, + patch: { + summary: "Stacks Blockchain API Proxy (PATCH)", + description: + "Proxy for the Stacks Blockchain API on a development network (devnet)", + operationId: "stacksBlockchainApiProxyPatch", + tags: ["Devnet"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + }, + }, + { + name: "*", + in: "path", + required: true, + description: + "The path (endpoint) for the Stacks Blockchain API", + schema: { + type: "string", + }, + }, + ], + responses: { + "200": { + description: "Default Response", + }, + }, + }, + options: { + summary: "Stacks Blockchain API Proxy (OPTIONS)", + description: + "Proxy for the Stacks Blockchain API on a development network (devnet)", + operationId: "stacksBlockchainApiProxyOptions", + tags: ["Devnet"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + }, + }, + { + name: "*", + in: "path", + required: true, + description: + "The path (endpoint) for the Stacks Blockchain API", + schema: { + type: "string", + }, + }, + ], + responses: { + "200": { + description: "Default Response", + }, + }, + }, + }, + "/v1/ext/{apiKey}/bitcoin-node/{*}": { + get: { + summary: "Bitcoin node Proxy (GET)", + description: + "Proxy for the Bitcoin node on a development network (devnet)", + operationId: "bitcoinNodeProxyGet", + tags: ["Devnet"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + example: "0941f307fd270ace19a5bfed67fbd3bc", + }, + }, + { + name: "*", + in: "path", + required: true, + description: "The path (endpoint) for the Bitcoin node RPC", + schema: { + type: "string", + example: "rest/chaininfo", + }, + }, + ], + responses: { + "200": { + description: "Default Response", + content: { + "application/json": { + schema: { + type: "object", + }, + }, + }, + }, + }, + }, + post: { + summary: "Bitcoin node Proxy (POST)", + description: + "Proxy for the Bitcoin node on a development network (devnet)", + operationId: "bitcoinNodeProxyPost", + tags: ["Devnet"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + example: "0941f307fd270ace19a5bfed67fbd3bc", + }, + }, + { + name: "*", + in: "path", + required: true, + description: "The path (endpoint) for the Bitcoin node RPC", + schema: { + type: "string", + example: "rest/chaininfo", + }, + }, + ], + requestBody: { + content: { + "application/json": { + schema: { + type: "object", + }, + }, + }, + }, + responses: { + "200": { + description: "Default Response", + content: { + "application/json": { + schema: { + type: "object", + }, + }, + }, + }, + }, + }, + put: { + summary: "Bitcoin node Proxy (PUT)", + description: + "Proxy for the Bitcoin node on a development network (devnet)", + operationId: "bitcoinNodeProxyPut", + tags: ["Devnet"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + }, + }, + { + name: "*", + in: "path", + required: true, + description: "The path (endpoint) for the Bitcoin node RPC", + schema: { + type: "string", + }, + }, + ], + responses: { + "200": { + description: "Default Response", + }, + }, + }, + delete: { + summary: "Bitcoin node Proxy (DELETE)", + description: + "Proxy for the Bitcoin node on a development network (devnet)", + operationId: "bitcoinNodeProxyDelete", + tags: ["Devnet"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + }, + }, + { + name: "*", + in: "path", + required: true, + description: "The path (endpoint) for the Bitcoin node RPC", + schema: { + type: "string", + }, + }, + ], + responses: { + "200": { + description: "Default Response", + }, + }, + }, + patch: { + summary: "Bitcoin node Proxy (PATCH)", + description: + "Proxy for the Bitcoin node on a development network (devnet)", + operationId: "bitcoinNodeProxyPatch", + tags: ["Devnet"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + }, + }, + { + name: "*", + in: "path", + required: true, + description: "The path (endpoint) for the Bitcoin node RPC", + schema: { + type: "string", + }, + }, + ], + responses: { + "200": { + description: "Default Response", + }, + }, + }, + options: { + summary: "Bitcoin node Proxy (OPTIONS)", + description: + "Proxy for the Bitcoin node on a development network (devnet)", + operationId: "bitcoinNodeProxyOptions", + tags: ["Devnet"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + }, + }, + { + name: "*", + in: "path", + required: true, + description: "The path (endpoint) for the Bitcoin node RPC", + schema: { + type: "string", + }, + }, + ], + responses: { + "200": { + description: "Default Response", + }, + }, + }, + }, + "/v1/ext/{apiKey}/chainhooks": { + get: { + summary: "Get all chainhooks", + description: "Get all of your chainhooks through the Hiro Platform", + operationId: "listAllChainhooks", + tags: ["Chainhooks"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + }, + }, + ], + responses: { + "200": { + description: "Default Response", + content: { + "application/json": { + schema: { + type: "array", + items: { + type: "object", + }, + }, + }, + }, + }, + }, + }, + post: { + summary: "Create a chainhook", + description: "Create a chainhook through the Hiro Platform", + operationId: "createChainhook", + tags: ["Chainhooks"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + example: "0941f307fd270ace19a5bfed67fbd3bc", + }, + }, + ], + requestBody: { + required: true, + description: "Chainhook predicate configuration", + content: { + "application/json": { + schema: { + type: "object", + }, + }, + }, + }, + responses: { + "200": { + description: "Default Response", + content: { + "application/json": { + schema: { + type: "object", + properties: { + status: { + type: "string", + }, + chainhookUuid: { + type: "string", + }, + }, + }, + }, + }, + }, + }, + }, + }, + "/v1/ext/{apiKey}/chainhooks/{chainhookUuid}": { + get: { + summary: "Get a specific chainhook", + description: "Get a specific chainhook through the Hiro Platform", + operationId: "retrieveChainhook", + tags: ["Chainhooks"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + example: "0941f307fd270ace19a5bfed67fbd3bc", + }, + }, + { + name: "chainhookUuid", + in: "path", + required: true, + description: "Chainhook UUID", + schema: { + type: "string", + example: "aa3626dc-2090-49cd-8f1e-8f9994393aed", + }, + }, + ], + responses: { + "200": { + description: "Default Response", + content: { + "application/json": { + schema: { + type: "object", + additionalProperties: true, + }, + }, + }, + }, + "404": { + description: "Default Response", + }, + }, + }, + put: { + summary: "Update a chainhook", + description: "Update a chainhook through the Hiro Platform", + operationId: "updateChainhook", + tags: ["Chainhooks"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + example: "0941f307fd270ace19a5bfed67fbd3bc", + }, + }, + { + name: "chainhookUuid", + in: "path", + required: true, + description: "Chainhook UUID", + schema: { + type: "string", + example: "aa3626dc-2090-49cd-8f1e-8f9994393aed", + }, + }, + ], + requestBody: { + description: "Chainhook predicate configuration", + content: { + "application/json": { + schema: { + type: "object", + }, + }, + }, + }, + responses: { + "200": { + description: "Default Response", + content: { + "application/json": { + schema: { + type: "object", + properties: { + status: { + type: "string", + }, + chainhookUuid: { + type: "string", + }, + }, + }, + }, + }, + }, + "404": { + description: "Default Response", + }, + "500": { + description: "Default Response", + }, + }, + }, + delete: { + summary: "Delete a chainhook", + description: "Delete a chainhook through the Hiro Platform", + operationId: "deleteChainhook", + tags: ["Chainhooks"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + example: "0941f307fd270ace19a5bfed67fbd3bc", + }, + }, + { + name: "chainhookUuid", + in: "path", + required: true, + description: "Chainhook UUID", + schema: { + type: "string", + example: "aa3626dc-2090-49cd-8f1e-8f9994393aed", + }, + }, + ], + responses: { + "200": { + description: "Default Response", + content: { + "application/json": { + schema: { + type: "object", + properties: { + status: { + type: "string", + }, + chainhookUuid: { + type: "string", + }, + message: { + type: "string", + }, + }, + }, + }, + }, + }, + }, + }, + }, + "/v1/ext/{apiKey}/chainhooks/{chainhookUuid}/status": { + get: { + summary: "Get a chainhook status", + description: + "Retrieve the status of a specific chainhook through the Hiro Platform", + operationId: "retrieveChainhookStatus", + tags: ["Chainhooks"], + parameters: [ + { + name: "apiKey", + in: "path", + required: true, + description: "Hiro API key", + schema: { + type: "string", + example: "0941f307fd270ace19a5bfed67fbd3bc", + }, + }, + { + name: "chainhookUuid", + in: "path", + required: true, + description: "Chainhook UUID", + schema: { + type: "string", + example: "aa3626dc-2090-49cd-8f1e-8f9994393aed", + }, + }, + ], + responses: { + "200": { + description: "Successfully retrieved chainhook status", + content: { + "application/json": { + schema: { + type: "object", + properties: { + status: { + type: "object", + properties: { + info: { + type: "object", + properties: { + expired_at_block_height: { + type: "integer", + }, + last_evaluated_block_height: { + type: "integer", + }, + last_occurrence: { + type: "integer", + }, + number_of_blocks_evaluated: { + type: "integer", + }, + number_of_times_triggered: { + type: "integer", + }, + }, + }, + type: { + type: "string", + }, + }, + }, + enabled: { + type: "boolean", + }, + }, + }, + }, + }, + }, + "404": { + description: "Chainhook not found", + }, + }, + }, + }, + }, + components: { + securitySchemes: { + ApiKeyAuth: { + type: "apiKey", + in: "path", + name: "apiKey", + }, + }, + }, + tags: [ + { + name: "Devnet", + description: "Development network management endpoints", + }, + { + name: "Chainhooks", + description: "Chainhook management endpoints", + }, + ], + }; + + await fs.writeFile( + platformApiPath, + JSON.stringify(platformApiSpec, null, 2) + ); + } catch (error) { + console.error("❌ Failed to generate platform-api.json:", error); + } +} + +async function fetchApiSpec(spec: ApiSpec): Promise { + try { + const response = await fetch(spec.url); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const text = await response.text(); + + // Validate that the response is valid JSON + let jsonData; + try { + jsonData = JSON.parse(text); + } catch (parseError) { + throw new Error(`Invalid JSON response from ${spec.url}: ${parseError}`); + } + + // Ensure openapi directory exists + const openApiDir = path.join(process.cwd(), "openapi"); + await fs.mkdir(openApiDir, { recursive: true }); + + // Write the file with proper naming convention + const filename = `${spec.name}-api.json`; + const filepath = path.join(openApiDir, filename); + + await fs.writeFile(filepath, JSON.stringify(jsonData, null, 2)); + } catch (error) { + console.error(`❌ Failed to fetch ${spec.name}:`, error); + } +} + +async function fetchGitHubApiSpec(spec: GitHubApiSpec): Promise { + try { + // Construct the raw GitHub URL + const rawUrl = `https://raw.githubusercontent.com/${spec.repo}/${spec.branch}/${spec.filePath}`; + + const response = await fetch(rawUrl); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const yamlText = await response.text(); + + // Parse YAML to check if it's valid + let yamlData; + try { + yamlData = yaml.load(yamlText); + } catch (parseError) { + throw new Error(`Invalid YAML from ${rawUrl}: ${parseError}`); + } + + // Use swagger-parser to dereference and bundle the spec + // Pass the raw URL as the base URL so $ref resolution works correctly + const bundledSpec = await SwaggerParser.dereference( + rawUrl, + yamlData as any + ); + + // Ensure openapi directory exists + const openApiDir = path.join(process.cwd(), "openapi"); + await fs.mkdir(openApiDir, { recursive: true }); + + // Write the file with proper naming convention + const filename = `${spec.name}-api.json`; + const filepath = path.join(openApiDir, filename); + + await fs.writeFile(filepath, JSON.stringify(bundledSpec, null, 2)); + } catch (error) { + console.error(`❌ Failed to fetch ${spec.name}:`, error); + } +} + +async function generateMarkdownForSpec(specPath: string, specName: string): Promise { + try { + console.log(`📝 Generating markdown for ${specName}...`); + + // Read the OpenAPI spec + const specContent = await fs.readFile(specPath, "utf-8"); + const spec = JSON.parse(specContent) as OpenAPIV3.Document | OpenAPIV3_1.Document; + + // Create markdown generator + const generator = new OpenAPIMarkdownGenerator(spec); + + // Generate markdown for all endpoints + const markdownMap = await generator.generateAllEndpoints(); + + // Create output directory + const outputDir = path.join(process.cwd(), "generated", "apis", specName); + await fs.mkdir(outputDir, { recursive: true }); + + // Create mapping for URL to file lookup + const urlMapping: Record = {}; + + // Save each endpoint's markdown + let count = 0; + for (const [key, markdown] of markdownMap) { + // Create a filename from the endpoint key + // e.g., "GET /v1/users/{id}" -> "get-v1-users-id.md" + const filename = key + .toLowerCase() + .replace(/[{}]/g, "") + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-|-$/g, "") + ".md"; + + const filePath = path.join(outputDir, filename); + await fs.writeFile(filePath, markdown.content); + + // Add to mapping + urlMapping[key] = { + method: markdown.method, + path: markdown.endpoint, + file: filename + }; + + count++; + } + + // Save the mapping file + const mappingPath = path.join(outputDir, "_mapping.json"); + await fs.writeFile(mappingPath, JSON.stringify(urlMapping, null, 2)); + + console.log(`✔️ Generated ${count} markdown files for ${specName}`); + } catch (error) { + console.error(`❌ Failed to generate markdown for ${specName}:`, error); + } +} + +async function generateAllMarkdown(): Promise { + console.log("\n📚 Generating markdown documentation...\n"); + + const openApiDir = path.join(process.cwd(), "openapi"); + + // Get all OpenAPI spec files + const specFiles = await fs.readdir(openApiDir); + const jsonFiles = specFiles.filter(file => file.endsWith(".json")); + + // Generate markdown for each spec + const markdownPromises = jsonFiles.map(file => { + const specPath = path.join(openApiDir, file); + const specName = file.replace("-api.json", ""); + return generateMarkdownForSpec(specPath, specName); + }); + + await Promise.all(markdownPromises); + + // Build and save endpoint mappings + console.log("\n📍 Building endpoint mappings..."); + const mappings = await buildEndpointMappings(); + await saveMappings(mappings); + + console.log("\n✔️ Markdown generation complete!"); +} + +async function fetchAllSpecs(): Promise { + console.log("Fetching OpenAPI specs..."); + + // Generate platform API spec and fetch other specs concurrently + const allPromises = [ + generatePlatformApiSpec(), + ...API_SPECS.map((spec) => fetchApiSpec(spec)), + ...GITHUB_API_SPECS.map((spec) => fetchGitHubApiSpec(spec)), + ]; + + await Promise.all(allPromises); + + console.log("✔️ Generated OpenAPI specs"); + + // Generate markdown for all specs + await generateAllMarkdown(); +} + +// Run the script if this file is executed directly +if (require.main === module) { + fetchAllSpecs().catch(console.error); +} + +export { + fetchAllSpecs, + fetchApiSpec, + fetchGitHubApiSpec, + generatePlatformApiSpec, +}; diff --git a/scripts/fetch-recipes.mts b/scripts/fetch-recipes.mts deleted file mode 100644 index 4330aedc0..000000000 --- a/scripts/fetch-recipes.mts +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env node - -/** - * Script to fetch code-block recipe files from a separate GitHub repo - * and store them locally under .cache/recipes for doc usage at build time. - */ - -import fs from "fs/promises"; -import path from "path"; -import https from "https"; - -// Configuration -const REPO_OWNER = "hirosystems"; -const REPO_NAME = "recipes"; -const BRANCH = "main"; -const BASE_PATH = "recipes/"; -const DEST_FOLDER = ".cache/recipes"; - -async function getGitHubFileList() { - const url = `https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}/contents/${BASE_PATH}?ref=${BRANCH}`; - const response = await fetchUrl(url); - try { - return JSON.parse(response); - } catch (error) { - console.error("Failed to parse GitHub API response:"); - console.error("Response:", response); - throw new Error(`Invalid JSON response from GitHub API: ${error.message}`); - } -} - -async function fetchUrl(url: string): Promise { - return new Promise((resolve, reject) => { - const handleResponse = (res: any) => { - // Handle redirects (status codes 301, 302, 307, 308) - if ( - res.statusCode >= 300 && - res.statusCode < 400 && - res.headers.location - ) { - console.log(`Following redirect to: ${res.headers.location}`); - https - .get( - res.headers.location, - { - headers: { - "User-Agent": "hirosystems/fetch-recipes", - Accept: "application/vnd.github.v3+json", - }, - }, - handleResponse - ) - .on("error", reject); - return; - } - - if (res.statusCode !== 200) { - reject(new Error(`GitHub API returned status ${res.statusCode}`)); - return; - } - - let data = ""; - res.on("data", (chunk: string) => (data += chunk)); - res.on("end", () => resolve(data)); - }; - - const req = https.get( - url, - { - headers: { - "User-Agent": "hirosystems/fetch-recipes", - Accept: "application/vnd.github.v3+json", - }, - }, - handleResponse - ); - - req.on("error", (err) => reject(err)); - req.end(); - }); -} - -async function main() { - try { - console.log("Creating cache directory..."); - await fs.mkdir(DEST_FOLDER, { recursive: true }); - - console.log(`Fetching file list from ${REPO_OWNER}/${REPO_NAME}...`); - const fileList = await getGitHubFileList(); - - if (!Array.isArray(fileList)) { - throw new Error("GitHub API did not return an array of files"); - } - - console.log(`Found ${fileList.length} total files`); - const mdxFiles = fileList.filter((f) => f.name.endsWith(".mdx")); - console.log(`Found ${mdxFiles.length} MDX files`); - - for (const file of mdxFiles) { - console.log(`Fetching ${file.name}...`); - const fileContent = await fetchUrl(file.download_url); - const filename = path.join(DEST_FOLDER, file.name); - await fs.writeFile(filename, fileContent, "utf8"); - console.log(`Successfully saved: ${file.name}`); - } - - console.log("All recipe code blocks fetched successfully."); - } catch (error) { - console.error("Error fetching code blocks:"); - console.error(error); - process.exit(1); - } -} - -main(); diff --git a/scripts/generate-docs.mjs b/scripts/generate-docs.mjs deleted file mode 100644 index cc2192b4a..000000000 --- a/scripts/generate-docs.mjs +++ /dev/null @@ -1,37 +0,0 @@ -import { generateFiles } from "fumadocs-openapi" - -// void generateFiles({ -// input: ["./openapi/stacks-api.json"], -// output: "./content/docs/stacks/api", -// groupBy: "tag", -// }) - -// void generateFiles({ -// input: ["./openapi/stacks-rpc-api.json"], -// output: "./content/docs/stacks/rpc-api", -// groupBy: "tag", -// }) - -// void generateFiles({ -// input: ["./openapi/runes-api.json"], -// output: "./content/docs/bitcoin/runes/api", -// groupBy: "tag" -// }) - -// void generateFiles({ -// input: ["./openapi/ordinals-api.json"], -// output: "./content/docs/bitcoin/ordinals/api", -// groupBy: "tag", -// }) - -// void generateFiles({ -// input: ["./openapi/token-metadata-api.json"], -// output: "./content/docs/stacks/token-metadata-api", -// groupBy: "tag", -// }) - -// void generateFiles({ -// input: ["./openapi/platform-api.json"], -// output: "./content/docs/stacks/platform-api", -// groupBy: "tag", -// }) \ No newline at end of file diff --git a/scripts/generate-llms-txt.ts b/scripts/generate-llms-txt.ts new file mode 100644 index 000000000..d8dcf812e --- /dev/null +++ b/scripts/generate-llms-txt.ts @@ -0,0 +1,208 @@ +#!/usr/bin/env bun +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import { source } from "../lib/source"; + +const PUBLIC_DIR = path.join(process.cwd(), "public"); + +// Configuration for generation +interface GenerationConfig { + productionUrl: string; +} + +// Environment variables (optional): +// LLMS_BASE_URL - URL for llms.txt (default: "https://docs.hiro.so") +const config: GenerationConfig = { + productionUrl: process.env.LLMS_BASE_URL || "https://docs.hiro.so", +}; + +interface PageMetadata { + title: string; + description: string; + url: string; + section: string[]; +} + +// Get all pages from source +function getAllPages(): PageMetadata[] { + const sourcePages = source.getPages(); + + return sourcePages + .map((page) => { + // Extract section from URL (split by / and filter out empty strings) + const urlParts = page.url.split("/").filter(Boolean); + const section = urlParts.slice(0, -1); // All parts except the last one + + return { + title: (page.data as any)?.title || page.file.name, + description: (page.data as any)?.description || "", + url: page.url, + section: section, + }; + }) + .sort((a, b) => a.url.localeCompare(b.url)); +} + +// Generate llms.txt content for a set of pages +function generateLLMsContent( + pages: PageMetadata[], + title: string, + currentSection: string[] = [] +): string { + const lines = [`# ${title}`, "", "## Pages", ""]; + + // For deep sections (like /tools), we want to group by the next level + const groupDepth = currentSection.length; + const groupedBySections = new Map(); + + // Group pages by their section at the appropriate depth + for (const page of pages) { + let sectionKey = "root"; + + if (page.section.length > groupDepth) { + // Group by the next level after current section + sectionKey = page.section[groupDepth]; + } else if (page.section.length === groupDepth && groupDepth > 0) { + // This is a page at the current level (like tools/clarinet.md) + sectionKey = "_overview"; + } + + const sectionArray = groupedBySections.get(sectionKey) ?? []; + sectionArray.push(page); + groupedBySections.set(sectionKey, sectionArray); + } + + // Sort sections, but put _overview first if it exists + const sortedSections = Array.from(groupedBySections.keys()).sort((a, b) => { + if (a === "_overview") return -1; + if (b === "_overview") return 1; + if (a === "root") return -1; + if (b === "root") return 1; + return a.localeCompare(b); + }); + + // Add subsection headers when we have multiple sections + const needsSubsectionHeaders = + sortedSections.length > 2 || + (currentSection.length === 0 && sortedSections.length > 1); + + for (const section of sortedSections) { + const sectionPages = (groupedBySections.get(section) ?? []).sort((a, b) => { + // Sort overview pages first + if (a.url.endsWith(`/${section}`)) return -1; + if (b.url.endsWith(`/${section}`)) return 1; + return a.title.localeCompare(b.title); + }); + + if (section === "_overview") { + // These are overview pages at the current level + for (const page of sectionPages) { + const mdUrl = + page.url === "/" + ? `${config.productionUrl}/index.md` + : `${config.productionUrl}${page.url}.md`; + lines.push( + `- [${page.title}](${mdUrl})${page.description ? `: ${page.description}` : ""}` + ); + } + if (sectionPages.length > 0) lines.push(""); + } else if (section !== "root") { + // Add subsection header for better organization + if (needsSubsectionHeaders) { + lines.push( + `#### ${section.charAt(0).toUpperCase() + section.slice(1).replace(/-/g, " ")}` + ); + lines.push(""); + } else { + lines.push( + `### ${section.charAt(0).toUpperCase() + section.slice(1).replace(/-/g, " ")}` + ); + lines.push(""); + } + + for (const page of sectionPages) { + const mdUrl = + page.url === "/" + ? `${config.productionUrl}/index.md` + : `${config.productionUrl}${page.url}.md`; + lines.push( + `- [${page.title}](${mdUrl})${page.description ? `: ${page.description}` : ""}` + ); + } + lines.push(""); + } else { + // Root level pages + for (const page of sectionPages) { + const mdUrl = + page.url === "/" + ? `${config.productionUrl}/index.md` + : `${config.productionUrl}${page.url}.md`; + lines.push( + `- [${page.title}](${mdUrl})${page.description ? `: ${page.description}` : ""}` + ); + } + if (sectionPages.length > 0) lines.push(""); + } + } + + return lines.join("\n").trim(); +} + +// Create directory if it doesn't exist +async function ensureDir(dir: string) { + try { + await fs.access(dir); + } catch { + await fs.mkdir(dir, { recursive: true }); + } +} + +// Main generation function +async function generateAllLLMsTxt() { + console.log("🚀 Starting documentation generation..."); + + const allPages = getAllPages(); + console.log(`📄 Found ${allPages.length} pages`); + + // Generate root llms.txt with production URLs + const rootContent = generateLLMsContent(allPages, "Hiro Documentation", []); + await fs.writeFile(path.join(PUBLIC_DIR, "llms.txt"), rootContent); + console.log("✔️ Generated root llms.txt"); + + // Generate section-level llms.txt files + const sections = new Map(); + + for (const page of allPages) { + // Generate for each directory level + for (let i = 1; i <= page.section.length; i++) { + const sectionPath = page.section.slice(0, i).join("/"); + const sectionArray = sections.get(sectionPath) ?? []; + sectionArray.push(page); + sections.set(sectionPath, sectionArray); + } + } + + // Create llms.txt for each section + for (const [sectionPath, sectionPages] of sections) { + const sectionParts = sectionPath.split("/"); + const sectionTitle = `${sectionParts + .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) + .join(" ")} Documentation`; + + const sectionContent = generateLLMsContent( + sectionPages, + sectionTitle, + sectionParts + ); + const outputPath = path.join(PUBLIC_DIR, sectionPath); + + await ensureDir(outputPath); + await fs.writeFile(path.join(outputPath, "llms.txt"), sectionContent); + } + console.log("✔️ Generated section llms.txt files"); + + console.log("✅ All llms.txt files generated successfully!"); +} + +// Run the generation +generateAllLLMsTxt().catch(console.error); diff --git a/scripts/generate-reference-docs.ts b/scripts/generate-reference-docs.ts new file mode 100644 index 000000000..3d4e6785d --- /dev/null +++ b/scripts/generate-reference-docs.ts @@ -0,0 +1,145 @@ +// scripts/generate-reference-docs.ts + +import { ReferenceMarkdownGenerator } from "../lib/markdown-generator"; +import fs from "fs/promises"; +import path from "path"; + +// Configuration +const INPUT_JSON_PATH = process.argv[2] || "./typedoc-output.json"; +const OUTPUT_DIR = "./content/docs/reference"; +const OUTPUT_FILENAME = "stacks-transactions.mdx"; + +async function generateReferenceDocs() { + try { + console.log("📚 Starting reference documentation generation...\n"); + + // Read the TypeDoc JSON file + console.log(`📖 Reading TypeDoc JSON from: ${INPUT_JSON_PATH}`); + const jsonContent = await fs.readFile(INPUT_JSON_PATH, "utf-8"); + const typeDocData = JSON.parse(jsonContent); + + console.log(`✅ Loaded ${typeDocData.name} v${typeDocData.version}`); + console.log(` Total exports: ${typeDocData.exports?.length || 0}`); + + // Generate the markdown + console.log("\n🔨 Generating markdown..."); + const generator = new ReferenceMarkdownGenerator(typeDocData); + const markdown = generator.generateFullDocument(); + + // Ensure output directory exists + const outputPath = path.join(OUTPUT_DIR, OUTPUT_FILENAME); + await fs.mkdir(OUTPUT_DIR, { recursive: true }); + + // Write the markdown file + console.log(`\n💾 Writing markdown to: ${outputPath}`); + await fs.writeFile(outputPath, markdown, "utf-8"); + + // Calculate some stats + const lines = markdown.split("\n").length; + const size = Buffer.byteLength(markdown, "utf-8"); + + console.log(`\n✨ Generation complete!`); + console.log(` Lines: ${lines.toLocaleString()}`); + console.log(` Size: ${(size / 1024).toFixed(2)} KB`); + console.log( + `\n📄 View your documentation at: /docs/reference/${OUTPUT_FILENAME.replace(".mdx", "")}` + ); + } catch (error) { + console.error("\n❌ Error generating documentation:", error); + process.exit(1); + } +} + +// For testing with sample data +async function generateWithSampleData() { + const sampleData = { + name: "@stacks/transactions", + version: "7.1.0", + exports: [ + { + name: "Address", + kind: "Namespace", + description: + "The Address namespace provides utilities for working with Stacks addresses.", + source: { + fileName: "packages/transactions/src/namespaces/address.ts", + line: 1, + url: "https://github.com/hirosystems/stacks.js/blob/c8267f2/packages/transactions/src/namespaces/address.ts#L1", + }, + }, + { + name: "AddressRepr", + kind: "Type alias", + description: "Type representation for Stacks addresses", + source: { + fileName: "packages/transactions/src/namespaces/address.ts", + line: 8, + url: "https://github.com/hirosystems/stacks.js/blob/c8267f2/packages/transactions/src/namespaces/address.ts#L8", + }, + }, + { + name: "fromPrivateKey", + kind: "Function", + source: { + fileName: "packages/transactions/src/namespaces/address.ts", + line: 90, + url: "https://github.com/hirosystems/stacks.js/blob/c8267f2/packages/transactions/src/namespaces/address.ts#L90", + }, + signatures: [ + { + parameters: [ + { + name: "privateKey", + type: "PrivateKey", + description: "The private key to convert.", + optional: false, + }, + { + name: "network", + type: 'StacksNetwork | "mainnet" | "testnet" | "devnet" | "mocknet"', + optional: true, + }, + ], + examples: [ + { + code: "```ts\nimport { Address } from '@stacks/transactions';\n\nconst address = Address.fromPrivateKey('73a2f291df5a8ce3ceb668a25ac7af45639513af7596d710ddf59f64f484fd2801');\n// 'SP10J81WVGVB3M4PHQN4Q4G0R8586TBJH948RESDR'\n\nconst address = Address.fromPrivateKey('73a2f291df5a8ce3ceb668a25ac7af45639513af7596d710ddf59f64f484fd2801', 'testnet');\n// 'ST10J81WVGVB3M4PHQN4Q4G0R8586TBJH94CGRESQ'\n```", + }, + ], + description: + "Convert a private key to a single-sig C32 Stacks address.", + returns: { + type: "string", + description: "The address string.", + }, + }, + ], + }, + ], + }; + + console.log("📚 Using sample data for testing...\n"); + + // Generate the markdown + const generator = new ReferenceMarkdownGenerator(sampleData); + const markdown = generator.generateFullDocument(); + + // Write to a test file + const outputPath = path.join(OUTPUT_DIR, "test-sample.mdx"); + await fs.mkdir(OUTPUT_DIR, { recursive: true }); + await fs.writeFile(outputPath, markdown, "utf-8"); + + console.log(`✅ Sample documentation generated at: ${outputPath}`); + console.log(`\n📄 View at: /docs/reference/test-sample`); +} + +// Main execution +if (require.main === module) { + // Check if --sample flag is passed + if (process.argv.includes("--sample")) { + generateWithSampleData().catch(console.error); + } else { + generateReferenceDocs().catch(console.error); + } +} + +export { generateReferenceDocs, generateWithSampleData }; diff --git a/scripts/openapi-to-markdown.mts b/scripts/openapi-to-markdown.mts new file mode 100644 index 000000000..141e4c4c1 --- /dev/null +++ b/scripts/openapi-to-markdown.mts @@ -0,0 +1,802 @@ +#!/usr/bin/env node + +import type { OpenAPIV3, OpenAPIV3_1 } from "openapi-types"; +import fs from "fs/promises"; +import path from "path"; + +// Type guard for OpenAPI 3.x documents +type OpenAPIDocument = OpenAPIV3.Document | OpenAPIV3_1.Document; +type OperationObject = OpenAPIV3.OperationObject | OpenAPIV3_1.OperationObject; +type ParameterObject = OpenAPIV3.ParameterObject | OpenAPIV3_1.ParameterObject; +type ReferenceObject = OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject; +type SchemaObject = OpenAPIV3.SchemaObject | OpenAPIV3_1.SchemaObject; +type ResponseObject = OpenAPIV3.ResponseObject | OpenAPIV3_1.ResponseObject; +type RequestBodyObject = OpenAPIV3.RequestBodyObject | OpenAPIV3_1.RequestBodyObject; +type MediaTypeObject = OpenAPIV3.MediaTypeObject | OpenAPIV3_1.MediaTypeObject; + +interface EndpointInfo { + path: string; + method: string; + operation: OperationObject; +} + +interface GeneratedMarkdown { + endpoint: string; + method: string; + content: string; +} + +/** + * Utility class for generating markdown documentation from OpenAPI specifications + */ +export class OpenAPIMarkdownGenerator { + private spec: OpenAPIDocument; + private serverUrl: string; + + constructor(spec: OpenAPIDocument) { + this.spec = spec; + // Extract base server URL + this.serverUrl = this.getServerUrl(); + } + + /** + * Get the base server URL from the OpenAPI spec + */ + private getServerUrl(): string { + if ("servers" in this.spec && this.spec.servers && this.spec.servers.length > 0) { + return this.spec.servers[0].url; + } + return "https://api.example.com"; + } + + /** + * Generate markdown for a specific endpoint operation + */ + public async generateEndpointMarkdown( + path: string, + method: string, + operation: OperationObject + ): Promise { + const sections: string[] = []; + + // Title + sections.push(`# ${operation.summary || this.generateTitle(path, method)}`); + sections.push(""); + + // Description + if (operation.description) { + sections.push(operation.description); + sections.push(""); + } + + // Endpoint + sections.push("## Endpoint"); + sections.push(""); + sections.push("```"); + sections.push(`${method.toUpperCase()} ${path}`); + sections.push("```"); + sections.push(""); + + // Parameters + const parameters = await this.generateParametersSection(operation.parameters); + if (parameters) { + sections.push(parameters); + sections.push(""); + } + + // Request Body + const requestBody = await this.generateRequestBodySection(operation.requestBody); + if (requestBody) { + sections.push(requestBody); + sections.push(""); + } + + // Request Example + const requestExample = this.generateRequestExample(path, method, operation); + if (requestExample) { + sections.push(requestExample); + sections.push(""); + } + + // Responses + const responses = await this.generateResponsesSection(operation.responses); + if (responses) { + sections.push(responses); + sections.push(""); + } + + // Authentication + const authentication = this.generateAuthenticationSection(operation); + sections.push(authentication); + sections.push(""); + + // Rate Limiting (if mentioned in description or x-rate-limit extension) + const rateLimiting = this.generateRateLimitingSection(operation); + if (rateLimiting) { + sections.push(rateLimiting); + sections.push(""); + } + + return sections.join("\n").trim(); + } + + /** + * Generate a title from path and method if summary is not provided + */ + private generateTitle(path: string, method: string): string { + // Extract meaningful parts from the path + const pathParts = path.split("/").filter(part => part && !part.startsWith("{")); + const resource = pathParts[pathParts.length - 1] || "resource"; + + // Convert to title case + const titleCase = (str: string) => + str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); + + const methodTitles: Record = { + get: "Get", + post: "Create", + put: "Update", + patch: "Patch", + delete: "Delete", + head: "Check", + options: "Options for" + }; + + return `${methodTitles[method.toLowerCase()] || titleCase(method)} ${titleCase(resource)}`; + } + + /** + * Generate parameters section + */ + private async generateParametersSection( + parameters?: (ParameterObject | ReferenceObject)[] + ): Promise { + if (!parameters || parameters.length === 0) { + return null; + } + + const sections: string[] = ["## Parameters"]; + + // Group parameters by location + const pathParams: ParameterObject[] = []; + const queryParams: ParameterObject[] = []; + const headerParams: ParameterObject[] = []; + + for (const param of parameters) { + const resolved = this.resolveReference(param) as ParameterObject; + if (!resolved) continue; + + switch (resolved.in) { + case "path": + pathParams.push(resolved); + break; + case "query": + queryParams.push(resolved); + break; + case "header": + headerParams.push(resolved); + break; + } + } + + // Path Parameters + if (pathParams.length > 0) { + sections.push(""); + sections.push("### Path Parameters"); + sections.push(""); + sections.push("| Name | Type | Required | Description |"); + sections.push("|------|------|----------|-------------|"); + + for (const param of pathParams) { + const type = this.getParameterType(param); + const required = param.required ? "Yes" : "No"; + const description = param.description || "-"; + sections.push(`| ${param.name} | ${type} | ${required} | ${description} |`); + } + } + + // Query Parameters + if (queryParams.length > 0) { + sections.push(""); + sections.push("### Query Parameters"); + sections.push(""); + sections.push("| Name | Type | Required | Default | Description |"); + sections.push("|------|------|----------|---------|-------------|"); + + for (const param of queryParams) { + const type = this.getParameterType(param); + const required = param.required ? "Yes" : "No"; + const defaultValue = this.getDefaultValue(param); + const description = param.description || "-"; + sections.push(`| ${param.name} | ${type} | ${required} | ${defaultValue} | ${description} |`); + } + } + + // Header Parameters + if (headerParams.length > 0) { + sections.push(""); + sections.push("### Header Parameters"); + sections.push(""); + sections.push("| Name | Type | Required | Description |"); + sections.push("|------|------|----------|-------------|"); + + for (const param of headerParams) { + const type = this.getParameterType(param); + const required = param.required ? "Yes" : "No"; + const description = param.description || "-"; + sections.push(`| ${param.name} | ${type} | ${required} | ${description} |`); + } + } + + return sections.join("\n"); + } + + /** + * Get parameter type from schema + */ + private getParameterType(param: ParameterObject): string { + if (!param.schema) return "string"; + + const schema = this.resolveReference(param.schema) as SchemaObject; + if (!schema) return "string"; + + if ("type" in schema) { + if (schema.type === "array" && "items" in schema) { + const itemsSchema = this.resolveReference(schema.items) as SchemaObject; + const itemType = itemsSchema && "type" in itemsSchema ? itemsSchema.type : "any"; + return `${itemType}[]`; + } + return schema.type as string; + } + + return "object"; + } + + /** + * Get default value from parameter + */ + private getDefaultValue(param: ParameterObject): string { + if (!param.schema) return "-"; + + const schema = this.resolveReference(param.schema) as SchemaObject; + if (!schema || !("default" in schema)) return "-"; + + if (schema.default === null) return "null"; + if (typeof schema.default === "string") return `"${schema.default}"`; + return String(schema.default); + } + + /** + * Generate request body section + */ + private async generateRequestBodySection( + requestBody?: RequestBodyObject | ReferenceObject + ): Promise { + if (!requestBody) return null; + + const resolved = this.resolveReference(requestBody) as RequestBodyObject; + if (!resolved || !resolved.content) return null; + + const sections: string[] = ["## Request Body"]; + + if (resolved.description) { + sections.push(""); + sections.push(resolved.description); + } + + sections.push(""); + sections.push(`**Required**: ${resolved.required ? "Yes" : "No"}`); + + // Get the first content type (usually application/json) + const contentTypes = Object.keys(resolved.content); + for (const contentType of contentTypes) { + const mediaType = resolved.content[contentType]; + + sections.push(""); + sections.push(`### Content Type: \`${contentType}\``); + + if (mediaType.schema) { + const schema = this.resolveReference(mediaType.schema) as SchemaObject; + const schemaExample = this.generateSchemaExample(schema); + + if (schemaExample) { + sections.push(""); + sections.push("```json"); + sections.push(schemaExample); + sections.push("```"); + } + } + + // Add example if provided + if (mediaType.example) { + sections.push(""); + sections.push("#### Example"); + sections.push(""); + sections.push("```json"); + sections.push(JSON.stringify(mediaType.example, null, 2)); + sections.push("```"); + } + } + + return sections.join("\n"); + } + + /** + * Generate request example + */ + private generateRequestExample( + path: string, + method: string, + operation: OperationObject + ): string | null { + const sections: string[] = ["## Request Example"]; + sections.push(""); + + // Build example URL with sample parameter values + let examplePath = path; + if (operation.parameters) { + for (const param of operation.parameters) { + const resolved = this.resolveReference(param) as ParameterObject; + if (resolved && resolved.in === "path") { + const exampleValue = this.getExampleValue(resolved); + examplePath = examplePath.replace(`{${resolved.name}}`, exampleValue); + } + } + } + + const fullUrl = `${this.serverUrl}${examplePath}`; + + sections.push("```bash"); + sections.push(`curl -X ${method.toUpperCase()} "${fullUrl}"`); + + // Add headers if needed + if (operation.parameters) { + for (const param of operation.parameters) { + const resolved = this.resolveReference(param) as ParameterObject; + if (resolved && resolved.in === "header") { + sections.push(` -H "${resolved.name}: ${this.getExampleValue(resolved)}"`); + } + } + } + + // Add request body if present + if (operation.requestBody) { + const requestBody = this.resolveReference(operation.requestBody) as RequestBodyObject; + if (requestBody && requestBody.content) { + const jsonContent = requestBody.content["application/json"]; + if (jsonContent && jsonContent.example) { + sections.push(` -H "Content-Type: application/json"`); + sections.push(` -d '${JSON.stringify(jsonContent.example)}'`); + } + } + } + + sections.push("```"); + + return sections.join(" \\\n"); + } + + /** + * Get example value for a parameter + */ + private getExampleValue(param: ParameterObject): string { + if (param.example) return String(param.example); + + if (param.schema) { + const schema = this.resolveReference(param.schema) as SchemaObject; + + // Check for examples array + if (schema && "examples" in schema && schema.examples && schema.examples.length > 0) { + return String(schema.examples[0]); + } + + // Check for example + if (schema && "example" in schema) return String(schema.example); + + // Generate based on type + if (schema && "type" in schema) { + switch (schema.type) { + case "integer": + return "1"; + case "boolean": + return "true"; + case "array": + return "item1,item2"; + default: + // Smart defaults based on parameter name + if (param.name.includes("address") || param.name === "principal") { + return "SP2X0TZ59D5SZ8ACQ6YMCHHNR2ZN51Z32E2CJ173"; + } + if (param.name.includes("hash")) { + return "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"; + } + if (param.name.includes("height")) { + return "100000"; + } + if (param.name.includes("id")) { + return "123e4567-e89b-12d3-a456-426614174000"; + } + return "example"; + } + } + } + + return "example"; + } + + /** + * Generate responses section + */ + private async generateResponsesSection( + responses?: OpenAPIV3.ResponsesObject | OpenAPIV3_1.ResponsesObject + ): Promise { + if (!responses) return null; + + const sections: string[] = ["## Response"]; + + // Sort response codes + const responseCodes = Object.keys(responses).sort(); + + for (const code of responseCodes) { + const response = this.resolveReference(responses[code]) as ResponseObject; + if (!response) continue; + + sections.push(""); + sections.push(`### ${code} ${this.getStatusText(code)}`); + sections.push(""); + + if (response.description) { + sections.push(response.description); + } + + if (response.content) { + for (const [contentType, mediaType] of Object.entries(response.content)) { + if (mediaType.schema) { + const schema = this.resolveReference(mediaType.schema) as SchemaObject; + const example = mediaType.example || this.generateSchemaExample(schema); + + if (example) { + sections.push(""); + sections.push("```json"); + sections.push(typeof example === "string" ? example : JSON.stringify(example, null, 2)); + sections.push("```"); + } + } + } + } + } + + // Add error responses table if there are multiple error codes + const errorCodes = responseCodes.filter(code => code.startsWith("4") || code.startsWith("5")); + if (errorCodes.length > 1) { + sections.push(""); + sections.push("### Error Responses"); + sections.push(""); + sections.push("| Status | Description |"); + sections.push("|--------|-------------|"); + + for (const code of errorCodes) { + const response = this.resolveReference(responses[code]) as ResponseObject; + if (response && response.description) { + sections.push(`| ${code} | ${response.description} |`); + } + } + } + + return sections.join("\n"); + } + + /** + * Get status text for HTTP status code + */ + private getStatusText(code: string): string { + const statusTexts: Record = { + "200": "OK", + "201": "Created", + "204": "No Content", + "400": "Bad Request", + "401": "Unauthorized", + "403": "Forbidden", + "404": "Not Found", + "500": "Internal Server Error", + "502": "Bad Gateway", + "503": "Service Unavailable" + }; + + return statusTexts[code] || ""; + } + + /** + * Generate authentication section + */ + private generateAuthenticationSection(operation: OperationObject): string { + const sections: string[] = ["## Authentication"]; + sections.push(""); + + // Check for security requirements + const security = operation.security || this.spec.security; + + if (!security || security.length === 0) { + sections.push("This endpoint does not require authentication."); + } else { + sections.push("This endpoint requires authentication:"); + sections.push(""); + + for (const requirement of security) { + for (const [scheme, scopes] of Object.entries(requirement)) { + // Look up the security scheme + if ("components" in this.spec && this.spec.components?.securitySchemes) { + const securityScheme = this.spec.components.securitySchemes[scheme]; + if (securityScheme && "type" in securityScheme) { + sections.push(`- **${scheme}**: ${securityScheme.type}`); + if (securityScheme.description) { + sections.push(` - ${securityScheme.description}`); + } + if (scopes && scopes.length > 0) { + sections.push(` - Required scopes: ${scopes.join(", ")}`); + } + } + } + } + } + } + + return sections.join("\n"); + } + + /** + * Generate rate limiting section + */ + private generateRateLimitingSection(operation: OperationObject): string | null { + // Check for x-rate-limit extension or mention in description + const hasRateLimit = operation.description?.toLowerCase().includes("rate limit") || + ("x-rate-limit" in operation); + + if (!hasRateLimit) return null; + + const sections: string[] = ["## Rate Limiting"]; + sections.push(""); + + // Default rate limiting info + sections.push("- **Rate Limit**: Standard API rate limits apply"); + sections.push("- **Headers**: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`"); + + return sections.join("\n"); + } + + /** + * Generate schema example + */ + private generateSchemaExample(schema?: SchemaObject | ReferenceObject): string | null { + if (!schema) return null; + + const resolved = this.resolveReference(schema) as SchemaObject; + if (!resolved) return null; + + // If there's an example, use it + if ("example" in resolved && resolved.example) { + return JSON.stringify(resolved.example, null, 2); + } + + // Generate based on schema type + return this.generateExampleFromSchema(resolved); + } + + /** + * Generate example from schema definition + */ + private generateExampleFromSchema(schema: SchemaObject, depth: number = 0): any { + // Prevent infinite recursion + if (depth > 5) return "..."; + + // Check for examples in the schema + if ("examples" in schema && schema.examples && schema.examples.length > 0) { + return schema.examples[0]; + } + + // Check for example (singular) in the schema + if ("example" in schema && schema.example !== undefined) { + return schema.example; + } + + // Handle anyOf/oneOf schemas + if ("anyOf" in schema && schema.anyOf && schema.anyOf.length > 0) { + return this.generateExampleFromSchema( + this.resolveReference(schema.anyOf[0]) as SchemaObject, + depth + ); + } + + if ("oneOf" in schema && schema.oneOf && schema.oneOf.length > 0) { + return this.generateExampleFromSchema( + this.resolveReference(schema.oneOf[0]) as SchemaObject, + depth + ); + } + + if ("type" in schema) { + switch (schema.type) { + case "string": + if ("enum" in schema && schema.enum) { + return schema.enum[0]; + } + // Check for format hints + if ("format" in schema) { + switch (schema.format) { + case "date-time": + return "2024-01-01T00:00:00Z"; + case "date": + return "2024-01-01"; + case "email": + return "user@example.com"; + case "uri": + return "https://example.com"; + default: + return "string"; + } + } + return "string"; + + case "number": + case "integer": + if ("minimum" in schema) { + return schema.minimum; + } + if ("maximum" in schema) { + return schema.maximum; + } + return schema.type === "integer" ? 1 : 1.0; + + case "boolean": + return true; + + case "array": + if ("items" in schema) { + const itemExample = this.generateExampleFromSchema( + this.resolveReference(schema.items) as SchemaObject, + depth + 1 + ); + return [itemExample]; + } + return []; + + case "object": + const obj: any = {}; + if ("properties" in schema && schema.properties) { + for (const [key, propSchema] of Object.entries(schema.properties)) { + const resolvedProp = this.resolveReference(propSchema) as SchemaObject; + obj[key] = this.generateExampleFromSchema(resolvedProp, depth + 1); + } + } + return obj; + + case "null": + return null; + + default: + return null; + } + } + + // If no type but has properties, treat as object + if ("properties" in schema && schema.properties) { + const obj: any = {}; + for (const [key, propSchema] of Object.entries(schema.properties)) { + const resolvedProp = this.resolveReference(propSchema) as SchemaObject; + obj[key] = this.generateExampleFromSchema(resolvedProp, depth + 1); + } + return obj; + } + + return {}; + } + + /** + * Resolve $ref references + */ + private resolveReference(obj: T | ReferenceObject): T | null { + if (!obj || typeof obj !== "object") return obj; + + if ("$ref" in obj) { + // Simple reference resolution - assumes local references + const refPath = obj.$ref.replace("#/", "").split("/"); + let resolved: any = this.spec; + + for (const part of refPath) { + resolved = resolved[part]; + if (!resolved) return null; + } + + return resolved as T; + } + + return obj; + } + + /** + * Process all operations in the OpenAPI spec + */ + public async generateAllEndpoints(): Promise> { + const results = new Map(); + + if (!this.spec.paths) { + return results; + } + + for (const [path, pathItem] of Object.entries(this.spec.paths)) { + if (!pathItem) continue; + + // Process each HTTP method + const methods = ["get", "post", "put", "patch", "delete", "head", "options"] as const; + + for (const method of methods) { + const operation = pathItem[method]; + if (operation && typeof operation === "object" && "responses" in operation) { + const markdown = await this.generateEndpointMarkdown(path, method, operation); + const key = `${method.toUpperCase()} ${path}`; + + results.set(key, { + endpoint: path, + method: method.toUpperCase(), + content: markdown + }); + } + } + } + + return results; + } +} + +/** + * Utility function to generate markdown for a single endpoint + */ +export async function generateMarkdownForEndpoint( + specPath: string, + endpoint: string, + method: string +): Promise { + try { + const specContent = await fs.readFile(specPath, "utf-8"); + const spec = JSON.parse(specContent) as OpenAPIDocument; + + const generator = new OpenAPIMarkdownGenerator(spec); + + // Find the operation + if (!spec.paths || !spec.paths[endpoint]) { + console.error(`Endpoint ${endpoint} not found in spec`); + return null; + } + + const pathItem = spec.paths[endpoint]; + const operation = pathItem[method.toLowerCase() as keyof typeof pathItem]; + + if (!operation || typeof operation !== "object" || !("responses" in operation)) { + console.error(`Method ${method} not found for endpoint ${endpoint}`); + return null; + } + + return await generator.generateEndpointMarkdown(endpoint, method, operation); + } catch (error) { + console.error(`Error generating markdown for ${method} ${endpoint}:`, error); + return null; + } +} + +/** + * Utility function to generate markdown for all endpoints in a spec + */ +export async function generateMarkdownForAllEndpoints( + specPath: string +): Promise> { + try { + const specContent = await fs.readFile(specPath, "utf-8"); + const spec = JSON.parse(specContent) as OpenAPIDocument; + + const generator = new OpenAPIMarkdownGenerator(spec); + return await generator.generateAllEndpoints(); + } catch (error) { + console.error(`Error generating markdown for spec:`, error); + return new Map(); + } +} \ No newline at end of file diff --git a/scripts/split.js b/scripts/split.js deleted file mode 100644 index 1cc21d833..000000000 --- a/scripts/split.js +++ /dev/null @@ -1,50 +0,0 @@ -const fs = require('fs'); -const path = require('path'); - -// Get the arguments from the command line -const args = process.argv.slice(2); -const fileName = args[0]; // The name of the file to process (e.g., 'stacks-api') - -// Define the input file path and output directory -const inputFilePath = path.join(__dirname, `../openapi/spec/${fileName}.mdx`); -const outputBaseDir = path.join(__dirname, '../tmp'); - -// Read the content of the input MDX file -let content = fs.readFileSync(inputFilePath, 'utf8'); - -// Remove any component tags from the content -content = content.replace(/<\/Root>/g, ''); - -// Split the content into sections based on the tags -const sections = content.split('').slice(1); // Remove the first item if it's empty - -// Ensure the output directory exists -if (!fs.existsSync(outputBaseDir)) { - fs.mkdirSync(outputBaseDir, { recursive: true }); -} - -// Process each section -sections.forEach((section, index) => { - // Re-add the tag to the section - section = `${section}`; - - // Find the route for naming the file and directory structure - const routeMatch = section.match(/route={"([^"]+)"}/); - if (!routeMatch) { - console.error('Could not find route for a section'); - return; - } - const routeParts = routeMatch[1].split('/').filter(Boolean); // Split and remove any empty strings - const specificEndpoint = routeParts.join('-'); // Join parts with hyphens - - // Add syntax to left-align the content of each markdown table - section = section.replace(/\| ([-:]+) \| ([-:]+) \|/g, '| :------ | :------ |'); - - // Write the section to a new MDX file, ensuring space between frontmatter and content - const outputFileName = `${specificEndpoint}.mdx`; - const outputPath = path.join(outputBaseDir, outputFileName); - fs.writeFileSync(outputPath, section); - console.log(`Generated ${outputPath}`); -}); - -console.log('Splitting complete.'); \ No newline at end of file diff --git a/scripts/update-index.mts b/scripts/update-index.mts deleted file mode 100644 index 13fa4c521..000000000 --- a/scripts/update-index.mts +++ /dev/null @@ -1,37 +0,0 @@ -import { readFileSync } from "node:fs"; -import { resolve } from "node:path"; -import env from "@next/env"; -import algosearch from "algoliasearch"; -import { sync } from "fumadocs-core/search-algolia/server"; -import type { SearchIndex } from "fumadocs-mdx"; - -env.loadEnvConfig(process.cwd()); - -const indexes = JSON.parse( - readFileSync(resolve("./.next/server/chunks/fumadocs_search.json")).toString() -) as SearchIndex[]; - -if (!process.env.NEXT_PUBLIC_ALGOLIA_API_KEY) { - console.warn("Algolia API Key not found, skip updating search index."); -} else { - const client = algosearch( - process.env.NEXT_PUBLIC_ALGOLIA_APP_ID || "", - process.env.NEXT_PUBLIC_ALGOLIA_API_KEY || "" - ); - - void sync(client, { - document: process.env.NEXT_PUBLIC_ALGOLIA_INDEX, - documents: indexes.map((docs) => ({ - _id: docs.id, - title: docs.title, - url: docs.url, - structured: docs.structuredData, - })), - }) - .then(() => { - console.log("search updated"); - }) - .catch((e) => { - console.error(e); - }); -} diff --git a/scripts/utils/api-endpoint-mapping.mts b/scripts/utils/api-endpoint-mapping.mts new file mode 100644 index 000000000..762b55949 --- /dev/null +++ b/scripts/utils/api-endpoint-mapping.mts @@ -0,0 +1,109 @@ +#!/usr/bin/env node + +import fs from "fs/promises"; +import path from "path"; +import { glob } from "glob"; + +interface EndpointMapping { + // URL path -> generated file mapping + [urlPath: string]: { + apiName: string; + method: string; + endpoint: string; + generatedFile: string; + }; +} + +/** + * Load all MDX files and extract APIPage usage to build URL mappings + */ +export async function buildEndpointMappings(): Promise { + const contentDir = path.join(process.cwd(), "content", "docs"); + const pattern = path.join(contentDir, "apis", "**/*.mdx"); + + const files = await glob(pattern, { + ignore: ["**/node_modules/**", "**/dist/**"] + }); + + const mappings: EndpointMapping = {}; + + for (const file of files) { + try { + const content = await fs.readFile(file, "utf-8"); + + // Extract APIPage component + const apiPageMatch = content.match(/]+)>/); + if (!apiPageMatch) continue; + + const propsString = apiPageMatch[1]; + + // Extract document + const documentMatch = propsString.match(/document=["']([^"']+)["']/); + if (!documentMatch) continue; + + // Extract API name from document path + const apiNameMatch = documentMatch[1].match(/\/([^/]+)\.json$/); + if (!apiNameMatch) continue; + + const apiName = apiNameMatch[1].replace("-api", ""); + + // Extract operations + const operationsMatch = propsString.match(/operations=\{(\[[^\]]+\])\}/); + if (!operationsMatch) continue; + + // Parse operations + const operationsStr = operationsMatch[1]; + const operationRegex = /\{\s*path:\s*['"`]([^'"`]+)['"`]\s*,\s*method:\s*['"`]([^'"`]+)['"`]\s*\}/g; + + let opMatch; + while ((opMatch = operationRegex.exec(operationsStr)) !== null) { + const endpoint = opMatch[1]; + const method = opMatch[2].toUpperCase(); + + // Calculate URL path from file path + const relativePath = path.relative(contentDir, file); + const urlPath = "/" + relativePath.replace(/\.mdx?$/, ""); + + // Generate the expected markdown filename + const generatedFile = `${method} ${endpoint}` + .toLowerCase() + .replace(/[{}]/g, "") + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-|-$/g, "") + ".md"; + + mappings[urlPath] = { + apiName, + method, + endpoint, + generatedFile + }; + } + } catch (error) { + console.error(`Error processing ${file}:`, error); + } + } + + return mappings; +} + +/** + * Save the mapping to a JSON file + */ +export async function saveMappings(mappings: EndpointMapping): Promise { + const mappingPath = path.join(process.cwd(), "generated", "api-mappings.json"); + await fs.writeFile(mappingPath, JSON.stringify(mappings, null, 2)); + console.log(`✔️ Saved API endpoint mappings to ${mappingPath}`); +} + +/** + * Load saved mappings + */ +export async function loadMappings(): Promise { + try { + const mappingPath = path.join(process.cwd(), "generated", "api-mappings.json"); + const content = await fs.readFile(mappingPath, "utf-8"); + return JSON.parse(content); + } catch { + return {}; + } +} \ No newline at end of file diff --git a/snippets/api-keys.mdx b/snippets/api-keys.mdx deleted file mode 100644 index dfefe937a..000000000 --- a/snippets/api-keys.mdx +++ /dev/null @@ -1,59 +0,0 @@ -Developers have open access to Hiro's APIs without the use of an API key, but are subject to [Hiro's rate limit policy](./rate-limiting). For developers who need access beyond these rate limits, we provide API keys. - - -If you're interested in obtaining an API key, you can generate one for free in the [Hiro Platform](https://platform.hiro.so) by creating an account. - -All API keys are set by default to the free "starter" account tier, which comes with a 900RPM rate limit. For builders who need access to higher API rate limits, dedicated support channels, and reliability guarantees through SLAs, you can upgrade your account tier through the Hiro Platform. - - -## Usage with cURL - -The API key is passed in the `header` of your HTTP API request with `x-api-key`. - -```terminal -$ curl https://api.hiro.so/... -H 'x-api-key: ' -``` - -## Usage with Node - -This snippet shows how to perform a `fetch` request with your API key by including it in the request headers. - -```ts fetch.ts -async function makeApiRequest(apiKey: string) { - const url = `https://api.hiro.so/`; - const response = await fetch(url, { - headers: { - "x-api-key": apiKey - } - }); - return response.json(); -} -``` - -## Usage with Stacks.js - -```ts client.ts -import { createApiKeyMiddleware, createFetchFn } from "@stacks/common"; -import { makeContractCall } from '@stacks/transactions'; - -const apiMiddleware = createApiKeyMiddleware({ - apiKey: "", -}); - -const customFetchFn = createFetchFn(apiMiddleware); - -const txOptions = { - // ... standard transaction options - client: { - fetch: customFetchFn, - }, -}; - -const transaction = await makeContractCall(txOptions); -``` - - -The API key is passed in the header of your HTTP API request and is used only for private use, like in server-side applications. - -If you use the API key in your client-side application, attackers can capture it using the client tools (E.g., browser console) and abuse your API key. - diff --git a/snippets/contributors-guide.mdx b/snippets/contributors-guide.mdx deleted file mode 100644 index 48d9139fa..000000000 --- a/snippets/contributors-guide.mdx +++ /dev/null @@ -1,62 +0,0 @@ -import { Steps, Step } from 'fumadocs-ui/components/steps'; - - -Some examples use the `gh` CLI package for creating issues and forking. To install that package, [click here](https://github.com/cli/cli). - - -## Issues - -If you find content that is obsolete, technically inaccurate, or unclear, start by creating an issue. - -This is a great way to give specific feedback and ensure the technical content is up-to-date and technically accurate. - -```terminal -$ gh issue create -``` - - -For creating an issue via the web, go [here](https://github.com/hirosystems/docs/issues/new). - - -## Pull requests - - - - To suggest more comprehensive changes or make updates yourself, feel free to make documentation changes by forking the repo and then submitting a pull request. - - Fork the repo and clone it. - - ```terminal - $ gh repo fork hirosystems/docs - ``` - - - For forking via the web, go [here](https://github.com/hirosystems/docs/fork). - - - - Create a new branch and make your changes. - - ```terminal - $ git checkout -b my-branch - ``` - - - Commit your changes with a message with a brief summary message: - - ```terminal - $ git commit -m "commit message" - ``` - - - Push up your branch: - - ```terminal - $ git push origin my-branch - ``` - - - - -PR titles should be descriptive enough for reviewers to understand *what* is being changed and have a description that explains *why* the change is being made. - diff --git a/snippets/rate-limiting.mdx b/snippets/rate-limiting.mdx deleted file mode 100644 index 198f3183a..000000000 --- a/snippets/rate-limiting.mdx +++ /dev/null @@ -1,40 +0,0 @@ -## API rate limits - -You can access all of Hiro's API services without an API key, but you are subject to rate limits of 25 RPM, per client IP. To build with higher rate limits, you can generate a free API key in the Hiro Platform that is set to the free "starter" plan as a default, and you can upgrade your account to a [higher tier](https://www.hiro.so/pricing) as needed: - -| Tiers | API RPM | Stacks L2 requests / month | Bitcoin L1 requests / month | -|:---------------|:--------|:---------------------------|:----------------------------| -| No API key | 25 | n/a | n/a | -| Free / Starter | 900 | 150K | 50K | -| $99 / Build | 3K | 15M | 500K | -| $599 / Scale | 7K | 75M | 5M | -| Enterprise | Custom | Custom | Custom | - -With a single API key, you gain access to Hiro's suite of API services that span Bitcoin and Stacks: - -**Bitcoin L1 API services** - -- [Ordinals API](/bitcoin/ordinals/api) (includes BRC-20 support) -- [Runes API](/bitcoin/runes/api) - -**Stacks L2 API services** - -- [Stacks Blockchain API](/stacks/api) -- [Token Metadata API](/stacks/token-metadata-api) - -These new rate limits help us ensure fair usage of Hiro APIs and provide the best possible service as our community of developers and applications grow. - - -You can create one for free in the [Hiro Platform](https://platform.hiro.so) by creating an account. - - -## STX / sBTC testnet faucet rate limits - -Note: these faucets are for Stacks and sBTC testnet tokens, which have no monetary value. - -| Type | Rate Limit | -|:-----------------------------|:-----------------------------| -| Stacking requests | 1 request per 2 days | -| Regular STX / sBTC requests | 1 request per minute (RPM) | - -To use the faucets, visit the [Hiro Platform Faucet](https://platform.hiro.so/faucet). diff --git a/source.config.ts b/source.config.ts new file mode 100644 index 000000000..6989d2322 --- /dev/null +++ b/source.config.ts @@ -0,0 +1,64 @@ +import { + defineConfig, + defineDocs, + frontmatterSchema, +} from "fumadocs-mdx/config"; +import { + remarkCodeHike, + recmaCodeHike, + type CodeHikeConfig, +} from "codehike/mdx"; +import remarkDirective from "remark-directive"; +import { remarkCustomDirectives } from "./lib/remark-custom-directives"; +import { z } from "zod"; + +export const docs = defineDocs({ + dir: "content/docs", + docs: { + schema: frontmatterSchema.extend({ + llm: z.boolean().optional(), + isNew: z.boolean().optional(), + publishedAt: z.string().optional(), + sidebarTitle: z.string().optional(), + root: z.boolean().optional(), + tags: z.array(z.string()).optional(), + labels: z.array(z.string()).optional(), + type: z.string().optional(), + isRpc: z.boolean().optional(), + // Interactive layout fields + interactive: z.boolean().optional(), + interactiveFeatures: z.array(z.string()).optional(), + interactiveLinks: z + .array( + z.object({ + title: z.string(), + href: z.string(), + icon: z.string().optional(), + }) + ) + .optional(), + }), + }, + meta: { + // options for `meta` collection + }, +}); + +const chConfig: CodeHikeConfig = { + components: { + code: "DocsKitCode", + inlineCode: "DocsKitInlineCode", + }, +}; + +export default defineConfig({ + mdxOptions: { + remarkPlugins: (v) => [ + [remarkCodeHike, chConfig], + remarkDirective, + remarkCustomDirectives, + ...v, + ], + recmaPlugins: [[recmaCodeHike, chConfig]], + }, +}); diff --git a/tailwind.config.js b/tailwind.config.js deleted file mode 100644 index 960db91b4..000000000 --- a/tailwind.config.js +++ /dev/null @@ -1,159 +0,0 @@ -const { createPreset } = require('fumadocs-ui/tailwind-plugin'); - -/** @type {import('tailwindcss').Config} */ -module.exports = { - darkMode: ['class'], - content: [ - './components/**/*.{ts,tsx}', - './app/**/*.{ts,tsx}', - './content/**/*.mdx', - './mdx-components.tsx', - './node_modules/fumadocs-ui/dist/**/*.js', - './node_modules/fumadocs-openapi/dist/**/*.js', - ], - presets: [createPreset({ - preset: 'default' - })], - theme: { - extend: { - colors: { - 'ch-border': 'hsl(var(--border))', - 'ch-selection': 'var(--ch-22)', - 'ch-tabs-background': 'hsl(var(--card))', - 'ch-tab-active-foreground': 'hsl(var(--card-foreground))', - 'ch-tab-inactive-foreground': 'hsl(var(--muted-foreground))', - 'ch-code': 'hsl(var(--code))', - 'ch-active-border': 'hsl(var(--hiro))', - 'ch-line-number': 'var(--ch-26)', - background: 'hsl(var(--background))', - foreground: 'hsl(var(--foreground))', - card: { - DEFAULT: 'hsl(var(--card))', - foreground: 'hsl(var(--card-foreground))' - }, - popover: { - DEFAULT: 'hsl(var(--popover))', - foreground: 'hsl(var(--popover-foreground))' - }, - primary: { - DEFAULT: 'hsl(var(--primary))', - foreground: 'hsl(var(--primary-foreground))' - }, - secondary: { - DEFAULT: 'hsl(var(--secondary))', - foreground: 'hsl(var(--secondary-foreground))' - }, - muted: { - DEFAULT: 'hsl(var(--muted))', - foreground: 'var(--muted-foreground)' - }, - accent: { - DEFAULT: 'hsl(var(--accent))', - foreground: 'hsl(var(--accent-foreground))' - }, - destructive: { - DEFAULT: 'hsl(var(--destructive))', - foreground: 'hsl(var(--destructive-foreground))' - }, - border: 'hsl(var(--border))', - input: 'hsl(var(--input))', - ring: 'hsl(var(--ring))', - hiro: 'hsl(var(--hiro) / )', - 'card-hover': 'hsl(var(--card-hover) / )', - icon: '(var(--icon)', - inverted: 'var(--inverted)', - code: 'hsl(var(--code) / )', - highlight: 'hsl(var(--highlight) / )', - content: 'hsl(var(--content) / )', - dark: 'var(--dark)', - gradient: 'var(--gradient)', - contrast: 'hsl(var(--contrast) / )', - chart: { - '1': 'hsl(var(--chart-1))', - '2': 'hsl(var(--chart-2))', - '3': 'hsl(var(--chart-3))', - '4': 'hsl(var(--chart-4))', - '5': 'hsl(var(--chart-5))' - }, - sidebar: { - DEFAULT: 'hsl(var(--sidebar-background))', - foreground: 'hsl(var(--sidebar-foreground))', - primary: 'hsl(var(--sidebar-primary))', - 'primary-foreground': 'hsl(var(--sidebar-primary-foreground))', - accent: 'hsl(var(--sidebar-accent))', - 'accent-foreground': 'hsl(var(--sidebar-accent-foreground))', - border: 'hsl(var(--sidebar-border))', - ring: 'hsl(var(--sidebar-ring))' - } - }, - fontFamily: { - sans: ['var(--font-geist-sans)'], - mono: ["var(--font-aeonikMono)"], - aeonik: ['var(--font-aeonik)'], - aeonikFono: ['var(--font-aeonikFono)'], - inter: ['var(--font-inter)'] - }, - backgroundImage: { - 'gradient-radial': 'radial-gradient(circle, var(--tw-gradient-stops))', - 'repeat-gradient-to-r': 'repeating-linear-gradient(to right, var(--tw-gradient-stops))', - 'repeat-gradient-to-br': 'repeating-linear-gradient(to bottom right, var(--tw-gradient-stops))' - }, - keyframes: { - updown: { - 'from, to': { - transform: 'translateY(-20px)' - }, - '50%': { - transform: 'translateY(20px)' - } - }, - light: { - 'from, to': { - opacity: '0.7' - }, - '50%': { - opacity: '1' - } - }, - stroke: { - from: { - 'stroke-dasharray': '1000' - }, - to: { - 'stroke-dasharray': '1000', - 'stroke-dashoffset': '2000' - } - }, - marquee: { - from: { - transform: 'translateX(0)' - }, - to: { - transform: 'translateX(calc(-100% - var(--gap)))' - } - }, - 'marquee-vertical': { - from: { - transform: 'translateY(0)' - }, - to: { - transform: 'translateY(calc(-100% - var(--gap)))' - } - } - }, - animation: { - stroke: 'stroke 5s linear infinite', - light: 'light 2s ease-in-out infinite', - updown: 'updown 3s ease-in-out infinite', - marquee: 'marquee var(--duration) linear infinite', - 'marquee-vertical': 'marquee-vertical var(--duration) linear infinite' - }, - borderRadius: { - lg: 'var(--radius)', - md: 'calc(var(--radius) - 2px)', - sm: 'calc(var(--radius) - 4px)' - } - } - }, - plugins: [require('tailwindcss-animate')], -}; diff --git a/tsconfig.json b/tsconfig.json index 47d1cd9d3..4fd260f7f 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -10,12 +10,13 @@ "noEmit": true, "esModuleInterop": true, "module": "esnext", - "moduleResolution": "node", + "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "paths": { + "@/.source": ["./.source/index.ts"], "@/*": ["./*"] }, "plugins": [ diff --git a/types/index.ts b/types/index.ts new file mode 100644 index 000000000..68ff437a2 --- /dev/null +++ b/types/index.ts @@ -0,0 +1,77 @@ +export interface HeadingProps extends React.HTMLAttributes { + children: React.ReactNode; + id?: string; + className?: string; +} + +export type RecipeType = "typescript" | "bash" | "clarity"; + +export type RecipeCategory = + | "stacks-js" + | "clarity" + | "bitcoin" + | "chainhook" + | "api" + | "clarinet"; + +export const CategorySubTags = { + "stacks-js": [ + "web", + "authentication", + "transactions", + "signing", + "smart-contracts", + "utils", + ] as const, + + clarity: [] as const, + + bitcoin: ["transactions", "signing"] as const, + + chainhook: [] as const, + + api: [ + "token-metadata", + "signer-metrics", + "rpc", + "platform", + "ordinals", + "runes", + ] as const, + + clarinet: ["testing", "deployment"] as const, +} as const; + +export type SubTagsForCategory = { + [K in RecipeCategory]: (typeof CategorySubTags)[K][number]; +}; + +export type RecipeSubTag = SubTagsForCategory[RecipeCategory]; + +// Base metadata from front matter +export interface RecipeMetadata { + id: string; + title: string; + description: string; + date: string; + categories: RecipeCategory[]; + tags: SubTagsForCategory[RecipeCategory][]; + dependencies?: Record; + external_url?: string; +} + +// Code blocks extracted from markdown content +export interface RecipeFile { + name: string; + path: string; + type: RecipeType; + content: string; + snippet?: string; + preview?: any; +} + +// Complete recipe with content and extracted files +export interface Recipe extends RecipeMetadata { + content: string; // The full markdown content + files: RecipeFile[]; // Extracted code blocks +} diff --git a/types/nav.ts b/types/nav.ts new file mode 100644 index 000000000..047950ada --- /dev/null +++ b/types/nav.ts @@ -0,0 +1,16 @@ +export interface NavItem { + title: string; + href?: string; + disabled?: boolean; + external?: boolean; + label?: string; + description?: string; +} + +export interface NavItemWithChildren extends NavItem { + items: NavItem[]; +} + +export interface MainNavItem extends NavItem {} + +export interface SidebarNavItem extends NavItemWithChildren {} diff --git a/types/recipes.ts b/types/recipes.ts deleted file mode 100644 index f199211c9..000000000 --- a/types/recipes.ts +++ /dev/null @@ -1,71 +0,0 @@ -export type RecipeType = "typescript" | "bash" | "clarity"; - -export type RecipeCategory = - | "stacks-js" - | "clarity" - | "bitcoin" - | "chainhook" - | "api" - | "clarinet"; - -export const CategorySubTags = { - "stacks-js": [ - "web", - "authentication", - "transactions", - "signing", - "smart-contracts", - "utils", - ] as const, - - clarity: [] as const, - - bitcoin: ["transactions", "signing"] as const, - - chainhook: [] as const, - - api: [ - "token-metadata", - "signer-metrics", - "rpc", - "platform", - "ordinals", - "runes", - ] as const, - - clarinet: ["testing", "deployment"] as const, -} as const; - -export type SubTagsForCategory = { - [K in RecipeCategory]: (typeof CategorySubTags)[K][number]; -}; - -export type RecipeSubTag = SubTagsForCategory[RecipeCategory]; - -// Base metadata from front matter -export interface RecipeMetadata { - id: string; - title: string; - description: string; - date: string; - categories: RecipeCategory[]; - tags: SubTagsForCategory[RecipeCategory][]; - dependencies?: Record; - external_url?: string; -} - -// Code blocks extracted from markdown content -export interface RecipeFile { - name: string; - path: string; - type: RecipeType; - content: string; - snippet?: string; - preview?: any; -} - -// Complete recipe with content and extracted files -export interface Recipe extends RecipeMetadata { - content: string; // The full markdown content - files: RecipeFile[]; // Extracted code blocks -} diff --git a/utils/data.ts b/utils/data.ts deleted file mode 100644 index bc582e2fe..000000000 --- a/utils/data.ts +++ /dev/null @@ -1,30 +0,0 @@ -export const guides = [ - { - title: "How to use your API Key with Stacks.js", - description: - "Learn the steps to integrate your API key with Stacks.js for seamless application development.", - tags: ["stacks.js", "api keys"], - createdAt: new Date().toLocaleDateString(), - }, - { - title: "Common Clarity Errors", - description: - "Identify and resolve the most frequent errors encountered while coding with Clarity.", - tags: ["smart contracts"], - createdAt: new Date().toLocaleDateString(), - }, - { - title: "How to get sBTC testnet tokens", - description: - "A guide on acquiring sBTC tokens on the testnet to help you test your applications on Stacks.", - tags: ["sbtc"], - createdAt: new Date().toLocaleDateString(), - }, - { - title: "Validate off-chain price feeds with Pyth", - description: - "Ensure the accuracy of your off-chain price feeds by integrating with the Pyth network.", - tags: ["oracles"], - createdAt: new Date().toLocaleDateString(), - }, -]; diff --git a/utils/modes.ts b/utils/modes.ts deleted file mode 100644 index 763401239..000000000 --- a/utils/modes.ts +++ /dev/null @@ -1,25 +0,0 @@ -/* eslint-disable import/no-relative-packages -- required */ -import { LayoutIcon, LibraryIcon, type LucideIcon } from "lucide-react"; -import { StacksIcon, BitcoinIcon } from "@/components/ui/icon"; - -export interface Mode { - param: string; - name: string; - type: "tab" | "link"; - icon?: React.ElementType; -} - -export const modes: Mode[] = [ - { - param: "stacks", - name: "Stacks", - type: "tab", - icon: StacksIcon, - }, - { - param: "bitcoin", - name: "Bitcoin", - type: "tab", - icon: BitcoinIcon, - }, -]; diff --git a/utils/process-markdown-links.ts b/utils/process-markdown-links.ts new file mode 100644 index 000000000..64a6fc198 --- /dev/null +++ b/utils/process-markdown-links.ts @@ -0,0 +1,73 @@ +/** + * Processes markdown content to convert relative links to absolute URLs with .md extension + * This is used when copying markdown content for LLMs + */ +export function processMarkdownLinks(content: string, baseUrl: string = "https://docs.hiro.so"): string { + // Process standard markdown links: [text](/path) + content = content.replace( + /\[([^\]]+)\]\(\/([^)]+)\)/g, + (match, text, path) => { + // Skip if it's already an absolute URL + if (path.startsWith('http://') || path.startsWith('https://')) { + return match; + } + + // Remove any trailing slashes + const cleanPath = path.replace(/\/$/, ''); + + // Don't add .md if it already has an extension or is an anchor + if (cleanPath.includes('.') || cleanPath.includes('#')) { + return `[${text}](${baseUrl}/${cleanPath})`; + } + + // Add .md extension for documentation links + return `[${text}](${baseUrl}/${cleanPath}.md)`; + } + ); + + // Process HTML links: + content = content.replace( + /href="\/([^"]+)"/g, + (match, path) => { + // Skip if it's already an absolute URL + if (path.startsWith('http://') || path.startsWith('https://')) { + return match; + } + + // Remove any trailing slashes + const cleanPath = path.replace(/\/$/, ''); + + // Don't add .md if it already has an extension or is an anchor + if (cleanPath.includes('.') || cleanPath.includes('#')) { + return `href="${baseUrl}/${cleanPath}"`; + } + + // Add .md extension for documentation links + return `href="${baseUrl}/${cleanPath}.md"`; + } + ); + + // Process reference-style links: [text]: /path + content = content.replace( + /^\[([^\]]+)\]:\s*\/(.+)$/gm, + (match, ref, path) => { + // Skip if it's already an absolute URL + if (path.startsWith('http://') || path.startsWith('https://')) { + return match; + } + + // Remove any trailing slashes + const cleanPath = path.replace(/\/$/, ''); + + // Don't add .md if it already has an extension + if (cleanPath.includes('.') || cleanPath.includes('#')) { + return `[${ref}]: ${baseUrl}/${cleanPath}`; + } + + // Add .md extension for documentation links + return `[${ref}]: ${baseUrl}/${cleanPath}.md`; + } + ); + + return content; +} \ No newline at end of file diff --git a/utils/source.ts b/utils/source.ts deleted file mode 100644 index 044156810..000000000 --- a/utils/source.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { writeFileSync } from "node:fs"; -import path from "node:path"; -import { createMDXSource, defaultSchemas } from "fumadocs-mdx"; -import type { StructuredData } from "fumadocs-core/mdx-plugins"; -import { PHASE_PRODUCTION_BUILD } from "next/constants"; -import { z } from "zod"; -import type { InferMetaType, InferPageType } from "fumadocs-core/source"; -import { loader } from "fumadocs-core/source"; -import { icons as lucideIcons } from "lucide-react"; -import type { LucideIcon } from "lucide-react"; -import { map } from "@/.map"; -import { create } from "@/components/ui/icon"; -import { StacksIcon, BitcoinIcon } from "@/components/ui/icon"; - -const customIcons = { - StacksIcon, - BitcoinIcon, -}; - -const icons = { ...lucideIcons, ...customIcons } as any; - -export function icon(iconName: string) { - if (iconName in icons) { - return create({ icon: icons[iconName as keyof typeof icons] }); - } -} - -const frontmatterSchema = defaultSchemas.frontmatter.extend({ - preview: z.string().optional() as any, - toc: z.boolean().default(true) as any, - index: z.boolean().default(false) as any, -}); - -export const utils = loader({ - baseUrl: "/", - rootDir: "docs", - icon(icon) { - if (icon in icons) - return create({ icon: icons[icon as keyof typeof icons] }); - }, - source: createMDXSource(map, { schema: { frontmatter: frontmatterSchema } }), -}); - -export type Page = InferPageType; -export type Meta = InferMetaType; - -export interface Index { - id: string; - title: string; - description?: string; - url: string; - structuredData: StructuredData; -} - -// Access and export MDX pages data to json file -// So that we can update search indexes after the build -const g = globalThis as unknown as { - __NEXT_DOCS_INDEX_UPDATED?: boolean; -}; - -if ( - process.env.NEXT_PHASE === PHASE_PRODUCTION_BUILD && - !g.__NEXT_DOCS_INDEX_UPDATED -) { - const mapPath = path.resolve("./.next/_map_indexes.json"); - const indexes: Index[] = utils.files.flatMap((file) => { - if (file.type !== "page") return []; - - return { - id: file.url, - title: file.data.title, - description: file.data.description, - url: file.url, - structuredData: file.data.exports.structuredData, - }; - }); - - writeFileSync(mapPath, JSON.stringify(indexes)); - - g.__NEXT_DOCS_INDEX_UPDATED = true; -} diff --git a/vercel.json b/vercel.json index 7711172b0..a907ddbf7 100644 --- a/vercel.json +++ b/vercel.json @@ -12,48 +12,17 @@ } ], "redirects": [ - { "source": "/chainhook/:path*", "destination": "/stacks/chainhook", "permanent": true }, - { "source": "/stacks/chainhook/concepts/bitcoin-predicates", "destination": "/stacks/chainhook/concepts/predicate-design", "permanent": true }, - { "source": "/stacks/chainhook/concepts/stacks-predicates", "destination": "/stacks/chainhook/concepts/predicate-design", "permanent": true }, - { "source": "/clarinet/:path*", "destination": "/stacks/clarinet", "permanent": true }, - { "source": "/stacks/explorer/:path*", "destination": "https://explorer.hiro.so", "permanent": true }, - { "source": "/explorer/:path*", "destination": "https://explorer.hiro.so", "permanent": true }, - { "source": "/hiro-archive/:path*", "destination": "/stacks/archive", "permanent": true }, - { "source": "/platform/:path*", "destination": "/stacks/platform", "permanent": true }, - { "source": "/stacks.js/:path*", "destination": "/stacks/stacks.js", "permanent": true }, - { "source": "/stacks-blockchain-api/:path*", "destination": "/stacks/api", "permanent": true }, - { "source": "/api/:path*", "destination": "/stacks/api", "permanent": true }, - { "source": "/stacks/api/fees/estimate", "destination": "/stacks/rpc-api/fees/estimate", "permanent": true }, - { "source": "/stacks/api/fees/transfer-estimate", "destination": "/stacks/rpc-api/fees/transfer-estimate", "permanent": true }, - { "source": "/stacks/api/info/core-api", "destination": "/stacks/rpc-api/info/core-api", "permanent": true }, - { "source": "/stacks/api/info/pox-details", "destination": "/stacks/rpc-api/pox/pox-details", "permanent": true }, - { "source": "/stacks/api/names/name-price", "destination": "/stacks/rpc-api/names/name-price", "permanent": true }, - { "source": "/stacks/api/names/namespace-price", "destination": "/stacks/rpc-api/names/namespace-price", "permanent": true }, - { "source": "/stacks/api/smart-contracts/interface", "destination": "/stacks/rpc-api/smart-contracts/interface", "permanent": true }, - { "source": "/stacks/api/smart-contracts/map-entry", "destination": "/stacks/rpc-api/smart-contracts/map-entry", "permanent": true }, - { "source": "/stacks/api/smart-contracts/read-only", "destination": "/stacks/rpc-api/smart-contracts/read-only", "permanent": true }, - { "source": "/stacks/api/smart-contracts/source", "destination": "/stacks/rpc-api/smart-contracts/source", "permanent": true }, - { "source": "/stacks/api/transactions/broadcast-transaction", "destination": "/stacks/rpc-api/transactions/broadcast-transaction", "permanent": true }, - { "source": "/metadata/:path*", "destination": "/stacks/token-metadata-api", "permanent": true }, - { "source": "/token-metadata-api/:path*", "destination": "/stacks/token-metadata-api", "permanent": true }, - { "source": "/ordinals/api/:path*", "destination": "/bitcoin/ordinals/api", "permanent": true }, - { "source": "/ordinals/explorer/:path*", "destination": "https://ordinals.hiro.so", "permanent": true }, - { "source": "/api-keys", "destination": "/guides/api-keys", "permanent": true }, - { "source": "/rate-limiting", "destination": "/guides/rate-limiting", "permanent": true }, - { "source": "/changelog", "destination": "/stacks", "permanent": true }, - { "source": "/contributors-guide", "destination": "/guides/contributors-guide", "permanent": true }, - { "source": "/example-apps/:path*", "destination": "/stacks/get-started", "permanent": true }, - { "source": "/build-apps/:path*", "destination": "/stacks", "permanent": true }, - { "source": "/get-started/:path*", "destination": "/stacks/get-started", "permanent": true }, - { "source": "/tutorials/:path*", "destination": "/stacks/get-started", "permanent": true }, - { "source": "/ordhook/:path*", "destination": "/bitcoin/indexer", "permanent": true }, - { "source": "/ordinals-api", "destination": "/bitcoin/ordinals/api", "permanent": true }, - { "source": "/nakamoto/:path*", "destination": "/stacks/nakamoto", "permanent": true }, - { "source": "/nakamoto-api/:path*", "destination": "/stacks/api", "permanent": true }, - { "source": "/hacks/:path*", "destination": "/stacks/hacks", "permanent": true }, - { "source": "/references/:path*", "destination": "/stacks/stacks.js", "permanent": true }, - { "source": "/stacksjs-starters", "destination": "/stacks/stacks.js", "permanent": true }, - { "source": "/ordinals/ordhook/:path*", "destination": "/bitcoin/indexer", "permanent": true }, - { "source": "/ordinals/:path*", "destination": "/bitcoin", "permanent": true } + { "source": "/stacks/clarinet/:path*", "destination": "/tools/clarinet", "permanent": true }, + { "source": "/stacks/clarinet-js-sdk/:path*", "destination": "/tools/clarinet", "permanent": true }, + { "source": "/stacks/chainhook/:path*", "destination": "/tools/chainhook", "permanent": true }, + { "source": "/stacks/stacks.js/:path*", "destination": "/reference/stacks.js", "permanent": true }, + { "source": "/stacks/connect/:path*", "destination": "/reference/stacks.js", "permanent": true }, + { "source": "/stacks/api/:path*", "destination": "/apis/stacks-blockchain-api", "permanent": true }, + { "source": "/stacks/rpc-api/:path*", "destination": "/apis/stacks-blockchain-api", "permanent": true }, + { "source": "/bitcoin/ordinals/:path*", "destination": "/apis/ordinals-api", "permanent": true }, + { "source": "/bitcoin/runes/:path*", "destination": "/apis/runes-api", "permanent": true }, + { "source": "/stacks/:path*", "destination": "/", "permanent": true }, + { "source": "/bitcoin/:path*", "destination": "/", "permanent": true }, + { "source": "/cookbook/:path*", "destination": "/resources/snippets", "permanent": true } ] } \ No newline at end of file