components.best-practices

작성자: coinbase

components.best-practices — AI 에이전트용 설치 가능한 스킬, coinbase/cds에서 게시함.

npx skills add https://github.com/coinbase/cds --skill components.best-practices

React Component Development Rules

Component Development Workflow

  1. Research similar reference components and given requirements/description
  2. Optionally, ask clarifying questions about the component's requirements & behavior
  3. Implement the component with unit tests & stories on web first before proceeding to mobile if both platforms were requested.
  4. Never write figma code connect files unless explicitly instructed to do so.
  5. Follow remaining general coding standards and guidelines you've been given.

Reference Components

These high quality components demonstrate proper use of patterns/conventions:

  • Select (alpha/): generics, controlled/uncontrolled, compound architecture
  • Stepper: props-based defaults, metadata generics, compound components
  • Carousel (web): compound components, imperative handle, context + hook
  • RollingNumber: animation config extraction, measurement patterns
  • SlideButton (mobile): gesture handling, spring animations, accessibility actions

Organization

File Structure

Every main CDS component should live within its own folder:

ComponentName/
├── ComponentName.tsx       # Main component file
├── SubComponent.tsx        # Supporting component (if needed)
├── index.ts                # Re-exports for public API
├── __stories__/            # Storybook stories
│   └── ComponentName.stories.tsx
├── __tests__/              # Unit tests
│   └── ComponentName.test.tsx
├── __figma__/              # Figma Code Connect files
│   └── ComponentName.figma.tsx

Component Categories

Organize components into category folders:

  • buttons - Button, IconButton, SlideButton
  • controls - TextInput, Select, Checkbox, Radio, Switch
  • cards - Card, DataCard, ContentCard
  • overlays - Modal, Toast, Alert, Drawer
  • layout - Box, Stack, Divider
  • typography - Text, Heading
  • icons - Icon
  • navigation - Tabs, Breadcrumb

Component Conventions

  • Memoize: Always memoize components with React's memo HOC
  • refs: All components should accept a ref via React's forwardRef pattern
  • Props documentation: Every prop that does not have a falsy default must have JSDoc comments with @default tags
  • Type exports: Export both a *BaseProps and *Props type (e.g., ButtonBaseProps, ButtonProps)
  • Style overrides: All components MUST support a way to override styles (varries by web/mobile platform)
  • testID: Support testID prop on root element for every component
  • Use design tokens: Reference packages/common/src/core/theme.ts:57-331 as the definitive source for available token names
  • Padding over margin: Use padding in combination with flex gap to achieve spacing instead of margin.

Design Token System

Token Categories

Design tokens are defined in packages/common/src/core/theme.ts:

  • Color: fg, fgMuted, fgInverse, fgPrimary, bgPrimary, bgSecondary, bgNegative, bgPositive, etc.
  • Space: 0, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 5, 6, 7, 8, 9, 10 (8px base unit)
  • IconSize: xs (12px), s (16px), m (24px), l (32px)
  • AvatarSize: s, m, l, xl, xxl, xxxl
  • BorderWidth: 0, 100, 200, 300, 400, 500
  • BorderRadius: 0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000
  • Font: display1-3, title1-4, headline, body, label1-2, caption, legal
  • Shadow: elevation1, elevation2

Semantic Color System

Colors use a spectrum system with hue + step notation:

  • Hues: blue, green, orange, yellow, gray, indigo, pink, purple, red, teal, chartreuse
  • Steps: 0, 5, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100
  • Example: blue60 = Coinbase brand blue (#0052FF)

Semantic tokens map to spectrum colors and adapt to light/dark mode:

  • fgPrimary: blue60 (light) / blue70 (dark)
  • bgPrimary: blue60 (light) / blue70 (dark)
  • bgNegative: red60 (both modes)
  • bgPositive: green60 (both modes)

Space Scale

space: {
  '0': 0,      // 0px
  '0.25': 2,   // 2px
  '0.5': 4,    // 4px
  '0.75': 6,   // 6px
  '1': 8,      // 8px - base unit
  '1.5': 12,   // 12px
  '2': 16,     // 16px
  '3': 24,     // 24px
  '4': 32,     // 32px
  '5': 40,     // 40px
  // ... up to 10 (80px)
}

Component Patterns

Compound Components

  • Break components down into discrete subcomponents (i.e. "slots")
  • Use this pattern for complex components with clear, distinct parts
  • Accept optional subcomponent props with sensible defaults using *Component/Default* naming:
    NavigationComponent = DefaultCarouselNavigation,
    PaginationComponent = DefaultCarouselPagination,
    
  • The names of classNames/styles keys must line up with the name of the subcomponents (e.g. classNames.pagination, styles.pagination).
  • Examples: Stepper, Carousel, Select (alpha)

Benefits:

  • Complete customization without forking
  • Sensible defaults for common use case
  • Exported subcomponents for consumers to customize/wrap themselves

Context + Hook Pattern

  • Pair contexts with use*Context() hooks that throw descriptive errors on misuse:
    export const useCarouselContext = () => {
      const context = useContext(CarouselContext);
      if (!context) throw new Error('useCarouselContext must be used within Carousel');
      return context;
    };
    

Controlled/Uncontrolled Components

  • Support both patterns for input components; validate and throw if consumer mixes them (e.g., provides value but not onChange)
  • Use internal state with prop override: const open = openProp ?? openInternal;

Generics for Type Safety

  • Use generics for components with dynamic value types:
    type SelectComponent = <Type extends SelectType, Value extends string>(
      props: SelectProps<Type, Value>,
    ) => React.ReactElement;
    
  • Examples: Select (alpha), Stepper

BaseProps & Props

  • Component modules encapsulate two prop Types: *BaseProps (platform-agnostic) and *Props (extends BaseProps with platform and component specific properties like className, classNames, styles, etc.)

  • Reuse other components' Types via utilities: Pick being preferred then secondarily Omit/Exclude

  • Compose prop types using Typescript intersections (&) in this order: (1) full types (2) Picks (3) Omits (4) other type literal(s):

    type MyComponentProps = BoxBaseProps &
      Pick<OtherComponentProps, 'someProp'> &
      Omit<AnotherComponentProps, 'otherProp'> & {
        propA: string;
        propB: number;
      };
    
  • When accepting components as props, define the contract types (*Props, *Component) in the main component file. These child component contracts do not use the *BaseProps pattern—only the main component needs BaseProps/Props separation. Default implementations can extend the contract with additional props in their own file:

    // In MyComponent.tsx - defines the contract
    type ChildProps = { id: string; label: ReactNode };
    type ChildComponent = React.FC<ChildProps>;
    
    // In DefaultChild.tsx - extends for default implementation
    type DefaultChildProps = SharedProps & Omit<HStackProps, 'children'> & ChildProps;
    

coinbase의 다른 스킬

git.repo-manager
coinbase
git.repo-manager — AI 에이전트를 위한 설치 가능한 스킬로, coinbase/cds에서 게시했습니다.
official
agentic-wallet
coinbase
awal CLI를 통한 암호화폐 지갑 작업 — 로그인, 잔액 확인, USDC/ETH/POL/SOL 전송, 토큰 거래, 지갑 충전, x402 결제 프로토콜 사용 등
official
authenticate-wallet
coinbase
이메일 OTP 기반 지갑 인증으로 검증 및 상태 확인을 제공합니다. 2단계 로그인 절차: 이메일로 6자리 OTP를 받기 위해 시작한 후, flowId와 코드로 인증을 완료합니다. 명령어 실행 전 셸 인젝션을 방지하기 위해 이메일, flowId, OTP에 대한 입력 검증 규칙이 포함되어 있습니다. 동반 CLI 명령어를 통해 상태 확인, 잔액 조회, 주소 검색 및 지갑 창 접근을 제공합니다. 모든 명령어는 기계 판독 가능한 출력을 위해 --json을 지원합니다...
official
fund
coinbase
Coinbase Onramp 또는 직접 전송을 통해 USDC를 지갑에 입금합니다. 사용자가 사전 설정된 금액($10, $20, $50) 또는 사용자 지정 값을 선택하고 Apple Pay, 직불카드, 은행 송금 또는 Coinbase 계정 자금 조달 중에서 선택할 수 있는 보조 UI를 엽니다. 다양한 결제 수단을 지원하며 정산 시간이 다릅니다: 카드 및 Apple Pay는 즉시, ACH 은행 송금은 1~3일 소요됩니다. Base 네트워크에서 USDC로 자금을 입금하며, 또는 사용자는 npx awal@2.0.3...을 통해 지갑 주소로 직접 USDC를 보낼 수 있습니다.
official
monetize-service
coinbase
x402 프로토콜을 통해 다른 에이전트가 발견하고 결제할 수 있는 유료 API 엔드포인트를 배포합니다. HTTP 402 결제 프로토콜을 사용하여 Base에서 요청당 USDC를 청구하며, 클라이언트는 서명된 트랜잭션으로 결제하고 API 키나 계정이 필요하지 않습니다. 검색 확장을 선언하면 엔드포인트를 x402 Bazaar에 자동으로 등록하여 에이전트가 발견할 수 있도록 합니다. Express 미들웨어를 사용하여 엔드포인트당 여러 가격 계층, 와일드카드 경로 및 여러 결제 옵션을 지원합니다. @x402/express 및 @x402/core 기반으로 구축되었습니다...
official
pay-for-service
coinbase
Base에서 x402 프로토콜을 통해 자동 USDC 결제로 유료 API를 호출합니다. x402 지원 엔드포인트에 HTTP 요청(GET, POST 등)을 실행하며, USDC 결제가 자동으로 처리됩니다. 메서드, JSON 본문, 쿼리 매개변수 및 사용자 정의 헤더를 통해 요청을 사용자 지정할 수 있습니다. 결제 제어 기능이 포함되어 있어 요청당 최대 USDC 금액을 설정하고 상관 ID로 관련 작업을 그룹화할 수 있습니다. 지갑 인증과 충분한 USDC 잔액이 필요하며, 셸을 방지하기 위해 모든 사용자 입력을 검증합니다...
official
query-blockchain-data
coinbase
Base에서 CDP SQL API를 통해 x402로 온체인 블록체인 데이터를 조회합니다. 사용자나 본인이 디코딩된 블록에 대한 온체인 정보를 확인하고자 할 때 사용하세요.
official
query-onchain-data
coinbase
Base에서 SQL을 사용하여 온체인 데이터를 쿼리하고, 쿼리당 x402 결제를 적용합니다. CoinbaseQL을 통해 디코딩된 이벤트, 트랜잭션 및 블록에 접근할 수 있습니다. CoinbaseQL은 조인, CTE, 서브쿼리 및 표준 함수를 지원하는 ClickHouse 기반 SQL 방언입니다. 세 가지 주요 테이블을 사용할 수 있습니다: base.events(디코딩된 스마트 컨트랙트 로그), base.transactions(전체 트랜잭션 데이터), base.blocks(블록 메타데이터). 이벤트 쿼리에서 전체 테이블 스캔을 피하기 위해 인덱싱된 필드(event_signature, address, block_timestamp)에 대한 필터링이 필요합니다.
official